diff --git a/.gitignore b/.gitignore index a9a481ad2..e6e7671f1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,12 @@ -db/bkp -app/subnets/import-subnet/upload/ -app/admin/import-export/upload/ config.php -css/*/images/logo/logo.png +db/bkp functions/scripts/custom/ -api/_lock.txt -app/dashboard/widgets/custom/ -functions/vendor +public/api/_lock.txt +public/app/admin/import-export/upload/ +public/app/dashboard/widgets/custom/ +public/app/subnets/import-subnet/upload/ +public/css/*/images/logo/logo.png +vendor +.continue .idea .vscode diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index d456f432b..000000000 --- a/.gitmodules +++ /dev/null @@ -1,38 +0,0 @@ -# git pull --recurse-submodules -# git submodule update --init --recursive --remote -[submodule "functions/php-saml"] - path = functions/php-saml - url = https://github.com/onelogin/php-saml.git - ignore = all - branch = 3.4.1 -[submodule "functions/PHPMailer"] - path = functions/PHPMailer - url = https://github.com/PHPMailer/PHPMailer.git - ignore = all -[submodule "app/login/captcha"] - path = app/login/captcha - url = https://github.com/dapphp/securimage.git - ignore = all -[submodule "css/assets/bootstrap-select"] - path = css/assets/bootstrap-select - url = https://github.com/silviomoreto/bootstrap-select.git - ignore = all -[submodule "functions/GoogleAuthenticator"] - path = functions/GoogleAuthenticator - url = https://github.com/PHPGangsta/GoogleAuthenticator - ignore = all -[submodule "functions/qrcodejs"] - path = functions/qrcodejs - url = https://github.com/davidshimjs/qrcodejs - ignore = all -[submodule "functions/xmlseclibs"] - path = functions/xmlseclibs - url = https://github.com/robrichards/xmlseclibs.git - ignore = all -[submodule "functions/parsedown"] - path = functions/parsedown - url = https://github.com/erusev/parsedown.git - ignore = all -[submodule "functions/LdapRecord"] - path = functions/LdapRecord - url = https://github.com/DirectoryTree/LdapRecord.git diff --git a/README.md b/README.md index 71440d6b8..5f9e0ba9a 100755 --- a/README.md +++ b/README.md @@ -30,8 +30,8 @@ to be able to display javascript quickly and correctly. phpIPAM has been developed and tested on the following PHP versions.\ The use of untested PHP versions is unsupported and may result in compatibility issues. -- MASTER: See latest 1.x.y release version -- DEVELOP: PHP versions 7.2 to 8.5 +- MASTER: Latest stable release version +- DEVELOP: PHP versions 8.2 to 8.5 ( composer migration, read [UPDATE.md](UPDATE.md) ) - 1.8.x: PHP versions 7.2 to 8.5 - 1.7.x: PHP versions 7.2 to 8.3 - 1.6.x: PHP versions 7.2 to 8.3 diff --git a/UPDATE b/UPDATE deleted file mode 100755 index f487ac973..000000000 --- a/UPDATE +++ /dev/null @@ -1,6 +0,0 @@ -# -# phpipam update instructions -# -please follow this instructions: - -http://phpipam.net/documents/upgrade/ \ No newline at end of file diff --git a/UPDATE.md b/UPDATE.md new file mode 100644 index 000000000..b3bb826a7 --- /dev/null +++ b/UPDATE.md @@ -0,0 +1,203 @@ +# Upgrading phpIPAM + +In general upgrading phpIPAM is a 6 step process: + +1. Check PHP requirements +1. Backup database and `config.php` configuration file +1. Prepare for composer package management [ *upgrading from phpIPAM < v1.9.0 ] +1. Upgrade phpIPAM code +1. Update webserver configuration [ *upgrading from phpIPAM < v1.9.0 ] +1. Upgrade phpIPAM database. + +__Before upgrading ensure you backup your MySQL database__ + +From version 1.7 onwards we have multiple branches available: + +- `master`: Tracks the latest stable release (choose this if unsure) +- `1.x`: Stable 1.x.y point release branches. +- `develop`: Current development version + +Pulling from the `master` git branch will install the latest available stable release, otherwise you need to switch to the required branch. + +# Check PHP requirements + +Check the `Supported PHP versions` section in [README.md](README.md) and ensure your hosting environment is compatible with your chosen version of phpIPAM. + +Check PHP version via GUI +``` +Administration -> Version Check +``` + +Check PHP version via command line + +```console +[root@ipam:/]$ php -v +PHP 8.2.30 (cli) (built: Feb 28 2026 07:07:34) (NTS) +Copyright (c) The PHP Group +Zend Engine v4.2.30, Copyright (c) Zend Technologies + with Zend OPcache v8.2.30, Copyright (c), by Zend Technologies +``` + +Upgrade PHP to a supported version before proceeding with the upgrade. + +# Create backup + +All phpIPAM state is stored in `config.php` and the database, separated from the PHP/HTML code. If you have a MySQL backup and archived `config.php` you can always restore if anything goes wrong during the upgrade process. Before proceeding __backup your SQL database and config.php__ by following these steps. + +via GUI +``` +Administration -> Import / Export -> Prepare MySQL dump +``` + +via command line + +```php +// config.php +/** + * database connection details + ******************************/ +$db['host'] = 'database_host'; +$db['user'] = 'username'; +$db['pass'] = 'password'; +$db['name'] = 'database_name'; +$db['port'] = 3306; +``` + +(adjust directories etc. according to your installation): + +```console +[root@ipam:/]$ cd /var/www/phpipam/ +[root@ipam:/var/www/phpipam]$ mysqldump -h 'database_host' -u 'username' -p 'database_name' >db/bkp/phpipam_migration_backup.db +Enter password: +``` + +Backup your `config.php` file containing database connection settings for phpIPAM. + +# Prepare for composer package management [ * upgrading from phpIPAM < v1.9.0 ] + +phpIPAM versions prior to 1.9.0 use a mix of git submodule and [composer](https://getcomposer.org/) packages installed in the `functions` sub-directory. + +phpIPAM version 1.9.0 and above switched to [composer](https://getcomposer.org/) exclusively for package management in the project root directory. + +Before you upgrade to 1.9.0 or above from 1.8.x or below, remove legacy git submodules by running `git submodule deinit`. + +__Ensure you have a backup your SQL database and config.php before proceeding__ + +(adjust directories etc. according to your installation): + +```console +[root@ipam:/]$ cd /var/www/phpipam +[root@ipam:/var/www/phpipam/]$ git submodule deinit -f --all +Cleared directory 'app/login/captcha' +Cleared directory 'functions/GoogleAuthenticator' +Cleared directory 'functions/LdapRecord' +Cleared directory 'functions/PHPMailer' +Cleared directory 'functions/parsedown' +Cleared directory 'functions/php-saml' +Cleared directory 'functions/qrcodejs' +Cleared directory 'functions/xmlseclibs' +``` + +Additionally remove the legacy `functions/vendor` composer package directory. + +(adjust directories etc. according to your installation): + +```console +[root@ipam:/]$ cd /var/www/phpipam +[root@ipam:/var/www/phpipam/]$ rm -fr functions/vendor +``` + +# Upgrade phpIPAM code + +## git on master 'stable' branch + +If you are using `master` branch on GitHub simply pull the latest stable release and update dependencies: + +(adjust directories etc. according to your installation): + +```console +[root@ipam:/]$ cd /var/www/phpipam +[root@ipam:/var/www/phpipam]$ git pull +[root@ipam:/var/www/phpipam]$ composer install --no-dev --no-scripts +``` + +## git on specific branch [ * phpIPAM >= v1.9.0 ] + +If you use specific branch, pull down new code, switch to desired branch and update dependencies; + +(adjust directories etc. according to your installation): + +```console +[root@ipam:/]$ cd /var/www/phpipam +[root@ipam:/var/www/phpipam]$ git pull +[root@ipam:/var/www/phpipam]$ git checkout -b 1.9 origin/1.9 +[root@ipam:/var/www/phpipam]$ composer install --no-dev --no-scripts +``` + +## git on specific branch [ * phpIPAM < v1.9.0 ] + +If you use specific branch, pull down new code, switch to desired branch and update dependencies; + +(adjust directories etc. according to your installation): + +```console +[root@ipam:/]$ cd /var/www/phpipam +[root@ipam:/var/www/phpipam]$ git pull +[root@ipam:/var/www/phpipam]$ git checkout -b 1.8 origin/1.8 +[root@ipam:/var/www/phpipam]$ git submodule update --init --recursive +[root@ipam:/var/www/phpipam]$ cd functions +[root@ipam:/var/www/phpipam/functions]$ composer install --no-dev --no-scripts +``` + +# Manual release upgrade + +To manually extract new phpipam release head over to [https://github.com/phpipam/phpipam/releases](https://github.com/phpipam/phpipam/releases), check assets and download files. Than extract new code and copy over old config.php file. + +(adjust directories etc. according to your installation): + +```console +[root@ipam:/]$ cd /var/www/phpipam +[root@ipam:/var/www/phpipam]$ tar -xvf phpipam-v1.9.0.tgz +[root@ipam:/var/www/phpipam]$ cp /backup/location/config.php /var/www/phpipam +[root@ipam:/var/www/phpipam]$ composer install --no-dev --no-scripts +``` + +# Update webserver configuration [ * upgrading from phpIPAM < v1.9.0 ] + +phpIPAM v1.9.0 relocated all HTML application code from the project root directory into the \"public\" sub-directory. + +When upgrading from phpIPAM v1.8.x or below, update your webserver, reverse-proxy or load-balancer configuration to point to the new HTML location. + +# Upgrade phpIPAM database + +To upgrade your phpIPAM database to latest version choose from the multiple options presented on the browser upgrade page: + +## Automatic database upgrade + +Open browser and follow upgrade procedure. + +## Manual query import + +In case you have some problems you can manually import each MySQL update statement directly into the database. All upgrade queries are available by following the instructions in `db/UPDATE.sql`, start from the statement that contains a version higher than current. + +Alternatively you can use the script below to output the queries needed to upgrade the MySQL database manually. + +Assuming your old version is v1.5: + +```console +[root@ipam:/]$ cd /var/www/phpipam +[root@ipam:/var/www/phpipam]$ php functions/upgrade_queries.php 1.5 +``` + +# Restore old installation and database + +In case anything goes wrong the restore procedure is simple: + +- Extract old code (restore version you had prior to upgrade) +- Copy over config.php +- Load old database backed up before starting upgrade + +```console +[root@ipam:/var/www/phpipam]$ mysql -h `database_host` -u `username` -p `database_name` =5.4" + }, + "suggest": { + "ext-pdo": "For database storage support", + "ext-pdo_mysql": "For MySQL database support", + "ext-pdo_sqlite": "For SQLite3 database support" + }, + "type": "library", + "autoload": { + "psr-4": { + "Securimage\\": "./" + }, + "classmap": [ + "securimage.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Drew Phillips", + "email": "drew@drew-phillips.com" + } + ], + "description": "PHP CAPTCHA Library", + "homepage": "https://www.phpcaptcha.org", + "keywords": [ + "Forms", + "anti-spam", + "captcha", + "security" + ], + "support": { + "issues": "https://github.com/dapphp/securimage/issues", + "source": "https://github.com/dapphp/securimage/tree/4.0.2" + }, + "abandoned": true, + "time": "2020-05-30T10:05:48+00:00" + }, + { + "name": "dasprid/enum", + "version": "1.0.7", + "source": { + "type": "git", + "url": "https://github.com/DASPRiD/Enum.git", + "reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/DASPRiD/Enum/zipball/b5874fa9ed0043116c72162ec7f4fb50e02e7cce", + "reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce", + "shasum": "" + }, + "require": { + "php": ">=7.1 <9.0" + }, + "require-dev": { + "phpunit/phpunit": "^7 || ^8 || ^9 || ^10 || ^11", + "squizlabs/php_codesniffer": "*" + }, + "type": "library", + "autoload": { + "psr-4": { + "DASPRiD\\Enum\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-2-Clause" + ], + "authors": [ + { + "name": "Ben Scholzen 'DASPRiD'", + "email": "mail@dasprids.de", + "homepage": "https://dasprids.de/", + "role": "Developer" + } + ], + "description": "PHP 7.1 enum implementation", + "keywords": [ + "enum", + "map" + ], + "support": { + "issues": "https://github.com/DASPRiD/Enum/issues", + "source": "https://github.com/DASPRiD/Enum/tree/1.0.7" + }, + "time": "2025-09-16T12:23:56+00:00" + }, + { + "name": "erusev/parsedown", + "version": "1.8.0", + "source": { + "type": "git", + "url": "https://github.com/erusev/parsedown.git", + "reference": "96baaad00f71ba04d76e45b4620f54d3beabd6f7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/erusev/parsedown/zipball/96baaad00f71ba04d76e45b4620f54d3beabd6f7", + "reference": "96baaad00f71ba04d76e45b4620f54d3beabd6f7", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.5|^8.5|^9.6" + }, + "type": "library", + "autoload": { + "psr-0": { + "Parsedown": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "description": "Parser for Markdown.", + "homepage": "http://parsedown.org", + "keywords": [ + "markdown", + "parser" + ], + "support": { + "issues": "https://github.com/erusev/parsedown/issues", + "source": "https://github.com/erusev/parsedown/tree/1.8.0" + }, + "funding": [ + { + "url": "https://github.com/erusev", + "type": "github" + } + ], + "time": "2026-02-16T11:41:01+00:00" + }, + { + "name": "firehed/cbor", + "version": "0.1.0", + "source": { + "type": "git", + "url": "https://github.com/Firehed/cbor-php.git", + "reference": "eef67b1b5fdf90a3688fc8d9d13afdaf342c4b80" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Firehed/cbor-php/zipball/eef67b1b5fdf90a3688fc8d9d13afdaf342c4b80", + "reference": "eef67b1b5fdf90a3688fc8d9d13afdaf342c4b80", + "shasum": "" + }, + "require-dev": { + "phpunit/phpunit": "^8.1" + }, + "suggest": { + "ext-bcmath": "Enables parsing of very large values" + }, + "type": "library", + "autoload": { + "psr-4": { + "Firehed\\CBOR\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Eric Stern", + "email": "eric@ericstern.com" + } + ], + "description": "CBOR decoder", + "homepage": "https://github.com/Firehed/CBOR", + "keywords": [ + "cbor" + ], + "support": { + "issues": "https://github.com/Firehed/cbor-php/issues", + "source": "https://github.com/Firehed/cbor-php/tree/master" + }, + "time": "2019-05-14T06:31:13+00:00" + }, + { + "name": "firehed/webauthn", + "version": "0.9.1", + "source": { + "type": "git", + "url": "https://github.com/Firehed/webauthn-php.git", + "reference": "1e403f080a10085657a4f32118e545bed7f54dbb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Firehed/webauthn-php/zipball/1e403f080a10085657a4f32118e545bed7f54dbb", + "reference": "1e403f080a10085657a4f32118e545bed7f54dbb", + "shasum": "" + }, + "require": { + "ext-gmp": "*", + "ext-hash": "*", + "ext-openssl": "*", + "firehed/cbor": "^0.1.0", + "php": "^8.2", + "sop/asn1": "^4.1.2" + }, + "require-dev": { + "mheap/phpunit-github-actions-printer": "^1.5", + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^11", + "squizlabs/php_codesniffer": "^3.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Firehed\\WebAuthn\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Eric Stern", + "email": "eric@ericstern.com" + } + ], + "description": "Support passkeys and Web Authentication", + "keywords": [ + "2fa", + "MFA", + "fido", + "passkeys", + "u2f", + "web authentication", + "webauthn" + ], + "support": { + "issues": "https://github.com/Firehed/webauthn-php/issues", + "source": "https://github.com/Firehed/webauthn-php/tree/0.9.1" + }, + "funding": [ + { + "url": "https://github.com/sponsors/Firehed", + "type": "github" + }, + { + "url": "https://www.snapauth.app", + "type": "other" + } + ], + "time": "2026-03-15T19:03:55+00:00" + }, + { + "name": "onelogin/php-saml", + "version": "4.3.1", + "source": { + "type": "git", + "url": "https://github.com/SAML-Toolkits/php-saml.git", + "reference": "b009f160e4ac11f49366a45e0d45706b48429353" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/SAML-Toolkits/php-saml/zipball/b009f160e4ac11f49366a45e0d45706b48429353", + "reference": "b009f160e4ac11f49366a45e0d45706b48429353", + "shasum": "" + }, + "require": { + "php": ">=7.3", + "robrichards/xmlseclibs": ">=3.1.4" + }, + "require-dev": { + "pdepend/pdepend": "^2.8.0", + "php-coveralls/php-coveralls": "^2.0", + "phploc/phploc": "^4.0 || ^5.0 || ^6.0 || ^7.0", + "phpunit/phpunit": "^9.5", + "sebastian/phpcpd": "^4.0 || ^5.0 || ^6.0 ", + "squizlabs/php_codesniffer": "^3.5.8" + }, + "suggest": { + "ext-curl": "Install curl lib to be able to use the IdPMetadataParser for parsing remote XMLs", + "ext-dom": "Install xml lib", + "ext-openssl": "Install openssl lib in order to handle with x509 certs (require to support sign and encryption)", + "ext-zlib": "Install zlib" + }, + "type": "library", + "autoload": { + "psr-4": { + "OneLogin\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHP SAML Toolkit", + "homepage": "https://github.com/SAML-Toolkits/php-saml", + "keywords": [ + "Federation", + "SAML2", + "SSO", + "identity", + "saml" + ], + "support": { + "email": "sixto.martin.garcia@gmail.com", + "issues": "https://github.com/onelogin/SAML-Toolkits/issues", + "source": "https://github.com/onelogin/SAML-Toolkits/" + }, + "funding": [ + { + "url": "https://github.com/SAML-Toolkits", + "type": "github" + } + ], + "time": "2025-12-09T10:50:49+00:00" + }, + { + "name": "phpgangsta/googleauthenticator", + "version": "dev-master", + "source": { + "type": "git", + "url": "https://github.com/PHPGangsta/GoogleAuthenticator.git", + "reference": "505c2af8337b559b33557f37cda38e5f843f3768" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPGangsta/GoogleAuthenticator/zipball/505c2af8337b559b33557f37cda38e5f843f3768", + "reference": "505c2af8337b559b33557f37cda38e5f843f3768", + "shasum": "" + }, + "require": { + "php": ">=5.3" + }, + "default-branch": true, + "type": "library", + "autoload": { + "classmap": [ + "PHPGangsta/GoogleAuthenticator.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-4-Clause" + ], + "authors": [ + { + "name": "Michael Kliewe", + "email": "info@phpgangsta.de", + "homepage": "http://www.phpgangsta.de/", + "role": "Developer" + } + ], + "description": "Google Authenticator 2-factor authentication", + "keywords": [ + "googleauthenticator", + "rfc6238", + "totp" + ], + "support": { + "issues": "https://github.com/PHPGangsta/GoogleAuthenticator/issues", + "source": "https://github.com/PHPGangsta/GoogleAuthenticator" + }, + "time": "2019-03-20T00:55:58+00:00" + }, + { + "name": "phpmailer/phpmailer", + "version": "v7.0.2", + "source": { + "type": "git", + "url": "https://github.com/PHPMailer/PHPMailer.git", + "reference": "ebf1655bd5b99b3f97e1a3ec0a69e5f4cd7ea088" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/ebf1655bd5b99b3f97e1a3ec0a69e5f4cd7ea088", + "reference": "ebf1655bd5b99b3f97e1a3ec0a69e5f4cd7ea088", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-filter": "*", + "ext-hash": "*", + "php": ">=5.5.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "^1.0", + "doctrine/annotations": "^1.2.6 || ^1.13.3", + "php-parallel-lint/php-console-highlighter": "^1.0.0", + "php-parallel-lint/php-parallel-lint": "^1.3.2", + "phpcompatibility/php-compatibility": "^10.0.0@dev", + "squizlabs/php_codesniffer": "^3.13.5", + "yoast/phpunit-polyfills": "^1.0.4" + }, + "suggest": { + "decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication", + "directorytree/imapengine": "For uploading sent messages via IMAP, see gmail example", + "ext-imap": "Needed to support advanced email address parsing according to RFC822", + "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", + "ext-openssl": "Needed for secure SMTP sending and DKIM signing", + "greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication", + "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", + "league/oauth2-google": "Needed for Google XOAUTH2 authentication", + "psr/log": "For optional PSR-3 debug logging", + "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)", + "thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication" + }, + "type": "library", + "autoload": { + "psr-4": { + "PHPMailer\\PHPMailer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-only" + ], + "authors": [ + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "support": { + "issues": "https://github.com/PHPMailer/PHPMailer/issues", + "source": "https://github.com/PHPMailer/PHPMailer/tree/v7.0.2" + }, + "funding": [ + { + "url": "https://github.com/Synchro", + "type": "github" + } + ], + "time": "2026-01-09T18:02:33+00:00" + }, + { + "name": "robrichards/xmlseclibs", + "version": "3.1.5", + "source": { + "type": "git", + "url": "https://github.com/robrichards/xmlseclibs.git", + "reference": "03062be78178cbb5e8f605cd255dc32a14981f92" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/robrichards/xmlseclibs/zipball/03062be78178cbb5e8f605cd255dc32a14981f92", + "reference": "03062be78178cbb5e8f605cd255dc32a14981f92", + "shasum": "" + }, + "require": { + "ext-openssl": "*", + "php": ">= 5.4" + }, + "type": "library", + "autoload": { + "psr-4": { + "RobRichards\\XMLSecLibs\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "A PHP library for XML Security", + "homepage": "https://github.com/robrichards/xmlseclibs", + "keywords": [ + "security", + "signature", + "xml", + "xmldsig" + ], + "support": { + "issues": "https://github.com/robrichards/xmlseclibs/issues", + "source": "https://github.com/robrichards/xmlseclibs/tree/3.1.5" + }, + "time": "2026-03-13T10:31:56+00:00" + }, + { + "name": "sop/asn1", + "version": "4.1.2", + "source": { + "type": "git", + "url": "https://github.com/sop/asn1.git", + "reference": "a652a5c4db949e4e1d065820aeef68c297ce404d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sop/asn1/zipball/a652a5c4db949e4e1d065820aeef68c297ce404d", + "reference": "a652a5c4db949e4e1d065820aeef68c297ce404d", + "shasum": "" + }, + "require": { + "ext-gmp": "*", + "ext-mbstring": "*", + "php": ">=7.2" + }, + "require-dev": { + "phpunit/phpunit": "^8.1" + }, + "type": "library", + "autoload": { + "psr-4": { + "Sop\\ASN1\\": "lib/ASN1/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Joni Kollani", + "email": "joni.kollani@gmail.com", + "role": "Developer" + } + ], + "description": "A PHP library for X.690 ASN.1 DER encoding and decoding.", + "homepage": "https://github.com/sop/asn1", + "keywords": [ + "DER", + "asn.1", + "asn1", + "x.690", + "x690" + ], + "support": { + "issues": "https://github.com/sop/asn1/issues", + "source": "https://github.com/sop/asn1/tree/4.1.2" + }, + "time": "2025-01-08T13:56:59+00:00" + } + ], + "packages-dev": [ + { + "name": "dealerdirect/phpcodesniffer-composer-installer", + "version": "v1.2.0", + "source": { + "type": "git", + "url": "https://github.com/PHPCSStandards/composer-installer.git", + "reference": "845eb62303d2ca9b289ef216356568ccc075ffd1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCSStandards/composer-installer/zipball/845eb62303d2ca9b289ef216356568ccc075ffd1", + "reference": "845eb62303d2ca9b289ef216356568ccc075ffd1", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^2.2", + "php": ">=5.4", + "squizlabs/php_codesniffer": "^3.1.0 || ^4.0" + }, + "require-dev": { + "composer/composer": "^2.2", + "ext-json": "*", + "ext-zip": "*", + "php-parallel-lint/php-parallel-lint": "^1.4.0", + "phpcompatibility/php-compatibility": "^9.0 || ^10.0.0@dev", + "yoast/phpunit-polyfills": "^1.0" + }, + "type": "composer-plugin", + "extra": { + "class": "PHPCSStandards\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin" + }, + "autoload": { + "psr-4": { + "PHPCSStandards\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Franck Nijhof", + "email": "opensource@frenck.dev", + "homepage": "https://frenck.dev", + "role": "Open source developer" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/composer-installer/graphs/contributors" + } + ], + "description": "PHP_CodeSniffer Standards Composer Installer Plugin", + "keywords": [ + "PHPCodeSniffer", + "PHP_CodeSniffer", + "code quality", + "codesniffer", + "composer", + "installer", + "phpcbf", + "phpcs", + "plugin", + "qa", + "quality", + "standard", + "standards", + "style guide", + "stylecheck", + "tests" + ], + "support": { + "issues": "https://github.com/PHPCSStandards/composer-installer/issues", + "security": "https://github.com/PHPCSStandards/composer-installer/security/policy", + "source": "https://github.com/PHPCSStandards/composer-installer" + }, + "funding": [ + { + "url": "https://github.com/PHPCSStandards", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + }, + { + "url": "https://thanks.dev/u/gh/phpcsstandards", + "type": "thanks_dev" + } + ], + "time": "2025-11-11T04:32:07+00:00" + }, + { + "name": "driftingly/rector-laravel", + "version": "2.3.0", + "source": { + "type": "git", + "url": "https://github.com/driftingly/rector-laravel.git", + "reference": "3c1c13f335b3b4d1a1f944a8ea194020044871ed" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/driftingly/rector-laravel/zipball/3c1c13f335b3b4d1a1f944a8ea194020044871ed", + "reference": "3c1c13f335b3b4d1a1f944a8ea194020044871ed", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0", + "rector/rector": "^2.2.7", + "webmozart/assert": "^1.11 || ^2.0" + }, + "type": "rector-extension", + "autoload": { + "psr-4": { + "RectorLaravel\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Rector upgrades rules for Laravel Framework", + "support": { + "issues": "https://github.com/driftingly/rector-laravel/issues", + "source": "https://github.com/driftingly/rector-laravel/tree/2.3.0" + }, + "time": "2026-04-08T10:52:44+00:00" + }, + { + "name": "laravel/pint", + "version": "v1.29.1", + "source": { + "type": "git", + "url": "https://github.com/laravel/pint.git", + "reference": "0770e9b7fafd50d4586881d456d6eb41c9247a80" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/pint/zipball/0770e9b7fafd50d4586881d456d6eb41c9247a80", + "reference": "0770e9b7fafd50d4586881d456d6eb41c9247a80", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-mbstring": "*", + "ext-tokenizer": "*", + "ext-xml": "*", + "php": "^8.2.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.95.1", + "illuminate/view": "^12.56.0", + "larastan/larastan": "^3.9.6", + "laravel-zero/framework": "^12.1.0", + "mockery/mockery": "^1.6.12", + "nunomaduro/termwind": "^2.4.0", + "pestphp/pest": "^3.8.6", + "shipfastlabs/agent-detector": "^1.1.3" + }, + "bin": [ + "builds/pint" + ], + "type": "project", + "autoload": { + "psr-4": { + "App\\": "app/", + "Database\\Seeders\\": "database/seeders/", + "Database\\Factories\\": "database/factories/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nuno Maduro", + "email": "enunomaduro@gmail.com" + } + ], + "description": "An opinionated code formatter for PHP.", + "homepage": "https://laravel.com", + "keywords": [ + "dev", + "format", + "formatter", + "lint", + "linter", + "php" + ], + "support": { + "issues": "https://github.com/laravel/pint/issues", + "source": "https://github.com/laravel/pint" + }, + "time": "2026-04-20T15:26:14+00:00" + }, + { + "name": "phpcompatibility/php-compatibility", + "version": "dev-develop", + "source": { + "type": "git", + "url": "https://github.com/PHPCompatibility/PHPCompatibility.git", + "reference": "aba7b5d3aec1ea5311e912efece301e2ef0b6338" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCompatibility/PHPCompatibility/zipball/aba7b5d3aec1ea5311e912efece301e2ef0b6338", + "reference": "aba7b5d3aec1ea5311e912efece301e2ef0b6338", + "shasum": "" + }, + "require": { + "php": ">=7.2", + "phpcsstandards/phpcsutils": "^1.1.2", + "squizlabs/php_codesniffer": "^4.0.1" + }, + "replace": { + "wimg/php-compatibility": "*" + }, + "require-dev": { + "php-parallel-lint/php-console-highlighter": "^1.0.0", + "php-parallel-lint/php-parallel-lint": "^1.4.0", + "phpcsstandards/phpcsdevcs": "^1.2.0", + "phpcsstandards/phpcsdevtools": "^1.2.3", + "phpunit/phpunit": "^8.0 || ^9.3.4 || ^10.5.32 || ^11.3.3", + "yoast/phpunit-polyfills": "^1.1.5 || ^2.0.5 || ^3.1.0" + }, + "default-branch": true, + "type": "phpcodesniffer-standard", + "extra": { + "branch-alias": { + "dev-master": "9.x-dev", + "dev-develop": "10.x-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0-or-later" + ], + "authors": [ + { + "name": "Wim Godden", + "homepage": "https://github.com/wimg", + "role": "lead" + }, + { + "name": "Juliette Reinders Folmer", + "homepage": "https://github.com/jrfnl", + "role": "lead" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCompatibility/PHPCompatibility/graphs/contributors" + } + ], + "description": "A set of sniffs for PHP_CodeSniffer that checks for PHP cross-version compatibility.", + "homepage": "https://techblog.wimgodden.be/tag/codesniffer/", + "keywords": [ + "compatibility", + "phpcs", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHPCompatibility/PHPCompatibility/issues", + "security": "https://github.com/PHPCompatibility/PHPCompatibility/security/policy", + "source": "https://github.com/PHPCompatibility/PHPCompatibility" + }, + "funding": [ + { + "url": "https://github.com/PHPCompatibility", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + }, + { + "url": "https://thanks.dev/u/gh/phpcompatibility", + "type": "thanks_dev" + } + ], + "time": "2026-04-06T00:21:12+00:00" + }, + { + "name": "phpcsstandards/phpcsutils", + "version": "1.2.2", + "source": { + "type": "git", + "url": "https://github.com/PHPCSStandards/PHPCSUtils.git", + "reference": "c216317e96c8b3f5932808f9b0f1f7a14e3bbf55" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCSStandards/PHPCSUtils/zipball/c216317e96c8b3f5932808f9b0f1f7a14e3bbf55", + "reference": "c216317e96c8b3f5932808f9b0f1f7a14e3bbf55", + "shasum": "" + }, + "require": { + "dealerdirect/phpcodesniffer-composer-installer": "^0.4.1 || ^0.5 || ^0.6.2 || ^0.7 || ^1.0", + "php": ">=5.4", + "squizlabs/php_codesniffer": "^3.13.5 || ^4.0.1" + }, + "require-dev": { + "ext-filter": "*", + "php-parallel-lint/php-console-highlighter": "^1.0", + "php-parallel-lint/php-parallel-lint": "^1.4.0", + "phpcsstandards/phpcsdevcs": "^1.2.0", + "yoast/phpunit-polyfills": "^1.1.0 || ^2.0.0 || ^3.0.0" + }, + "type": "phpcodesniffer-standard", + "extra": { + "branch-alias": { + "dev-stable": "1.x-dev", + "dev-develop": "1.x-dev" + } + }, + "autoload": { + "classmap": [ + "PHPCSUtils/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0-or-later" + ], + "authors": [ + { + "name": "Juliette Reinders Folmer", + "homepage": "https://github.com/jrfnl", + "role": "lead" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/PHPCSUtils/graphs/contributors" + } + ], + "description": "A suite of utility functions for use with PHP_CodeSniffer", + "homepage": "https://phpcsutils.com/", + "keywords": [ + "PHP_CodeSniffer", + "phpcbf", + "phpcodesniffer-standard", + "phpcs", + "phpcs3", + "phpcs4", + "standards", + "static analysis", + "tokens", + "utility" + ], + "support": { + "docs": "https://phpcsutils.com/", + "issues": "https://github.com/PHPCSStandards/PHPCSUtils/issues", + "security": "https://github.com/PHPCSStandards/PHPCSUtils/security/policy", + "source": "https://github.com/PHPCSStandards/PHPCSUtils" + }, + "funding": [ + { + "url": "https://github.com/PHPCSStandards", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + }, + { + "url": "https://thanks.dev/u/gh/phpcsstandards", + "type": "thanks_dev" + } + ], + "time": "2025-12-08T14:27:58+00:00" + }, + { + "name": "phpstan/phpstan", + "version": "2.1.53", + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/ef67586798c003274797b288a68b221e4270dca7", + "reference": "ef67586798c003274797b288a68b221e4270dca7", + "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": "2026-04-28T16:09:00+00:00" + }, + { + "name": "rector/rector", + "version": "2.4.2", + "source": { + "type": "git", + "url": "https://github.com/rectorphp/rector.git", + "reference": "e645b6463c6a88ea5b44b17d3387d35a912c7946" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/e645b6463c6a88ea5b44b17d3387d35a912c7946", + "reference": "e645b6463c6a88ea5b44b17d3387d35a912c7946", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0", + "phpstan/phpstan": "^2.1.48" + }, + "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", + "homepage": "https://getrector.com/", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], + "support": { + "issues": "https://github.com/rectorphp/rector/issues", + "source": "https://github.com/rectorphp/rector/tree/2.4.2" + }, + "funding": [ + { + "url": "https://github.com/tomasvotruba", + "type": "github" + } + ], + "time": "2026-04-16T13:07:34+00:00" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git", + "reference": "0525c73950de35ded110cffafb9892946d7771b5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/0525c73950de35ded110cffafb9892946d7771b5", + "reference": "0525c73950de35ded110cffafb9892946d7771b5", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=7.2.0" + }, + "require-dev": { + "phpunit/phpunit": "^8.4.0 || ^9.3.4 || ^10.5.32 || 11.3.3 - 11.5.28 || ^11.5.31" + }, + "bin": [ + "bin/phpcbf", + "bin/phpcs" + ], + "type": "library", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "Former lead" + }, + { + "name": "Juliette Reinders Folmer", + "role": "Current lead" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer/graphs/contributors" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHPCSStandards/PHP_CodeSniffer/issues", + "security": "https://github.com/PHPCSStandards/PHP_CodeSniffer/security/policy", + "source": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "wiki": "https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki" + }, + "funding": [ + { + "url": "https://github.com/PHPCSStandards", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + }, + { + "url": "https://thanks.dev/u/gh/phpcsstandards", + "type": "thanks_dev" + } + ], + "time": "2025-11-10T16:43:36+00:00" + }, + { + "name": "webmozart/assert", + "version": "2.3.0", + "source": { + "type": "git", + "url": "https://github.com/webmozarts/assert.git", + "reference": "eb0d790f735ba6cff25c683a85a1da0eadeff9e4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webmozarts/assert/zipball/eb0d790f735ba6cff25c683a85a1da0eadeff9e4", + "reference": "eb0d790f735ba6cff25c683a85a1da0eadeff9e4", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-date": "*", + "ext-filter": "*", + "php": "^8.2" + }, + "suggest": { + "ext-intl": "", + "ext-simplexml": "", + "ext-spl": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-feature/2-0": "2.0-dev" + } + }, + "autoload": { + "psr-4": { + "Webmozart\\Assert\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + }, + { + "name": "Woody Gilk", + "email": "woody.gilk@gmail.com" + } + ], + "description": "Assertions to validate method input/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "support": { + "issues": "https://github.com/webmozarts/assert/issues", + "source": "https://github.com/webmozarts/assert/tree/2.3.0" + }, + "time": "2026-04-11T10:33:05+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": { + "phpgangsta/googleauthenticator": 20, + "phpcompatibility/php-compatibility": 20 + }, + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": "^8.2", + "ext-ctype": "*", + "ext-curl": "*", + "ext-dom": "*", + "ext-filter": "*", + "ext-gd": "*", + "ext-gettext": "*", + "ext-gmp": "*", + "ext-iconv": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-openssl": "*", + "ext-pcre": "*", + "ext-pdo": "*", + "ext-pdo_mysql": "*", + "ext-session": "*", + "ext-sockets": "*" + }, + "platform-dev": [], + "platform-overrides": { + "php": "8.2" + }, + "plugin-api-version": "2.3.0" +} diff --git a/functions/composer.phar b/composer.phar similarity index 100% rename from functions/composer.phar rename to composer.phar diff --git a/config.dist.php b/config.dist.php index 2e7b4e5b5..9f8efb350 100755 --- a/config.dist.php +++ b/config.dist.php @@ -91,14 +91,14 @@ $debugging = false; /* - * API Crypt security provider. "mcrypt" or "openssl*" + * API Crypt security provider."openssl-*" * Supported methods: * openssl-128-cbc (alias openssl, openssl-128) *default * openssl-256-cbc (alias openssl-256) * * default as of 1.3.2 "openssl-128-cbc" ******************************/ -// $api_crypt_encryption_library = "mcrypt"; +// $api_crypt_encryption_library = "openssl-128-cbc"; /** @@ -164,7 +164,7 @@ /** * Permit private subpages - private apps under /app/tools/custom//index.php ******************************/ -$private_subpages = array(); +$private_subpages = []; /** * proxy connection details diff --git a/db/SCHEMA.sql b/db/SCHEMA.sql index 054584321..de8688875 100755 --- a/db/SCHEMA.sql +++ b/db/SCHEMA.sql @@ -1102,5 +1102,5 @@ CREATE TABLE `nominatim_cache` ( # Dump of table -- for autofix comment, leave as it is # ------------------------------------------------------------ -UPDATE `settings` SET `version` = "1.8"; +UPDATE `settings` SET `version` = "1.9"; UPDATE `settings` SET `dbversion` = 46; diff --git a/db/bkp/.htaccess b/db/bkp/.htaccess deleted file mode 100755 index ede920ebe..000000000 --- a/db/bkp/.htaccess +++ /dev/null @@ -1,4 +0,0 @@ - - Order Allow,Deny - Deny from all - \ No newline at end of file diff --git a/functions/GoogleAuthenticator b/functions/GoogleAuthenticator deleted file mode 160000 index 505c2af83..000000000 --- a/functions/GoogleAuthenticator +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 505c2af8337b559b33557f37cda38e5f843f3768 diff --git a/functions/LdapRecord b/functions/LdapRecord deleted file mode 160000 index 17e1daca0..000000000 --- a/functions/LdapRecord +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 17e1daca04bfee46116eabd1587ed754d0c00877 diff --git a/functions/PEAR/Net/DNS2.php b/functions/PEAR/Net/DNS2.php index 1f1dd4937..393c62b08 100644 --- a/functions/PEAR/Net/DNS2.php +++ b/functions/PEAR/Net/DNS2.php @@ -297,7 +297,7 @@ static public function autoload($name) // if (strncmp($name, 'Net_DNS2', 8) == 0) { - include dirname(__FILE__) . '/../' . str_replace('_', '/', $name) . '.php'; + include __DIR__ . '/../' . str_replace('_', '/', $name) . '.php'; } return; @@ -417,7 +417,7 @@ public function setServers($nameservers) // if we don't have a domain, but we have a search list, then // take the first entry on the search list as the domain // - if ( (strlen($this->domain) == 0) + if ( (strlen((string) $this->domain) == 0) && (count($this->search_list) > 0) ) { $this->domain = $this->search_list[0]; @@ -838,7 +838,7 @@ public static function expandIPv6($_address) { $hex = unpack('H*hex', inet_pton($_address)); - return substr(preg_replace('/([A-f0-9]{4})/', "$1:", $hex['hex']), 0, -1); + return substr((string) preg_replace('/([A-f0-9]{4})/', "$1:", (string) $hex['hex']), 0, -1); } /** @@ -1093,7 +1093,7 @@ private function sendTCPRequest($_ns, $_data, $_axfr = false) // // if a local IP address / port is set, then add it // - if (strlen($this->local_host) > 0) { + if (strlen((string) $this->local_host) > 0) { $this->sock[Net_DNS2_Socket::SOCK_STREAM][$_ns]->bindAddress( $this->local_host, $this->local_port @@ -1303,7 +1303,7 @@ private function sendUDPRequest($_ns, $_data) // // if a local IP address / port is set, then add it // - if (strlen($this->local_host) > 0) { + if (strlen((string) $this->local_host) > 0) { $this->sock[Net_DNS2_Socket::SOCK_DGRAM][$_ns]->bindAddress( $this->local_host, $this->local_port diff --git a/functions/PEAR/Net/DNS2/BitMap.php b/functions/PEAR/Net/DNS2/BitMap.php index b68786fac..ed2a1b0e3 100644 --- a/functions/PEAR/Net/DNS2/BitMap.php +++ b/functions/PEAR/Net/DNS2/BitMap.php @@ -115,7 +115,7 @@ public static function arrayToBitMap(array $data) foreach ($data as $rr) { - $rr = strtoupper($rr); + $rr = strtoupper((string) $rr); // // get the type id for the RR diff --git a/functions/PEAR/Net/DNS2/Cache.php b/functions/PEAR/Net/DNS2/Cache.php index 01740a25f..d041cd3b6 100644 --- a/functions/PEAR/Net/DNS2/Cache.php +++ b/functions/PEAR/Net/DNS2/Cache.php @@ -77,7 +77,7 @@ public function get($key) if (isset($this->cache_data[$key])) { if ($this->cache_serializer == 'json') { - return json_decode($this->cache_data[$key]['object']); + return json_decode((string) $this->cache_data[$key]['object']); } else { return unserialize($this->cache_data[$key]['object']); } diff --git a/functions/PEAR/Net/DNS2/Cache/File.php b/functions/PEAR/Net/DNS2/Cache/File.php index a0e0b7bf7..a7ddf3019 100644 --- a/functions/PEAR/Net/DNS2/Cache/File.php +++ b/functions/PEAR/Net/DNS2/Cache/File.php @@ -116,7 +116,7 @@ public function __destruct() // // if there's no cache file set, then there's nothing to do // - if (strlen($this->cache_file) == 0) { + if (strlen((string) $this->cache_file) == 0) { return; } @@ -182,7 +182,7 @@ public function __destruct() // // write the file contents // - fwrite($fp, $data); + fwrite($fp, (string) $data); } // diff --git a/functions/PEAR/Net/DNS2/Cache/Shm.php b/functions/PEAR/Net/DNS2/Cache/Shm.php index 5308b53fc..73537d750 100644 --- a/functions/PEAR/Net/DNS2/Cache/Shm.php +++ b/functions/PEAR/Net/DNS2/Cache/Shm.php @@ -23,8 +23,9 @@ */ class Net_DNS2_Cache_Shm extends Net_DNS2_Cache { - /* + /** * resource id of the shared memory cache + * @var resource|false */ private $_cache_id = false; @@ -151,7 +152,7 @@ public function __destruct() // // if there's no cache file set, then there's nothing to do // - if (strlen($this->cache_file) == 0) { + if (strlen((string) $this->cache_file) == 0) { return; } @@ -251,10 +252,12 @@ public function __destruct() $o = shmop_write($this->_cache_id, $data, 0); } - // // close the segment - // - shmop_close($this->_cache_id); + if (version_compare(PHP_VERSION, '8.0.0', '<')) { + // phpcs:ignore + shmop_close($this->_cache_id); + // phpcs:ignore + } // // unlock diff --git a/functions/PEAR/Net/DNS2/Exception.php b/functions/PEAR/Net/DNS2/Exception.php index 3b9e93c29..5bd438c43 100644 --- a/functions/PEAR/Net/DNS2/Exception.php +++ b/functions/PEAR/Net/DNS2/Exception.php @@ -43,8 +43,8 @@ public function __construct( $message = '', $code = 0, $previous = null, - Net_DNS2_Packet_Request $request = null, - Net_DNS2_Packet_Response $response = null + ?Net_DNS2_Packet_Request $request = null, + ?Net_DNS2_Packet_Response $response = null ) { // // store the request/response objects (if passed) diff --git a/functions/PEAR/Net/DNS2/Packet.php b/functions/PEAR/Net/DNS2/Packet.php index 41b6a43e0..ea41e66f5 100644 --- a/functions/PEAR/Net/DNS2/Packet.php +++ b/functions/PEAR/Net/DNS2/Packet.php @@ -304,7 +304,7 @@ public static function expand(Net_DNS2_Packet &$packet, &$offset, $escape_dot_li } $elem = ''; - $elem = substr($packet->rdata, $offset, $xlen); + $elem = substr((string) $packet->rdata, $offset, $xlen); // // escape literal dots in certain cases (SOA rname) @@ -346,11 +346,11 @@ public static function label(Net_DNS2_Packet &$packet, &$offset) if (($xlen + $offset) > $packet->rdlength) { - $name = substr($packet->rdata, $offset); + $name = substr((string) $packet->rdata, $offset); $offset = $packet->rdlength; } else { - $name = substr($packet->rdata, $offset, $xlen); + $name = substr((string) $packet->rdata, $offset, $xlen); $offset += $xlen; } diff --git a/functions/PEAR/Net/DNS2/PrivateKey.php b/functions/PEAR/Net/DNS2/PrivateKey.php index 70e4538a5..0f0dc1daf 100644 --- a/functions/PEAR/Net/DNS2/PrivateKey.php +++ b/functions/PEAR/Net/DNS2/PrivateKey.php @@ -317,14 +317,14 @@ public function parseFile($file) 'rsa' => [ - 'n' => base64_decode($this->_modulus), - 'e' => base64_decode($this->_public_exponent), - 'd' => base64_decode($this->_private_exponent), - 'p' => base64_decode($this->_prime1), - 'q' => base64_decode($this->_prime2), - 'dmp1' => base64_decode($this->_exponent1), - 'dmq1' => base64_decode($this->_exponent2), - 'iqmp' => base64_decode($this->_coefficient) + 'n' => base64_decode((string) $this->_modulus), + 'e' => base64_decode((string) $this->_public_exponent), + 'd' => base64_decode((string) $this->_private_exponent), + 'p' => base64_decode((string) $this->_prime1), + 'q' => base64_decode((string) $this->_prime2), + 'dmp1' => base64_decode((string) $this->_exponent1), + 'dmq1' => base64_decode((string) $this->_exponent2), + 'iqmp' => base64_decode((string) $this->_coefficient) ] ]; @@ -339,11 +339,11 @@ public function parseFile($file) 'dsa' => [ - 'p' => base64_decode($this->prime), - 'q' => base64_decode($this->subprime), - 'g' => base64_decode($this->base), - 'priv_key' => base64_decode($this->private_value), - 'pub_key' => base64_decode($this->public_value) + 'p' => base64_decode((string) $this->prime), + 'q' => base64_decode((string) $this->subprime), + 'g' => base64_decode((string) $this->base), + 'priv_key' => base64_decode((string) $this->private_value), + 'pub_key' => base64_decode((string) $this->public_value) ] ]; diff --git a/functions/PEAR/Net/DNS2/RR.php b/functions/PEAR/Net/DNS2/RR.php index d06f2988d..02db2ca6a 100644 --- a/functions/PEAR/Net/DNS2/RR.php +++ b/functions/PEAR/Net/DNS2/RR.php @@ -228,7 +228,7 @@ protected function buildString(array $chunks) foreach ($chunks as $r) { - $r = trim($r); + $r = trim((string) $r); if (strlen($r) == 0) { continue; } @@ -303,7 +303,7 @@ public function set(Net_DNS2_Packet &$packet, array $rr) $this->ttl = $rr['ttl']; $this->rdlength = $rr['rdlength']; - $this->rdata = substr($packet->rdata, $packet->offset, $rr['rdlength']); + $this->rdata = substr((string) $packet->rdata, $packet->offset, $rr['rdlength']); return $this->rrSet($packet); } @@ -374,7 +374,7 @@ public function get(Net_DNS2_Packet &$packet) // // add the RR // - $data .= pack('n', strlen($rdata)) . $rdata; + $data .= pack('n', strlen((string) $rdata)) . $rdata; return $data; } @@ -546,12 +546,12 @@ public static function fromString($line) case isset(Net_DNS2_Lookups::$classes_by_name[strtoupper($value)]): - $class = strtoupper(array_shift($values)); + $class = strtoupper((string) array_shift($values)); break; case isset(Net_DNS2_Lookups::$rr_types_by_name[strtoupper($value)]): - $type = strtoupper(array_shift($values)); + $type = strtoupper((string) array_shift($values)); break 2; break; diff --git a/functions/PEAR/Net/DNS2/RR/AAAA.php b/functions/PEAR/Net/DNS2/RR/AAAA.php index 09f9ee3d3..3c79e9d7e 100644 --- a/functions/PEAR/Net/DNS2/RR/AAAA.php +++ b/functions/PEAR/Net/DNS2/RR/AAAA.php @@ -99,7 +99,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // but we want to keep with the preferred standard, so we'll parse // it manually. // - $x = unpack('n8', $this->rdata); + $x = unpack('n8', (string) $this->rdata); if (count($x) == 8) { $this->address = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $x); diff --git a/functions/PEAR/Net/DNS2/RR/AFSDB.php b/functions/PEAR/Net/DNS2/RR/AFSDB.php index a4e4fe124..b5165a8e9 100644 --- a/functions/PEAR/Net/DNS2/RR/AFSDB.php +++ b/functions/PEAR/Net/DNS2/RR/AFSDB.php @@ -85,7 +85,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the subtype // - $x = unpack('nsubtype', $this->rdata); + $x = unpack('nsubtype', (string) $this->rdata); $this->subtype = $x['subtype']; $offset = $packet->offset + 2; @@ -111,7 +111,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->hostname) > 0) { + if (strlen((string) $this->hostname) > 0) { $data = pack('n', $this->subtype); $packet->offset += 2; diff --git a/functions/PEAR/Net/DNS2/RR/AMTRELAY.php b/functions/PEAR/Net/DNS2/RR/AMTRELAY.php index 8dda35f53..766e57108 100644 --- a/functions/PEAR/Net/DNS2/RR/AMTRELAY.php +++ b/functions/PEAR/Net/DNS2/RR/AMTRELAY.php @@ -97,7 +97,7 @@ protected function rrFromString(array $rdata) $this->precedence = array_shift($rdata); $this->discovery = array_shift($rdata); $this->relay_type = array_shift($rdata); - $this->relay = trim(strtolower(trim(array_shift($rdata))), '.'); + $this->relay = trim(strtolower(trim((string) array_shift($rdata))), '.'); // // if there's anything else other than 0 in the discovery value, then force it to one, so @@ -159,7 +159,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // parse off the first two octets // - $x = unpack('Cprecedence/Csecond', $this->rdata); + $x = unpack('Cprecedence/Csecond', (string) $this->rdata); $this->precedence = $x['precedence']; $this->discovery = ($x['second'] >> 7) & 0x1; @@ -176,7 +176,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) break; case self::AMTRELAY_TYPE_IPV4: - $this->relay = inet_ntop(substr($this->rdata, $offset, 4)); + $this->relay = inet_ntop(substr((string) $this->rdata, $offset, 4)); break; case self::AMTRELAY_TYPE_IPV6: @@ -185,7 +185,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // PHP's inet_ntop returns IPv6 addresses in their compressed form, but we want to keep // with the preferred standard, so we'll parse it manually. // - $ip = unpack('n8', substr($this->rdata, $offset, 16)); + $ip = unpack('n8', substr((string) $this->rdata, $offset, 16)); if (count($ip) == 8) { $this->relay = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); } else @@ -245,7 +245,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) break; case self::AMTRELAY_TYPE_DOMAIN: - $data .= pack('Ca*', strlen($this->relay), $this->relay); + $data .= pack('Ca*', strlen((string) $this->relay), $this->relay); break; default: diff --git a/functions/PEAR/Net/DNS2/RR/APL.php b/functions/PEAR/Net/DNS2/RR/APL.php index fe7a6a85c..67852c502 100644 --- a/functions/PEAR/Net/DNS2/RR/APL.php +++ b/functions/PEAR/Net/DNS2/RR/APL.php @@ -75,7 +75,7 @@ protected function rrFromString(array $rdata) { foreach ($rdata as $item) { - if (preg_match('/^(!?)([1|2])\:([^\/]*)\/([0-9]{1,3})$/', $item, $m)) { + if (preg_match('/^(!?)([1|2])\:([^\/]*)\/([0-9]{1,3})$/', (string) $item, $m)) { $i = [ @@ -119,7 +119,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // unpack the family, prefix, negate and length values // $x = unpack( - 'naddress_family/Cprefix/Cextra', substr($this->rdata, $offset) + 'naddress_family/Cprefix/Cextra', substr((string) $this->rdata, $offset) ); $item = [ @@ -134,7 +134,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) case 1: $r = unpack( - 'C*', substr($this->rdata, $offset + 4, $item['afd_length']) + 'C*', substr((string) $this->rdata, $offset + 4, $item['afd_length']) ); if (count($r) < 4) { @@ -149,7 +149,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) break; case 2: $r = unpack( - 'C*', substr($this->rdata, $offset + 4, $item['afd_length']) + 'C*', substr((string) $this->rdata, $offset + 4, $item['afd_length']) ); if (count($r) < 8) { diff --git a/functions/PEAR/Net/DNS2/RR/ATMA.php b/functions/PEAR/Net/DNS2/RR/ATMA.php index c8cd553d6..e92a7aa0f 100644 --- a/functions/PEAR/Net/DNS2/RR/ATMA.php +++ b/functions/PEAR/Net/DNS2/RR/ATMA.php @@ -68,7 +68,7 @@ protected function rrFromString(array $rdata) { $value = array_shift($rdata); - if (ctype_xdigit($value) == true) { + if (ctype_xdigit((string) $value) == true) { $this->format = 0; $this->address = $value; @@ -102,19 +102,19 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the format // - $x = unpack('Cformat/N*address', $this->rdata); + $x = unpack('Cformat/N*address', (string) $this->rdata); $this->format = $x['format']; if ($this->format == 0) { - $a = unpack('@1/H*address', $this->rdata); + $a = unpack('@1/H*address', (string) $this->rdata); $this->address = $a['address']; } else if ($this->format == 1) { - $this->address = substr($this->rdata, 1, $this->rdlength - 1); + $this->address = substr((string) $this->rdata, 1, $this->rdlength - 1); } else { diff --git a/functions/PEAR/Net/DNS2/RR/CAA.php b/functions/PEAR/Net/DNS2/RR/CAA.php index bebfd2ccd..cc3e14114 100644 --- a/functions/PEAR/Net/DNS2/RR/CAA.php +++ b/functions/PEAR/Net/DNS2/RR/CAA.php @@ -94,15 +94,15 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the flags and tag length // - $x = unpack('Cflags/Ctag_length', $this->rdata); + $x = unpack('Cflags/Ctag_length', (string) $this->rdata); $this->flags = $x['flags']; $offset = 2; - $this->tag = substr($this->rdata, $offset, $x['tag_length']); + $this->tag = substr((string) $this->rdata, $offset, $x['tag_length']); $offset += $x['tag_length']; - $this->value = substr($this->rdata, $offset); + $this->value = substr((string) $this->rdata, $offset); return true; } @@ -123,10 +123,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->value) > 0) { + if (strlen((string) $this->value) > 0) { $data = chr($this->flags); - $data .= chr(strlen($this->tag)) . $this->tag . $this->value; + $data .= chr(strlen((string) $this->tag)) . $this->tag . $this->value; $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/CERT.php b/functions/PEAR/Net/DNS2/RR/CERT.php index c76c8b1ec..aae510f21 100644 --- a/functions/PEAR/Net/DNS2/RR/CERT.php +++ b/functions/PEAR/Net/DNS2/RR/CERT.php @@ -113,7 +113,7 @@ public function __construct(?Net_DNS2_Packet &$packet = null, ?array $rr = null) protected function rrToString() { return $this->format . ' ' . $this->keytag . ' ' . $this->algorithm . - ' ' . base64_encode($this->certificate); + ' ' . base64_encode((string) $this->certificate); } /** @@ -133,7 +133,7 @@ protected function rrFromString(array $rdata) $this->format = array_shift($rdata); if (!is_numeric($this->format)) { - $mnemonic = strtoupper(trim($this->format)); + $mnemonic = strtoupper(trim((string) $this->format)); if (!isset($this->cert_format_name_to_id[$mnemonic])) { return false; @@ -156,7 +156,7 @@ protected function rrFromString(array $rdata) $this->algorithm = array_shift($rdata); if (!is_numeric($this->algorithm)) { - $mnemonic = strtoupper(trim($this->algorithm)); + $mnemonic = strtoupper(trim((string) $this->algorithm)); if (!isset(Net_DNS2_Lookups::$algorithm_name_to_id[$mnemonic])) { return false; @@ -199,7 +199,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the format, keytag and algorithm // - $x = unpack('nformat/nkeytag/Calgorithm', $this->rdata); + $x = unpack('nformat/nkeytag/Calgorithm', (string) $this->rdata); $this->format = $x['format']; $this->keytag = $x['keytag']; @@ -208,7 +208,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // copy the certificate // - $this->certificate = substr($this->rdata, 5, $this->rdlength - 5); + $this->certificate = substr((string) $this->rdata, 5, $this->rdlength - 5); return true; } @@ -229,7 +229,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->certificate) > 0) { + if (strlen((string) $this->certificate) > 0) { $data = pack('nnC', $this->format, $this->keytag, $this->algorithm) . $this->certificate; diff --git a/functions/PEAR/Net/DNS2/RR/CNAME.php b/functions/PEAR/Net/DNS2/RR/CNAME.php index 46c7d8b87..d93ed97dd 100644 --- a/functions/PEAR/Net/DNS2/RR/CNAME.php +++ b/functions/PEAR/Net/DNS2/RR/CNAME.php @@ -95,7 +95,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->cname) > 0) { + if (strlen((string) $this->cname) > 0) { return $packet->compress($this->cname, $packet->offset); } diff --git a/functions/PEAR/Net/DNS2/RR/CSYNC.php b/functions/PEAR/Net/DNS2/RR/CSYNC.php index 994ae7316..44a4b712c 100644 --- a/functions/PEAR/Net/DNS2/RR/CSYNC.php +++ b/functions/PEAR/Net/DNS2/RR/CSYNC.php @@ -63,7 +63,7 @@ protected function rrToString() // foreach ($this->type_bit_maps as $rr) { - $out .= ' ' . strtoupper($rr); + $out .= ' ' . strtoupper((string) $rr); } return $out; @@ -104,7 +104,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the serial and flags values // - $x = unpack('@' . $packet->offset . '/Nserial/nflags', $packet->rdata); + $x = unpack('@' . $packet->offset . '/Nserial/nflags', (string) $packet->rdata); $this->serial = Net_DNS2::expandUint32($x['serial']); $this->flags = $x['flags']; @@ -113,7 +113,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // parse out the RR bitmap // $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( - substr($this->rdata, 6) + substr((string) $this->rdata, 6) ); return true; diff --git a/functions/PEAR/Net/DNS2/RR/DHCID.php b/functions/PEAR/Net/DNS2/RR/DHCID.php index d42e53f61..28f313f9f 100644 --- a/functions/PEAR/Net/DNS2/RR/DHCID.php +++ b/functions/PEAR/Net/DNS2/RR/DHCID.php @@ -59,7 +59,7 @@ class Net_DNS2_RR_DHCID extends Net_DNS2_RR protected function rrToString() { $out = pack('nC', $this->id_type, $this->digest_type); - $out .= base64_decode($this->digest); + $out .= base64_decode((string) $this->digest); return base64_encode($out); } @@ -75,7 +75,7 @@ protected function rrToString() */ protected function rrFromString(array $rdata) { - $data = base64_decode(array_shift($rdata)); + $data = base64_decode((string) array_shift($rdata)); if (strlen($data) > 0) { // @@ -113,7 +113,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the id type and digest type // - $x = unpack('nid_type/Cdigest_type', $this->rdata); + $x = unpack('nid_type/Cdigest_type', (string) $this->rdata); $this->id_type = $x['id_type']; $this->digest_type = $x['digest_type']; @@ -122,7 +122,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // copy out the digest // $this->digest = base64_encode( - substr($this->rdata, 3, $this->rdlength - 3) + substr((string) $this->rdata, 3, $this->rdlength - 3) ); return true; @@ -144,10 +144,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->digest) > 0) { + if (strlen((string) $this->digest) > 0) { $data = pack('nC', $this->id_type, $this->digest_type) . - base64_decode($this->digest); + base64_decode((string) $this->digest); $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/DNAME.php b/functions/PEAR/Net/DNS2/RR/DNAME.php index 64403e621..ce4ee193b 100644 --- a/functions/PEAR/Net/DNS2/RR/DNAME.php +++ b/functions/PEAR/Net/DNS2/RR/DNAME.php @@ -95,7 +95,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->dname) > 0) { + if (strlen((string) $this->dname) > 0) { return $packet->compress($this->dname, $packet->offset); } diff --git a/functions/PEAR/Net/DNS2/RR/DNSKEY.php b/functions/PEAR/Net/DNS2/RR/DNSKEY.php index 311ba29d0..e37dff467 100644 --- a/functions/PEAR/Net/DNS2/RR/DNSKEY.php +++ b/functions/PEAR/Net/DNS2/RR/DNSKEY.php @@ -100,7 +100,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the flags, protocol and algorithm // - $x = unpack('nflags/Cprotocol/Calgorithm', $this->rdata); + $x = unpack('nflags/Cprotocol/Calgorithm', (string) $this->rdata); // // TODO: right now we're just displaying what's in DNS; we really @@ -114,7 +114,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) $this->protocol = $x['protocol']; $this->algorithm = $x['algorithm']; - $this->key = base64_encode(substr($this->rdata, 4)); + $this->key = base64_encode(substr((string) $this->rdata, 4)); return true; } @@ -135,10 +135,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->key) > 0) { + if (strlen((string) $this->key) > 0) { $data = pack('nCC', $this->flags, $this->protocol, $this->algorithm); - $data .= base64_decode($this->key); + $data .= base64_decode((string) $this->key); $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/DS.php b/functions/PEAR/Net/DNS2/RR/DS.php index 401f4837d..ab1275c39 100644 --- a/functions/PEAR/Net/DNS2/RR/DS.php +++ b/functions/PEAR/Net/DNS2/RR/DS.php @@ -99,7 +99,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the keytag, algorithm and digesttype // - $x = unpack('nkeytag/Calgorithm/Cdigesttype/H*digest', $this->rdata); + $x = unpack('nkeytag/Calgorithm/Cdigesttype/H*digest', (string) $this->rdata); $this->keytag = $x['keytag']; $this->algorithm = $x['algorithm']; @@ -125,7 +125,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->digest) > 0) { + if (strlen((string) $this->digest) > 0) { $data = pack('nCCH*', $this->keytag, $this->algorithm, $this->digesttype, $this->digest); diff --git a/functions/PEAR/Net/DNS2/RR/EUI48.php b/functions/PEAR/Net/DNS2/RR/EUI48.php index b24f47524..364eb5219 100644 --- a/functions/PEAR/Net/DNS2/RR/EUI48.php +++ b/functions/PEAR/Net/DNS2/RR/EUI48.php @@ -65,7 +65,7 @@ protected function rrFromString(array $rdata) // re: RFC 7043, the field must be represented as six two-digit hex numbers // separated by hyphens. // - $a = explode('-', $value); + $a = explode('-', (string) $value); if (count($a) != 6) { return false; @@ -83,7 +83,7 @@ protected function rrFromString(array $rdata) // // store it // - $this->address = strtolower($value); + $this->address = strtolower((string) $value); return true; } @@ -101,7 +101,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $x = unpack('C6', $this->rdata); + $x = unpack('C6', (string) $this->rdata); if (count($x) == 6) { $this->address = vsprintf('%02x-%02x-%02x-%02x-%02x-%02x', $x); @@ -127,7 +127,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) { $data = ''; - $a = explode('-', $this->address); + $a = explode('-', (string) $this->address); foreach ($a as $b) { $data .= chr(hexdec($b)); diff --git a/functions/PEAR/Net/DNS2/RR/EUI64.php b/functions/PEAR/Net/DNS2/RR/EUI64.php index 625684c99..7be534096 100644 --- a/functions/PEAR/Net/DNS2/RR/EUI64.php +++ b/functions/PEAR/Net/DNS2/RR/EUI64.php @@ -64,7 +64,7 @@ protected function rrFromString(array $rdata) // re: RFC 7043, the field must be represented as 8 two-digit hex numbers // separated by hyphens. // - $a = explode('-', $value); + $a = explode('-', (string) $value); if (count($a) != 8) { return false; @@ -82,7 +82,7 @@ protected function rrFromString(array $rdata) // // store it // - $this->address = strtolower($value); + $this->address = strtolower((string) $value); return true; } @@ -100,7 +100,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $x = unpack('C8', $this->rdata); + $x = unpack('C8', (string) $this->rdata); if (count($x) == 8) { $this->address = vsprintf( @@ -128,7 +128,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) { $data = ''; - $a = explode('-', $this->address); + $a = explode('-', (string) $this->address); foreach ($a as $b) { $data .= chr(hexdec($b)); diff --git a/functions/PEAR/Net/DNS2/RR/HINFO.php b/functions/PEAR/Net/DNS2/RR/HINFO.php index 0bfb8e0e1..0397431fb 100644 --- a/functions/PEAR/Net/DNS2/RR/HINFO.php +++ b/functions/PEAR/Net/DNS2/RR/HINFO.php @@ -65,8 +65,8 @@ protected function rrFromString(array $rdata) $data = $this->buildString($rdata); if (count($data) == 2) { - $this->cpu = trim($data[0], '"'); - $this->os = trim($data[1], '"'); + $this->cpu = trim((string) $data[0], '"'); + $this->os = trim((string) $data[1], '"'); return true; } @@ -111,9 +111,9 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->cpu) > 0) { + if (strlen((string) $this->cpu) > 0) { - $data = pack('Ca*Ca*', strlen($this->cpu), $this->cpu, strlen($this->os), $this->os); + $data = pack('Ca*Ca*', strlen((string) $this->cpu), $this->cpu, strlen((string) $this->os), $this->os); $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/HIP.php b/functions/PEAR/Net/DNS2/RR/HIP.php index 029ae69fb..82e1b922e 100644 --- a/functions/PEAR/Net/DNS2/RR/HIP.php +++ b/functions/PEAR/Net/DNS2/RR/HIP.php @@ -108,7 +108,7 @@ protected function rrToString() protected function rrFromString(array $rdata) { $this->pk_algorithm = array_shift($rdata); - $this->hit = strtoupper(array_shift($rdata)); + $this->hit = strtoupper((string) array_shift($rdata)); $this->public_key = array_shift($rdata); // @@ -124,7 +124,7 @@ protected function rrFromString(array $rdata) // store the lengths; // $this->hit_length = strlen(pack('H*', $this->hit)); - $this->pk_length = strlen(base64_decode($this->public_key)); + $this->pk_length = strlen(base64_decode((string) $this->public_key)); return true; } @@ -145,7 +145,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the algorithm and length values // - $x = unpack('Chit_length/Cpk_algorithm/npk_length', $this->rdata); + $x = unpack('Chit_length/Cpk_algorithm/npk_length', (string) $this->rdata); $this->hit_length = $x['hit_length']; $this->pk_algorithm = $x['pk_algorithm']; @@ -156,16 +156,16 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // copy out the HIT value // - $hit = unpack('H*', substr($this->rdata, $offset, $this->hit_length)); + $hit = unpack('H*', substr((string) $this->rdata, $offset, $this->hit_length)); - $this->hit = strtoupper($hit[1]); + $this->hit = strtoupper((string) $hit[1]); $offset += $this->hit_length; // // copy out the public key // $this->public_key = base64_encode( - substr($this->rdata, $offset, $this->pk_length) + substr((string) $this->rdata, $offset, $this->pk_length) ); $offset += $this->pk_length; @@ -200,7 +200,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if ( (strlen($this->hit) > 0) && (strlen($this->public_key) > 0) ) { + if ( (strlen((string) $this->hit) > 0) && (strlen((string) $this->public_key) > 0) ) { // // pack the length, algorithm and HIT values @@ -216,7 +216,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) // // add the public key // - $data .= base64_decode($this->public_key); + $data .= base64_decode((string) $this->public_key); // // add the offset diff --git a/functions/PEAR/Net/DNS2/RR/IPSECKEY.php b/functions/PEAR/Net/DNS2/RR/IPSECKEY.php index 8148b0520..1470dbeba 100644 --- a/functions/PEAR/Net/DNS2/RR/IPSECKEY.php +++ b/functions/PEAR/Net/DNS2/RR/IPSECKEY.php @@ -130,7 +130,7 @@ protected function rrFromString(array $rdata) $precedence = array_shift($rdata); $gateway_type = array_shift($rdata); $algorithm = array_shift($rdata); - $gateway = trim(strtolower(trim(array_shift($rdata))), '.'); + $gateway = trim(strtolower(trim((string) array_shift($rdata))), '.'); $key = array_shift($rdata); // @@ -206,7 +206,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // parse off the precedence, gateway type and algorithm // - $x = unpack('Cprecedence/Cgateway_type/Calgorithm', $this->rdata); + $x = unpack('Cprecedence/Cgateway_type/Calgorithm', (string) $this->rdata); $this->precedence = $x['precedence']; $this->gateway_type = $x['gateway_type']; @@ -223,12 +223,12 @@ protected function rrSet(Net_DNS2_Packet &$packet) break; case self::GATEWAY_TYPE_IPV4: - $this->gateway = inet_ntop(substr($this->rdata, $offset, 4)); + $this->gateway = inet_ntop(substr((string) $this->rdata, $offset, 4)); $offset += 4; break; case self::GATEWAY_TYPE_IPV6: - $ip = unpack('n8', substr($this->rdata, $offset, 16)); + $ip = unpack('n8', substr((string) $this->rdata, $offset, 16)); if (count($ip) == 8) { $this->gateway = vsprintf('%x:%x:%x:%x:%x:%x:%x:%x', $ip); @@ -260,7 +260,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) case self::ALGORITHM_DSA: case self::ALGORITHM_RSA: - $this->key = base64_encode(substr($this->rdata, $offset)); + $this->key = base64_encode(substr((string) $this->rdata, $offset)); break; default: @@ -307,7 +307,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) break; case self::GATEWAY_TYPE_DOMAIN: - $data .= chr(strlen($this->gateway)) . $this->gateway; + $data .= chr(strlen((string) $this->gateway)) . $this->gateway; break; default: @@ -324,7 +324,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) case self::ALGORITHM_DSA: case self::ALGORITHM_RSA: - $data .= base64_decode($this->key); + $data .= base64_decode((string) $this->key); break; default: diff --git a/functions/PEAR/Net/DNS2/RR/ISDN.php b/functions/PEAR/Net/DNS2/RR/ISDN.php index 5a29fce99..b41c9e936 100644 --- a/functions/PEAR/Net/DNS2/RR/ISDN.php +++ b/functions/PEAR/Net/DNS2/RR/ISDN.php @@ -96,7 +96,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // look for a SA (sub address) - it's optional // - if ( (strlen($this->isdnaddress) + 1) < $this->rdlength) { + if ( (strlen((string) $this->isdnaddress) + 1) < $this->rdlength) { $this->sa = Net_DNS2_Packet::label($packet, $packet->offset); } else { @@ -123,12 +123,12 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->isdnaddress) > 0) { + if (strlen((string) $this->isdnaddress) > 0) { - $data = chr(strlen($this->isdnaddress)) . $this->isdnaddress; + $data = chr(strlen((string) $this->isdnaddress)) . $this->isdnaddress; if (!empty($this->sa)) { - $data .= chr(strlen($this->sa)); + $data .= chr(strlen((string) $this->sa)); $data .= $this->sa; } diff --git a/functions/PEAR/Net/DNS2/RR/KX.php b/functions/PEAR/Net/DNS2/RR/KX.php index 9414ff91d..32c4d398e 100644 --- a/functions/PEAR/Net/DNS2/RR/KX.php +++ b/functions/PEAR/Net/DNS2/RR/KX.php @@ -88,7 +88,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // parse the preference // - $x = unpack('npreference', $this->rdata); + $x = unpack('npreference', (string) $this->rdata); $this->preference = $x['preference']; // @@ -116,9 +116,9 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->exchange) > 0) { + if (strlen((string) $this->exchange) > 0) { - $data = pack('nC', $this->preference, strlen($this->exchange)) . + $data = pack('nC', $this->preference, strlen((string) $this->exchange)) . $this->exchange; $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/L32.php b/functions/PEAR/Net/DNS2/RR/L32.php index 79b1e55bc..4d956298b 100644 --- a/functions/PEAR/Net/DNS2/RR/L32.php +++ b/functions/PEAR/Net/DNS2/RR/L32.php @@ -85,7 +85,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the values // - $x = unpack('npreference/C4locator', $this->rdata); + $x = unpack('npreference/C4locator', (string) $this->rdata); $this->preference = $x['preference']; @@ -114,12 +114,12 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->locator32) > 0) { + if (strlen((string) $this->locator32) > 0) { // // break out the locator value // - $n = explode('.', $this->locator32); + $n = explode('.', (string) $this->locator32); // // pack the data diff --git a/functions/PEAR/Net/DNS2/RR/L64.php b/functions/PEAR/Net/DNS2/RR/L64.php index 17d693308..d516d75f7 100644 --- a/functions/PEAR/Net/DNS2/RR/L64.php +++ b/functions/PEAR/Net/DNS2/RR/L64.php @@ -87,7 +87,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the values // - $x = unpack('npreference/n4locator', $this->rdata); + $x = unpack('npreference/n4locator', (string) $this->rdata); $this->preference = $x['preference']; @@ -118,12 +118,12 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->locator64) > 0) { + if (strlen((string) $this->locator64) > 0) { // // break out the locator64 // - $n = explode(':', $this->locator64); + $n = explode(':', (string) $this->locator64); // // pack the data diff --git a/functions/PEAR/Net/DNS2/RR/LOC.php b/functions/PEAR/Net/DNS2/RR/LOC.php index 77e0eef48..3d4403699 100644 --- a/functions/PEAR/Net/DNS2/RR/LOC.php +++ b/functions/PEAR/Net/DNS2/RR/LOC.php @@ -191,7 +191,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack( 'Cver/Csize/Choriz_pre/Cvert_pre/Nlatitude/Nlongitude/Naltitude', - $this->rdata + (string) $this->rdata ); // diff --git a/functions/PEAR/Net/DNS2/RR/LP.php b/functions/PEAR/Net/DNS2/RR/LP.php index ca95ff284..2df5d0c36 100644 --- a/functions/PEAR/Net/DNS2/RR/LP.php +++ b/functions/PEAR/Net/DNS2/RR/LP.php @@ -66,7 +66,7 @@ protected function rrToString() protected function rrFromString(array $rdata) { $this->preference = array_shift($rdata); - $this->fqdn = trim(array_shift($rdata), '.'); + $this->fqdn = trim((string) array_shift($rdata), '.'); return true; } @@ -87,7 +87,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // parse the preference // - $x = unpack('npreference', $this->rdata); + $x = unpack('npreference', (string) $this->rdata); $this->preference = $x['preference']; $offset = $packet->offset + 2; @@ -115,7 +115,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->fqdn) > 0) { + if (strlen((string) $this->fqdn) > 0) { $data = pack('n', $this->preference); $packet->offset += 2; diff --git a/functions/PEAR/Net/DNS2/RR/MX.php b/functions/PEAR/Net/DNS2/RR/MX.php index b1c2a4f61..725bf0f2a 100644 --- a/functions/PEAR/Net/DNS2/RR/MX.php +++ b/functions/PEAR/Net/DNS2/RR/MX.php @@ -85,7 +85,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // parse the preference // - $x = unpack('npreference', $this->rdata); + $x = unpack('npreference', (string) $this->rdata); $this->preference = $x['preference']; // @@ -113,7 +113,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->exchange) > 0) { + if (strlen((string) $this->exchange) > 0) { $data = pack('n', $this->preference); $packet->offset += 2; diff --git a/functions/PEAR/Net/DNS2/RR/NAPTR.php b/functions/PEAR/Net/DNS2/RR/NAPTR.php index 9d9cebde3..5103ab777 100644 --- a/functions/PEAR/Net/DNS2/RR/NAPTR.php +++ b/functions/PEAR/Net/DNS2/RR/NAPTR.php @@ -131,7 +131,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the order and preference // - $x = unpack('norder/npreference', $this->rdata); + $x = unpack('norder/npreference', (string) $this->rdata); $this->order = $x['order']; $this->preference = $x['preference']; @@ -163,13 +163,13 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if ( (isset($this->order)) && (strlen($this->services) > 0) ) { + if ( (isset($this->order)) && (strlen((string) $this->services) > 0) ) { $data = pack('nn', $this->order, $this->preference); - $data .= chr(strlen($this->flags)) . $this->flags; - $data .= chr(strlen($this->services)) . $this->services; - $data .= chr(strlen($this->regexp)) . $this->regexp; + $data .= chr(strlen((string) $this->flags)) . $this->flags; + $data .= chr(strlen((string) $this->services)) . $this->services; + $data .= chr(strlen((string) $this->regexp)) . $this->regexp; $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/NID.php b/functions/PEAR/Net/DNS2/RR/NID.php index 8b501377d..90c1d80d3 100644 --- a/functions/PEAR/Net/DNS2/RR/NID.php +++ b/functions/PEAR/Net/DNS2/RR/NID.php @@ -87,7 +87,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the values // - $x = unpack('npreference/n4nodeid', $this->rdata); + $x = unpack('npreference/n4nodeid', (string) $this->rdata); $this->preference = $x['preference']; @@ -118,12 +118,12 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->nodeid) > 0) { + if (strlen((string) $this->nodeid) > 0) { // // break out the node id // - $n = explode(':', $this->nodeid); + $n = explode(':', (string) $this->nodeid); // // pack the data diff --git a/functions/PEAR/Net/DNS2/RR/NS.php b/functions/PEAR/Net/DNS2/RR/NS.php index 7e9f81a43..fb707d2ca 100644 --- a/functions/PEAR/Net/DNS2/RR/NS.php +++ b/functions/PEAR/Net/DNS2/RR/NS.php @@ -95,7 +95,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->nsdname) > 0) { + if (strlen((string) $this->nsdname) > 0) { return $packet->compress($this->nsdname, $packet->offset); } diff --git a/functions/PEAR/Net/DNS2/RR/NSAP.php b/functions/PEAR/Net/DNS2/RR/NSAP.php index 09c80a6f1..87b4bf183 100644 --- a/functions/PEAR/Net/DNS2/RR/NSAP.php +++ b/functions/PEAR/Net/DNS2/RR/NSAP.php @@ -74,7 +74,7 @@ protected function rrToString() */ protected function rrFromString(array $rdata) { - $data = strtolower(trim(array_shift($rdata))); + $data = strtolower(trim((string) array_shift($rdata))); // // there is no real standard for format, so we can't rely on the fact that @@ -137,7 +137,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack( 'Cafi/nidi/Cdfi/C3aa/nrsvd/nrd/narea/Nidh/nidl/Csel', - $this->rdata + (string) $this->rdata ); $this->afi = sprintf('0x%02x', $x['afi']); @@ -173,33 +173,35 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if ($this->afi == '0x47') { + // phpcs:ignore + if ((string) $this->afi === (string) '0x47') { + // phpcs:enable // // build the aa field // - $aa = unpack('A2x/A2y/A2z', $this->aa); + $aa = unpack('A2x/A2y/A2z', (string) $this->aa); // // build the id field // - $id = unpack('A8a/A4b', $this->id); + $id = unpack('A8a/A4b', (string) $this->id); // $data = pack( 'CnCCCCnnnNnC', - hexdec($this->afi), - hexdec($this->idi), - hexdec($this->dfi), - hexdec($aa['x']), - hexdec($aa['y']), - hexdec($aa['z']), - hexdec($this->rsvd), - hexdec($this->rd), - hexdec($this->area), - hexdec($id['a']), - hexdec($id['b']), - hexdec($this->sel) + hexdec((string) $this->afi), + hexdec((string) $this->idi), + hexdec((string) $this->dfi), + hexdec((string) $aa['x']), + hexdec((string) $aa['y']), + hexdec((string) $aa['z']), + hexdec((string) $this->rsvd), + hexdec((string) $this->rd), + hexdec((string) $this->area), + hexdec((string) $id['a']), + hexdec((string) $id['b']), + hexdec((string) $this->sel) ); if (strlen($data) == 20) { diff --git a/functions/PEAR/Net/DNS2/RR/NSEC.php b/functions/PEAR/Net/DNS2/RR/NSEC.php index d64735f2a..04547b451 100644 --- a/functions/PEAR/Net/DNS2/RR/NSEC.php +++ b/functions/PEAR/Net/DNS2/RR/NSEC.php @@ -99,7 +99,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // parse out the RR's from the bitmap // $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( - substr($this->rdata, $offset - $packet->offset) + substr((string) $this->rdata, $offset - $packet->offset) ); return true; @@ -121,7 +121,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->next_domain_name) > 0) { + if (strlen((string) $this->next_domain_name) > 0) { $data = $packet->compress($this->next_domain_name, $packet->offset); $bitmap = Net_DNS2_BitMap::arrayToBitMap($this->type_bit_maps); diff --git a/functions/PEAR/Net/DNS2/RR/NSEC3.php b/functions/PEAR/Net/DNS2/RR/NSEC3.php index b4d3c0858..af5fc152a 100644 --- a/functions/PEAR/Net/DNS2/RR/NSEC3.php +++ b/functions/PEAR/Net/DNS2/RR/NSEC3.php @@ -107,7 +107,7 @@ protected function rrToString() // foreach ($this->type_bit_maps as $rr) { - $out .= ' ' . strtoupper($rr); + $out .= ' ' . strtoupper((string) $rr); } return $out; @@ -139,11 +139,11 @@ protected function rrFromString(array $rdata) } else { $this->salt_length = strlen(pack('H*', $salt)); - $this->salt = strtoupper($salt); + $this->salt = strtoupper((string) $salt); } $this->hashed_owner_name = array_shift($rdata); - $this->hash_length = strlen(base64_decode($this->hashed_owner_name)); + $this->hash_length = strlen(base64_decode((string) $this->hashed_owner_name)); $this->type_bit_maps = $rdata; @@ -166,7 +166,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the first values // - $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', $this->rdata); + $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', (string) $this->rdata); $this->algorithm = $x['algorithm']; $this->flags = $x['flags']; @@ -177,15 +177,15 @@ protected function rrSet(Net_DNS2_Packet &$packet) if ($this->salt_length > 0) { - $x = unpack('H*', substr($this->rdata, $offset, $this->salt_length)); - $this->salt = strtoupper($x[1]); + $x = unpack('H*', substr((string) $this->rdata, $offset, $this->salt_length)); + $this->salt = strtoupper((string) $x[1]); $offset += $this->salt_length; } // // unpack the hash length // - $x = unpack('@' . $offset . '/Chash_length', $this->rdata); + $x = unpack('@' . $offset . '/Chash_length', (string) $this->rdata); $offset++; // @@ -195,7 +195,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) if ($this->hash_length > 0) { $this->hashed_owner_name = base64_encode( - substr($this->rdata, $offset, $this->hash_length) + substr((string) $this->rdata, $offset, $this->hash_length) ); $offset += $this->hash_length; } @@ -204,7 +204,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // parse out the RR bitmap // $this->type_bit_maps = Net_DNS2_BitMap::bitMapToArray( - substr($this->rdata, $offset) + substr((string) $this->rdata, $offset) ); return true; @@ -247,7 +247,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) $data .= chr($this->hash_length); if ($this->hash_length > 0) { - $data .= base64_decode($this->hashed_owner_name); + $data .= base64_decode((string) $this->hashed_owner_name); } // diff --git a/functions/PEAR/Net/DNS2/RR/NSEC3PARAM.php b/functions/PEAR/Net/DNS2/RR/NSEC3PARAM.php index 8bb39bf80..9fda2419d 100644 --- a/functions/PEAR/Net/DNS2/RR/NSEC3PARAM.php +++ b/functions/PEAR/Net/DNS2/RR/NSEC3PARAM.php @@ -106,7 +106,7 @@ protected function rrFromString(array $rdata) } else { $this->salt_length = strlen(pack('H*', $salt)); - $this->salt = strtoupper($salt); + $this->salt = strtoupper((string) $salt); } return true; @@ -125,7 +125,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', $this->rdata); + $x = unpack('Calgorithm/Cflags/niterations/Csalt_length', (string) $this->rdata); $this->algorithm = $x['algorithm']; $this->flags = $x['flags']; @@ -134,8 +134,8 @@ protected function rrSet(Net_DNS2_Packet &$packet) if ($this->salt_length > 0) { - $x = unpack('H*', substr($this->rdata, 5, $this->salt_length)); - $this->salt = strtoupper($x[1]); + $x = unpack('H*', substr((string) $this->rdata, 5, $this->salt_length)); + $this->salt = strtoupper((string) $x[1]); } return true; diff --git a/functions/PEAR/Net/DNS2/RR/OPENPGPKEY.php b/functions/PEAR/Net/DNS2/RR/OPENPGPKEY.php index ee3d36b3b..51ec59620 100644 --- a/functions/PEAR/Net/DNS2/RR/OPENPGPKEY.php +++ b/functions/PEAR/Net/DNS2/RR/OPENPGPKEY.php @@ -76,7 +76,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) { if ($this->rdlength > 0) { - $this->key = base64_encode(substr($this->rdata, 0, $this->rdlength)); + $this->key = base64_encode(substr((string) $this->rdata, 0, $this->rdlength)); return true; } @@ -97,9 +97,9 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->key) > 0) { + if (strlen((string) $this->key) > 0) { - $data = base64_decode($this->key); + $data = base64_decode((string) $this->key); $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/OPT.php b/functions/PEAR/Net/DNS2/RR/OPT.php index 75a9962d0..d8ec37d5a 100644 --- a/functions/PEAR/Net/DNS2/RR/OPT.php +++ b/functions/PEAR/Net/DNS2/RR/OPT.php @@ -134,7 +134,7 @@ protected function rrFromString(array $rdata) { $this->option_code = array_shift($rdata); $this->option_data = array_shift($rdata); - $this->option_length = strlen($this->option_data); + $this->option_length = strlen((string) $this->option_data); $x = unpack('Cextended/Cversion/Cdo/Cz', pack('N', $this->ttl)); @@ -175,7 +175,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the code and length // - $x = unpack('noption_code/noption_length', $this->rdata); + $x = unpack('noption_code/noption_length', (string) $this->rdata); $this->option_code = $x['option_code']; $this->option_length = $x['option_length']; @@ -183,7 +183,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // copy out the data based on the length // - $this->option_data = substr($this->rdata, 4); + $this->option_data = substr((string) $this->rdata, 4); } return true; diff --git a/functions/PEAR/Net/DNS2/RR/PTR.php b/functions/PEAR/Net/DNS2/RR/PTR.php index f66745008..03042edef 100644 --- a/functions/PEAR/Net/DNS2/RR/PTR.php +++ b/functions/PEAR/Net/DNS2/RR/PTR.php @@ -41,7 +41,7 @@ class Net_DNS2_RR_PTR extends Net_DNS2_RR */ protected function rrToString() { - return rtrim($this->ptrdname, '.') . '.'; + return rtrim((string) $this->ptrdname, '.') . '.'; } /** @@ -94,7 +94,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->ptrdname) > 0) { + if (strlen((string) $this->ptrdname) > 0) { return $packet->compress($this->ptrdname, $packet->offset); } diff --git a/functions/PEAR/Net/DNS2/RR/PX.php b/functions/PEAR/Net/DNS2/RR/PX.php index e0f97e5d5..983a8f796 100644 --- a/functions/PEAR/Net/DNS2/RR/PX.php +++ b/functions/PEAR/Net/DNS2/RR/PX.php @@ -95,7 +95,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // parse the preference // - $x = unpack('npreference', $this->rdata); + $x = unpack('npreference', (string) $this->rdata); $this->preference = $x['preference']; $offset = $packet->offset + 2; @@ -122,7 +122,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->map822) > 0) { + if (strlen((string) $this->map822) > 0) { $data = pack('n', $this->preference); $packet->offset += 2; diff --git a/functions/PEAR/Net/DNS2/RR/RP.php b/functions/PEAR/Net/DNS2/RR/RP.php index b545ab087..34b87645c 100644 --- a/functions/PEAR/Net/DNS2/RR/RP.php +++ b/functions/PEAR/Net/DNS2/RR/RP.php @@ -107,7 +107,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->mboxdname) > 0) { + if (strlen((string) $this->mboxdname) > 0) { return $packet->compress($this->mboxdname, $packet->offset) . $packet->compress($this->txtdname, $packet->offset); diff --git a/functions/PEAR/Net/DNS2/RR/RRSIG.php b/functions/PEAR/Net/DNS2/RR/RRSIG.php index 13ede6308..70ebd52c0 100644 --- a/functions/PEAR/Net/DNS2/RR/RRSIG.php +++ b/functions/PEAR/Net/DNS2/RR/RRSIG.php @@ -139,7 +139,7 @@ protected function rrToString() */ protected function rrFromString(array $rdata) { - $this->typecovered = strtoupper(array_shift($rdata)); + $this->typecovered = strtoupper((string) array_shift($rdata)); $this->algorithm = array_shift($rdata); $this->labels = array_shift($rdata); $this->origttl = array_shift($rdata); @@ -153,7 +153,7 @@ protected function rrFromString(array $rdata) $this->signature .= $line; } - $this->signature = trim($this->signature); + $this->signature = trim((string) $this->signature); return true; } @@ -176,7 +176,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack( 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', - $this->rdata + (string) $this->rdata ); $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; @@ -202,10 +202,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) $sigoffset = $offset; $this->signname = strtolower( - Net_DNS2_Packet::expand($packet, $sigoffset) + (string) Net_DNS2_Packet::expand($packet, $sigoffset) ); $this->signature = base64_encode( - substr($this->rdata, 18 + ($sigoffset - $offset)) + substr((string) $this->rdata, 18 + ($sigoffset - $offset)) ); return true; @@ -227,16 +227,16 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->signature) > 0) { + if (strlen((string) $this->signature) > 0) { // // parse the values out of the dates // preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $this->sigexp, $e + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', (string) $this->sigexp, $e ); preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $this->sigincep, $i + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', (string) $this->sigincep, $i ); // @@ -257,7 +257,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) // the signer name is special; it's not allowed to be compressed // (see section 3.1.7) // - $names = explode('.', strtolower($this->signname)); + $names = explode('.', strtolower((string) $this->signname)); foreach ($names as $name) { $data .= chr(strlen($name)); @@ -268,7 +268,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) // // add the signature // - $data .= base64_decode($this->signature); + $data .= base64_decode((string) $this->signature); $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/RT.php b/functions/PEAR/Net/DNS2/RR/RT.php index 08e2b160e..0446223c2 100644 --- a/functions/PEAR/Net/DNS2/RR/RT.php +++ b/functions/PEAR/Net/DNS2/RR/RT.php @@ -86,7 +86,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the preference // - $x = unpack('npreference', $this->rdata); + $x = unpack('npreference', (string) $this->rdata); $this->preference = $x['preference']; $offset = $packet->offset + 2; @@ -112,7 +112,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->intermediatehost) > 0) { + if (strlen((string) $this->intermediatehost) > 0) { $data = pack('n', $this->preference); $packet->offset += 2; diff --git a/functions/PEAR/Net/DNS2/RR/SIG.php b/functions/PEAR/Net/DNS2/RR/SIG.php index 98ea17532..981aee239 100644 --- a/functions/PEAR/Net/DNS2/RR/SIG.php +++ b/functions/PEAR/Net/DNS2/RR/SIG.php @@ -144,7 +144,7 @@ protected function rrToString() */ protected function rrFromString(array $rdata) { - $this->typecovered = strtoupper(array_shift($rdata)); + $this->typecovered = strtoupper((string) array_shift($rdata)); $this->algorithm = array_shift($rdata); $this->labels = array_shift($rdata); $this->origttl = array_shift($rdata); @@ -158,7 +158,7 @@ protected function rrFromString(array $rdata) $this->signature .= $line; } - $this->signature = trim($this->signature); + $this->signature = trim((string) $this->signature); return true; } @@ -181,7 +181,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack( 'ntc/Calgorithm/Clabels/Norigttl/Nsigexp/Nsigincep/nkeytag', - $this->rdata + (string) $this->rdata ); $this->typecovered = Net_DNS2_Lookups::$rr_types_by_id[$x['tc']]; @@ -207,10 +207,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) $sigoffset = $offset; $this->signname = strtolower( - Net_DNS2_Packet::expand($packet, $sigoffset) + (string) Net_DNS2_Packet::expand($packet, $sigoffset) ); $this->signature = base64_encode( - substr($this->rdata, 18 + ($sigoffset - $offset)) + substr((string) $this->rdata, 18 + ($sigoffset - $offset)) ); return true; @@ -236,10 +236,10 @@ protected function rrGet(Net_DNS2_Packet &$packet) // parse the values out of the dates // preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $this->sigexp, $e + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', (string) $this->sigexp, $e ); preg_match( - '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $this->sigincep, $i + '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', (string) $this->sigincep, $i ); // @@ -260,7 +260,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) // the signer name is special; it's not allowed to be compressed // (see section 3.1.7) // - $names = explode('.', strtolower($this->signname)); + $names = explode('.', strtolower((string) $this->signname)); foreach ($names as $name) { $data .= chr(strlen($name)); @@ -274,7 +274,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) // private key object, and we have access to openssl, then assume this // is a SIG(0), and generate a new signature // - if ( (strlen($this->signature) == 0) + if ( (strlen((string) $this->signature) == 0) && ($this->private_key instanceof Net_DNS2_PrivateKey) && (extension_loaded('openssl') === true) ) { @@ -393,7 +393,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA256: case Net_DNS2_Lookups::DNSSEC_ALGORITHM_RSASHA512: - $this->signature = base64_encode($this->signature); + $this->signature = base64_encode((string) $this->signature); break; } } @@ -401,7 +401,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) // // add the signature // - $data .= base64_decode($this->signature); + $data .= base64_decode((string) $this->signature); $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/SOA.php b/functions/PEAR/Net/DNS2/RR/SOA.php index 36dee536f..aecaa3bdc 100644 --- a/functions/PEAR/Net/DNS2/RR/SOA.php +++ b/functions/PEAR/Net/DNS2/RR/SOA.php @@ -144,7 +144,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack( '@' . $offset . '/Nserial/Nrefresh/Nretry/Nexpire/Nminimum/', - $packet->rdata + (string) $packet->rdata ); $this->serial = Net_DNS2::expandUint32($x['serial']); @@ -172,7 +172,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->mname) > 0) { + if (strlen((string) $this->mname) > 0) { $data = $packet->compress($this->mname, $packet->offset); $data .= $packet->compress($this->rname, $packet->offset); diff --git a/functions/PEAR/Net/DNS2/RR/SRV.php b/functions/PEAR/Net/DNS2/RR/SRV.php index e5cca0c39..148bbbb6f 100644 --- a/functions/PEAR/Net/DNS2/RR/SRV.php +++ b/functions/PEAR/Net/DNS2/RR/SRV.php @@ -102,7 +102,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the priority, weight and port // - $x = unpack('npriority/nweight/nport', $this->rdata); + $x = unpack('npriority/nweight/nport', (string) $this->rdata); $this->priority = $x['priority']; $this->weight = $x['weight']; @@ -130,7 +130,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->target) > 0) { + if (strlen((string) $this->target) > 0) { $data = pack('nnn', $this->priority, $this->weight, $this->port); $packet->offset += 6; diff --git a/functions/PEAR/Net/DNS2/RR/SSHFP.php b/functions/PEAR/Net/DNS2/RR/SSHFP.php index 93f773959..336ad4f29 100644 --- a/functions/PEAR/Net/DNS2/RR/SSHFP.php +++ b/functions/PEAR/Net/DNS2/RR/SSHFP.php @@ -139,7 +139,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the algorithm and finger print type // - $x = unpack('Calgorithm/Cfp_type', $this->rdata); + $x = unpack('Calgorithm/Cfp_type', (string) $this->rdata); $this->algorithm = $x['algorithm']; $this->fp_type = $x['fp_type']; @@ -167,8 +167,8 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // parse the finger print; this assumes SHA-1 // - $fp = unpack('H*a', substr($this->rdata, 2)); - $this->fingerprint = strtolower($fp['a']); + $fp = unpack('H*a', substr((string) $this->rdata, 2)); + $this->fingerprint = strtolower((string) $fp['a']); return true; } @@ -189,7 +189,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->fingerprint) > 0) { + if (strlen((string) $this->fingerprint) > 0) { $data = pack( 'CCH*', $this->algorithm, $this->fp_type, $this->fingerprint diff --git a/functions/PEAR/Net/DNS2/RR/TALINK.php b/functions/PEAR/Net/DNS2/RR/TALINK.php index 265aee2bf..a502ee962 100644 --- a/functions/PEAR/Net/DNS2/RR/TALINK.php +++ b/functions/PEAR/Net/DNS2/RR/TALINK.php @@ -106,10 +106,10 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if ( (strlen($this->previous) > 0) || (strlen($this->next) > 0) ) { + if ( (strlen((string) $this->previous) > 0) || (strlen((string) $this->next) > 0) ) { - $data = chr(strlen($this->previous)) . $this->previous . - chr(strlen($this->next)) . $this->next; + $data = chr(strlen((string) $this->previous)) . $this->previous . + chr(strlen((string) $this->next)) . $this->next; $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/RR/TKEY.php b/functions/PEAR/Net/DNS2/RR/TKEY.php index 1563ca995..5b6635e73 100644 --- a/functions/PEAR/Net/DNS2/RR/TKEY.php +++ b/functions/PEAR/Net/DNS2/RR/TKEY.php @@ -90,7 +90,7 @@ protected function rrToString() $out = $this->cleanString($this->algorithm) . '. ' . $this->mode; if ($this->key_size > 0) { - $out .= ' ' . trim($this->key_data, '.') . '.'; + $out .= ' ' . trim((string) $this->key_data, '.') . '.'; } else { $out .= ' .'; @@ -115,7 +115,7 @@ protected function rrFromString(array $rdata) // $this->algorithm = $this->cleanString(array_shift($rdata)); $this->mode = array_shift($rdata); - $this->key_data = trim(array_shift($rdata), '.'); + $this->key_data = trim((string) array_shift($rdata), '.'); // // the rest of the data is set manually @@ -154,7 +154,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack( '@' . $offset . '/Ninception/Nexpiration/nmode/nerror/nkey_size', - $packet->rdata + (string) $packet->rdata ); $this->inception = Net_DNS2::expandUint32($x['inception']); @@ -170,14 +170,14 @@ protected function rrSet(Net_DNS2_Packet &$packet) // if ($this->key_size > 0) { - $this->key_data = substr($packet->rdata, $offset, $this->key_size); + $this->key_data = substr((string) $packet->rdata, $offset, $this->key_size); $offset += $this->key_size; } // // unpack the other length // - $x = unpack('@' . $offset . '/nother_size', $packet->rdata); + $x = unpack('@' . $offset . '/nother_size', (string) $packet->rdata); $this->other_size = $x['other_size']; $offset += 2; @@ -188,7 +188,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) if ($this->other_size > 0) { $this->other_data = substr( - $packet->rdata, $offset, $this->other_size + (string) $packet->rdata, $offset, $this->other_size ); } @@ -211,13 +211,13 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->algorithm) > 0) { + if (strlen((string) $this->algorithm) > 0) { // // make sure the size values are correct // - $this->key_size = strlen($this->key_data); - $this->other_size = strlen($this->other_data); + $this->key_size = strlen((string) $this->key_data); + $this->other_size = strlen((string) $this->other_data); // // add the algorithm without compression diff --git a/functions/PEAR/Net/DNS2/RR/TLSA.php b/functions/PEAR/Net/DNS2/RR/TLSA.php index cf06be7f4..0e9d554e6 100644 --- a/functions/PEAR/Net/DNS2/RR/TLSA.php +++ b/functions/PEAR/Net/DNS2/RR/TLSA.php @@ -62,7 +62,7 @@ class Net_DNS2_RR_TLSA extends Net_DNS2_RR protected function rrToString() { return $this->cert_usage . ' ' . $this->selector . ' ' . - $this->matching_type . ' ' . base64_encode($this->certificate); + $this->matching_type . ' ' . base64_encode((string) $this->certificate); } /** @@ -100,7 +100,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the format, keytag and algorithm // - $x = unpack('Cusage/Cselector/Ctype', $this->rdata); + $x = unpack('Cusage/Cselector/Ctype', (string) $this->rdata); $this->cert_usage = $x['usage']; $this->selector = $x['selector']; @@ -109,7 +109,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // copy the certificate // - $this->certificate = substr($this->rdata, 3, $this->rdlength - 3); + $this->certificate = substr((string) $this->rdata, 3, $this->rdlength - 3); return true; } @@ -130,7 +130,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->certificate) > 0) { + if (strlen((string) $this->certificate) > 0) { $data = pack( 'CCC', $this->cert_usage, $this->selector, $this->matching_type diff --git a/functions/PEAR/Net/DNS2/RR/TSIG.php b/functions/PEAR/Net/DNS2/RR/TSIG.php index 5b60c054b..23eff3fca 100644 --- a/functions/PEAR/Net/DNS2/RR/TSIG.php +++ b/functions/PEAR/Net/DNS2/RR/TSIG.php @@ -131,7 +131,7 @@ protected function rrToString() $out = $this->cleanString($this->algorithm) . '. ' . $this->time_signed . ' ' . $this->fudge . ' ' . $this->mac_size . ' ' . - base64_encode($this->mac) . ' ' . $this->original_id . ' ' . + base64_encode((string) $this->mac) . ' ' . $this->original_id . ' ' . $this->error . ' '. $this->other_length; if ($this->other_length > 0) { @@ -158,7 +158,7 @@ protected function rrFromString(array $rdata) // // this assumes it's passed in base64 encoded. // - $this->key = preg_replace('/\s+/', '', array_shift($rdata)); + $this->key = preg_replace('/\s+/', '', (string) array_shift($rdata)); // // the rest of the data is set to default @@ -207,7 +207,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack( '@' . $offset . '/ntime_high/Ntime_low/nfudge/nmac_size', - $this->rdata + (string) $this->rdata ); $this->time_signed = Net_DNS2::expandUint32($x['time_low']); @@ -221,7 +221,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // if ($this->mac_size > 0) { - $this->mac = substr($this->rdata, $offset, $this->mac_size); + $this->mac = substr((string) $this->rdata, $offset, $this->mac_size); $offset += $this->mac_size; } @@ -230,7 +230,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack( '@' . $offset . '/noriginal_id/nerror/nother_length', - $this->rdata + (string) $this->rdata ); $this->original_id = $x['original_id']; @@ -256,7 +256,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // $x = unpack( 'nhigh/nlow', - substr($this->rdata, $offset + 6, $this->other_length) + substr((string) $this->rdata, $offset + 6, $this->other_length) ); $this->other_data = $x['low']; } @@ -280,7 +280,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->key) > 0) { + if (strlen((string) $this->key) > 0) { // // create a new packet for the signature- @@ -318,7 +318,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) // // add the algorithm name without compression // - $sig_data .= Net_DNS2_Packet::pack(strtolower($this->algorithm)); + $sig_data .= Net_DNS2_Packet::pack(strtolower((string) $this->algorithm)); // // add the rest of the values @@ -336,14 +336,14 @@ protected function rrGet(Net_DNS2_Packet &$packet) // sign the data // $this->mac = $this->_signHMAC( - $sig_data, base64_decode($this->key), $this->algorithm + $sig_data, base64_decode((string) $this->key), $this->algorithm ); $this->mac_size = strlen($this->mac); // // compress the algorithm // - $data = Net_DNS2_Packet::pack(strtolower($this->algorithm)); + $data = Net_DNS2_Packet::pack(strtolower((string) $this->algorithm)); // // pack the time, fudge and mac size @@ -358,7 +358,7 @@ protected function rrGet(Net_DNS2_Packet &$packet) // if ($this->error == Net_DNS2_Lookups::RCODE_BADTIME) { - $this->other_length = strlen($this->other_data); + $this->other_length = strlen((string) $this->other_data); if ($this->other_length != 6) { return null; @@ -416,7 +416,7 @@ private function _signHMAC($data, $key = null, $algorithm = self::HMAC_MD5) ); } - return hash_hmac(self::$hash_algorithms[$algorithm], $data, $key, true); + return hash_hmac(self::$hash_algorithms[$algorithm], $data, (string) $key, true); } // diff --git a/functions/PEAR/Net/DNS2/RR/TXT.php b/functions/PEAR/Net/DNS2/RR/TXT.php index e3e99a676..3a985e14c 100644 --- a/functions/PEAR/Net/DNS2/RR/TXT.php +++ b/functions/PEAR/Net/DNS2/RR/TXT.php @@ -119,10 +119,10 @@ protected function rrGet(Net_DNS2_Packet &$packet) foreach ($this->text as $t) { - $data .= chr(strlen($t)) . $t; + $data .= chr(strlen((string) $t)) . $t; } - $packet->offset += strlen($data); + $packet->offset += strlen((string) $data); return $data; } diff --git a/functions/PEAR/Net/DNS2/RR/TYPE65534.php b/functions/PEAR/Net/DNS2/RR/TYPE65534.php index 9722866d6..f133651dd 100644 --- a/functions/PEAR/Net/DNS2/RR/TYPE65534.php +++ b/functions/PEAR/Net/DNS2/RR/TYPE65534.php @@ -41,7 +41,7 @@ class Net_DNS2_RR_TYPE65534 extends Net_DNS2_RR */ protected function rrToString() { - return base64_encode($this->private_data); + return base64_encode((string) $this->private_data); } /** @@ -93,11 +93,11 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->private_data) > 0) { + if (strlen((string) $this->private_data) > 0) { $data = $this->private_data; - $packet->offset += strlen($data); + $packet->offset += strlen((string) $data); return $data; } diff --git a/functions/PEAR/Net/DNS2/RR/URI.php b/functions/PEAR/Net/DNS2/RR/URI.php index 3be89e988..bd85aec29 100644 --- a/functions/PEAR/Net/DNS2/RR/URI.php +++ b/functions/PEAR/Net/DNS2/RR/URI.php @@ -75,7 +75,7 @@ protected function rrFromString(array $rdata) { $this->priority = $rdata[0]; $this->weight = $rdata[1]; - $this->target = trim(strtolower(trim($rdata[2])), '"'); + $this->target = trim(strtolower(trim((string) $rdata[2])), '"'); return true; } @@ -96,7 +96,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // unpack the priority and weight // - $x = unpack('npriority/nweight/a*target', $this->rdata); + $x = unpack('npriority/nweight/a*target', (string) $this->rdata); $this->priority = $x['priority']; $this->weight = $x['weight']; @@ -121,7 +121,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->target) > 0) { + if (strlen((string) $this->target) > 0) { $data = pack('nna*', $this->priority, $this->weight, $this->target); diff --git a/functions/PEAR/Net/DNS2/RR/WKS.php b/functions/PEAR/Net/DNS2/RR/WKS.php index 75a94e416..a922a578c 100644 --- a/functions/PEAR/Net/DNS2/RR/WKS.php +++ b/functions/PEAR/Net/DNS2/RR/WKS.php @@ -77,7 +77,7 @@ protected function rrToString() */ protected function rrFromString(array $rdata) { - $this->address = strtolower(trim(array_shift($rdata), '.')); + $this->address = strtolower(trim((string) array_shift($rdata), '.')); $this->protocol = array_shift($rdata); $this->bitmap = $rdata; @@ -100,7 +100,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // // get the address and protocol value // - $x = unpack('Naddress/Cprotocol', $this->rdata); + $x = unpack('Naddress/Cprotocol', (string) $this->rdata); $this->address = long2ip($x['address']); $this->protocol = $x['protocol']; @@ -109,7 +109,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) // unpack the port list bitmap // $port = 0; - foreach (unpack('@5/C*', $this->rdata) as $set) { + foreach (unpack('@5/C*', (string) $this->rdata) as $set) { $s = sprintf('%08b', $set); @@ -139,7 +139,7 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->address) > 0) { + if (strlen((string) $this->address) > 0) { $data = pack('NC', ip2long($this->address), $this->protocol); diff --git a/functions/PEAR/Net/DNS2/RR/X25.php b/functions/PEAR/Net/DNS2/RR/X25.php index b28edd5e0..0592154a8 100644 --- a/functions/PEAR/Net/DNS2/RR/X25.php +++ b/functions/PEAR/Net/DNS2/RR/X25.php @@ -98,9 +98,9 @@ protected function rrSet(Net_DNS2_Packet &$packet) */ protected function rrGet(Net_DNS2_Packet &$packet) { - if (strlen($this->psdnaddress) > 0) { + if (strlen((string) $this->psdnaddress) > 0) { - $data = chr(strlen($this->psdnaddress)) . $this->psdnaddress; + $data = chr(strlen((string) $this->psdnaddress)) . $this->psdnaddress; $packet->offset += strlen($data); diff --git a/functions/PEAR/Net/DNS2/Resolver.php b/functions/PEAR/Net/DNS2/Resolver.php index c1d7f8a89..a826a5f5e 100644 --- a/functions/PEAR/Net/DNS2/Resolver.php +++ b/functions/PEAR/Net/DNS2/Resolver.php @@ -69,7 +69,7 @@ public function query($name, $type = 'A', $class = 'IN') // if ( (strpos($name, '.') === false) && ($type != 'PTR') ) { - $name .= '.' . strtolower($this->domain); + $name .= '.' . strtolower((string) $this->domain); } // @@ -190,7 +190,7 @@ public function query($name, $type = 'A', $class = 'IN') // foreach ($response->answer as $index => $object) { - if ( (strcasecmp(trim($object->name, '.'), trim($packet->question[0]->qname, '.')) == 0) + if ( (strcasecmp(trim((string) $object->name, '.'), trim((string) $packet->question[0]->qname, '.')) == 0) && ($object->type == $packet->question[0]->qtype) && ($object->class == $packet->question[0]->qclass) ) { diff --git a/functions/PEAR/Net/DNS2/Socket.php b/functions/PEAR/Net/DNS2/Socket.php index 953f9a820..74bf6f462 100644 --- a/functions/PEAR/Net/DNS2/Socket.php +++ b/functions/PEAR/Net/DNS2/Socket.php @@ -129,7 +129,7 @@ public function open() // // bind to a local IP/port if it's set // - if (strlen($this->local_host) > 0) { + if (strlen((string) $this->local_host) > 0) { $opts['socket']['bindto'] = $this->local_host; if ($this->local_port > 0) { diff --git a/functions/PEAR/Net/IPv4.php b/functions/PEAR/Net/IPv4.php index f5f6a4432..c2c5bded4 100755 --- a/functions/PEAR/Net/IPv4.php +++ b/functions/PEAR/Net/IPv4.php @@ -32,7 +32,7 @@ * * @global array $GLOBALS['Net_IPv4_Netmask_Map'] */ -$GLOBALS['Net_IPv4_Netmask_Map'] = array( +$GLOBALS['Net_IPv4_Netmask_Map'] = [ 0 => "0.0.0.0", 1 => "128.0.0.0", 2 => "192.0.0.0", @@ -66,7 +66,7 @@ 30 => "255.255.255.252", 31 => "255.255.255.254", 32 => "255.255.255.255" - ); + ]; // }}} // {{{ Net_IPv4 @@ -90,12 +90,12 @@ class Net_IPv4 { // {{{ properties - var $ip = ""; - var $bitmask = false; - var $netmask = ""; - var $network = ""; - var $broadcast = ""; - var $long = 0; + public $ip = ""; + public $bitmask = false; + public $netmask = ""; + public $network = ""; + public $broadcast = ""; + public $long = 0; //pear public $pear; @@ -292,7 +292,7 @@ function calculate() * a network long ip address. Whichever was given, populate the * other field */ - if (strlen($this->ip)) { + if (strlen((string) $this->ip)) { if (! $this->validateIP($this->ip)) { return $this->pear->raiseError("invalid IP address"); } @@ -307,9 +307,9 @@ function calculate() * Check to see if we were supplied with a bitmask or a netmask. * Populate the other field as needed. */ - if (strlen($this->bitmask)) { + if (strlen((string) $this->bitmask)) { $this->netmask = $validNM[$this->bitmask]; - } else if (strlen($this->netmask)) { + } else if (strlen((string) $this->netmask)) { $validNM_rev = array_flip($validNM); $this->bitmask = $validNM_rev[$this->netmask]; } else { @@ -326,7 +326,7 @@ function calculate() function getNetmask($length) { - if (! PEAR::isError($ipobj = Net_IPv4::parseAddress("0.0.0.0/" . $length))) { + if (! PEAR::isError($ipobj = $this->parseAddress("0.0.0.0/" . $length))) { $mask = $ipobj->netmask; unset($ipobj); return $mask; @@ -339,7 +339,7 @@ function getNetmask($length) function getNetLength($netmask) { - if (! PEAR::isError($ipobj = Net_IPv4::parseAddress("0.0.0.0/" . $netmask))) { + if (! PEAR::isError($ipobj = $this->parseAddress("0.0.0.0/" . $netmask))) { $bitmask = $ipobj->bitmask; unset($ipobj); return $bitmask; @@ -352,7 +352,7 @@ function getNetLength($netmask) function getSubnet($ip, $netmask) { - if (! PEAR::isError($ipobj = Net_IPv4::parseAddress($ip . "/" . $netmask))) { + if (! PEAR::isError($ipobj = $this->parseAddress($ip . "/" . $netmask))) { $net = $ipobj->network; unset($ipobj); return $net; @@ -366,13 +366,13 @@ function getSubnet($ip, $netmask) function inSameSubnet($ip1, $ip2) { if (! is_object($ip1) || strcasecmp(get_class($ip1), 'net_ipv4') <> 0) { - $ipobj1 = Net_IPv4::parseAddress($ip1); + $ipobj1 = $this->parseAddress($ip1); if (PEAR::isError($ipobj1)) { return $this->pear->raiseError("IP addresses must be an understood format or a Net_IPv4 object"); } } if (! is_object($ip2) || strcasecmp(get_class($ip2), 'net_ipv4') <> 0) { - $ipobj2 = Net_IPv4::parseAddress($ip2); + $ipobj2 = $this->parseAddress($ip2); if (PEAR::isError($ipobj2)) { return $this->pear->raiseError("IP addresses must be an understood format or a Net_IPv4 object"); } @@ -394,7 +394,7 @@ function inSameSubnet($ip1, $ip2) */ function atoh($addr) { - if (! Net_IPv4::validateIP($addr)) { + if (! $this->validateIP($addr)) { return false; } $ap = explode(".", $addr); @@ -430,7 +430,7 @@ function htoa($addr) */ function ip2double($ip) { - return (double)(sprintf("%u", ip2long($ip))); + return (float)(sprintf("%u", ip2long($ip))); } // }}} @@ -451,14 +451,14 @@ function ip2double($ip) function ipInNetwork($ip, $network) { if (! is_object($network) || strcasecmp(get_class($network), 'net_ipv4') <> 0) { - $network = Net_IPv4::parseAddress($network); + $network = $this->parseAddress($network); } if (strcasecmp(get_class($network), 'pear_error') === 0) { return false; } - $net = Net_IPv4::ip2double($network->network); - $bcast = Net_IPv4::ip2double($network->broadcast); - $ip = Net_IPv4::ip2double($ip); + $net = $this->ip2double($network->network); + $bcast = $this->ip2double($network->broadcast); + $ip = $this->ip2double($ip); unset($network); if ($ip >= $net && $ip <= $bcast) { return true; diff --git a/functions/PEAR/Net/IPv6.php b/functions/PEAR/Net/IPv6.php index f15176b8c..63145a903 100755 --- a/functions/PEAR/Net/IPv6.php +++ b/functions/PEAR/Net/IPv6.php @@ -154,7 +154,7 @@ public static function separate($ip) if(false === strrpos($ip, '/')) { - return array($addr, $spec); + return [$addr, $spec]; } @@ -167,7 +167,7 @@ public static function separate($ip) } - return array($addr, $spec); + return [$addr, $spec]; } // }}} @@ -620,7 +620,7 @@ public static function uncompress($ip, $leadingZeros = false) if(true == $leadingZeros) { - $uipT = array(); + $uipT = []; $uiparts = explode(':', $uip); foreach($uiparts as $p) { @@ -666,7 +666,7 @@ public static function uncompress($ip, $leadingZeros = false) * @param String $ip a valid IPv6-address (hex format) * @param boolean $force if true the address will be compresses as best as possible (since 1.2.0) * - * @return tring the compressed IPv6-address (hex format) + * @return string the compressed IPv6-address (hex format) * @access public * @see Uncompress() * @static @@ -734,8 +734,8 @@ public static function compress($ip, $force = false) } - $cip = preg_replace('/((^:)|(:$))/', '', $cip); - $cip = preg_replace('/((^:)|(:$))/', '::', $cip); + $cip = preg_replace('/((^:)|(:$))/', '', (string) $cip); + $cip = preg_replace('/((^:)|(:$))/', '::', (string) $cip); if ('' != $netmask) { @@ -792,7 +792,7 @@ public static function recommendedFormat($ip) public static function isCompressible($ip) { - return (bool)($ip != Net_IPv6::compress($address)); + return (bool)($ip != Net_IPv6::compress($ip)); } @@ -832,7 +832,7 @@ public static function SplitV64($ip, $uncompress = true) $pos = strrpos($ip, ':'); if(false === $pos) { - return array("", $ip); + return ["", $ip]; } $ip[$pos] = '_'; @@ -842,7 +842,7 @@ public static function SplitV64($ip, $uncompress = true) } else { - return array($ip, ""); + return [$ip, ""]; } } @@ -878,7 +878,7 @@ public static function checkIPv6($ip) $count = 0; if (!empty($ipPart[0])) { - $ipv6 = explode(':', $ipPart[0]); + $ipv6 = explode(':', (string) $ipPart[0]); foreach($ipv6 as $element) { // made a validate precheck if(!preg_match('/[0-9a-fA-F]*/', $element)) { @@ -895,7 +895,7 @@ public static function checkIPv6($ip) } $dec = hexdec($ipv6[$i]); - $hex = strtoupper(preg_replace("/^[0]{1,3}(.*[0-9a-fA-F])$/", + $hex = strtoupper((string) preg_replace("/^[0]{1,3}(.*[0-9a-fA-F])$/", "\\1", $ipv6[$i])); @@ -914,12 +914,12 @@ public static function checkIPv6($ip) } else if (6 == $count and !empty($ipPart[1])) { - $ipv4 = explode('.', $ipPart[1]); + $ipv4 = explode('.', (string) $ipPart[1]); $count = 0; for ($i = 0; $i < count($ipv4); $i++) { - if ($ipv4[$i] >= 0 && (integer)$ipv4[$i] <= 255 + if ($ipv4[$i] >= 0 && (int)$ipv4[$i] <= 255 && preg_match("/^\d{1,3}$/", $ipv4[$i])) { $count++; @@ -1011,7 +1011,7 @@ public static function parseAddress($ipToParse, $bits = null) $endAddress = Net_IPv6::_bin2Ip(Net_IPv6::_ip2Bin($ip) | ($binNetmask ^ $maxNetmask)); - return array('start' => $startAddress, 'end' => $endAddress); + return ['start' => $startAddress, 'end' => $endAddress]; } // }}} diff --git a/functions/PEAR/Net/Ping.php b/functions/PEAR/Net/Ping.php index 4c2270a40..adf640dc8 100644 --- a/functions/PEAR/Net/Ping.php +++ b/functions/PEAR/Net/Ping.php @@ -67,7 +67,7 @@ class Net_Ping * @var string * @access private */ - var $_ping_path = ""; + public $_ping_path = ""; /** * Array with the result from the ping execution @@ -75,7 +75,7 @@ class Net_Ping * @var array * @access private */ - var $_result = array(); + public $_result = []; /** * OS_Guess instance @@ -83,7 +83,7 @@ class Net_Ping * @var object * @access private */ - var $_OS_Guess = ""; + public $_OS_Guess = ""; /** * OS_Guess->getSysname result @@ -91,7 +91,7 @@ class Net_Ping * @var string * @access private */ - var $_sysname = ""; + public $_sysname = ""; /** * Ping command arguments @@ -99,7 +99,7 @@ class Net_Ping * @var array * @access private */ - var $_args = array(); + public $_args = []; /** * Indicates if an empty array was given to setArgs @@ -107,7 +107,7 @@ class Net_Ping * @var boolean * @access private */ - var $_noArgs = true; + public $_noArgs = true; /** * Contains the argument->option relation @@ -115,7 +115,7 @@ class Net_Ping * @var array * @access private */ - var $_argRelation = array(); + public $_argRelation = []; //pear public $pear; @@ -239,7 +239,7 @@ function _setNoArgs($args) public static function _setPingPath($sysname) { $status = ''; - $output = array(); + $output = []; $ping_path = ''; if ("windows" == $sysname) { @@ -268,7 +268,7 @@ public static function _setPingPath($sysname) */ function _createArgList() { - $retval = array(); + $retval = []; $timeout = ""; $iface = ""; @@ -378,7 +378,7 @@ function _createArgList() function ping($host) { if($this->_noArgs) { - $this->setArgs(array('count' => 3)); + $this->setArgs(['count' => 3]); } $argList = $this->_createArgList(); @@ -388,7 +388,7 @@ function ping($host) // success), users may call the ping() method repeatedly to // perform unrelated ping tests Make sure we don't have raw data // from a previous call laying in the _result array. - $this->_result = array(); + $this->_result = []; exec($cmd, $this->_result); @@ -420,13 +420,13 @@ function ping($host) */ function checkHost($host, $severely = true) { - $matches = array(); + $matches = []; - $this->setArgs(array("count" => 10, + $this->setArgs(["count" => 10, "size" => 32, "quiet" => null, "deadline" => 10 - ) + ] ); $res = $this->ping($host); if ($this->pear->isError($res)) { @@ -467,52 +467,52 @@ public static function _raiseError($error) */ function _initArgRelation() { - $this->_argRelation["sunos"] = array( + $this->_argRelation["sunos"] = [ "timeout" => NULL, "ttl" => "-t", "count" => " ", "quiet" => "-q", "size" => " ", "iface" => "-i" - ); + ]; - $this->_argRelation["freebsd"] = array ( + $this->_argRelation["freebsd"] = [ "timeout" => "-t", "ttl" => "-m", "count" => "-c", "quiet" => "-q", "size" => NULL, "iface" => NULL - ); + ]; - $this->_argRelation["netbsd"] = array ( + $this->_argRelation["netbsd"] = [ "timeout" => "-w", "iface" => "-I", "ttl" => "-T", "count" => "-c", "quiet" => "-q", "size" => "-s" - ); + ]; - $this->_argRelation["openbsd"] = array ( + $this->_argRelation["openbsd"] = [ "timeout" => "-w", "iface" => "-I", "ttl" => "-t", "count" => "-c", "quiet" => "-q", "size" => "-s" - ); + ]; - $this->_argRelation["darwin"] = array ( + $this->_argRelation["darwin"] = [ "timeout" => "-t", "iface" => NULL, "ttl" => NULL, "count" => "-c", "quiet" => "-q", "size" => NULL - ); + ]; - $this->_argRelation["linux"] = array ( + $this->_argRelation["linux"] = [ "timeout" => "-W", "iface" => NULL, "ttl" => "-t", @@ -520,9 +520,9 @@ function _initArgRelation() "quiet" => "-q", "size" => "-s", "deadline" => "-w" - ); + ]; - $this->_argRelation["linuxdebian"] = array ( + $this->_argRelation["linuxdebian"] = [ "timeout" => "-W", "iface" => NULL, "ttl" => "-t", @@ -530,9 +530,9 @@ function _initArgRelation() "quiet" => "-q", "size" => "-s", "deadline" => "-w", - ); + ]; - $this->_argRelation["linuxredhat8"] = array ( + $this->_argRelation["linuxredhat8"] = [ "timeout" => NULL, "iface" => "-I", "ttl" => "-t", @@ -540,9 +540,9 @@ function _initArgRelation() "quiet" => "-q", "size" => "-s", "deadline" => "-w" - ); + ]; - $this->_argRelation["linuxredhat9"] = array ( + $this->_argRelation["linuxredhat9"] = [ "timeout" => "-W", "iface" => "-I", "ttl" => "-t", @@ -550,34 +550,34 @@ function _initArgRelation() "quiet" => "-q", "size" => "-s", "deadline" => "-w" - ); + ]; - $this->_argRelation["windows"] = array ( + $this->_argRelation["windows"] = [ "timeout" => "-w", "iface" => NULL, "ttl" => "-i", "count" => "-n", "quiet" => NULL, "size" => "-l" - ); + ]; - $this->_argRelation["hpux"] = array ( + $this->_argRelation["hpux"] = [ "timeout" => NULL, "iface" => NULL, "ttl" => "-t", "count" => "-n", "quiet" => NULL, "size" => " " - ); + ]; - $this->_argRelation["aix"] = array ( + $this->_argRelation["aix"] = [ "timeout" => "-i", "iface" => NULL, "ttl" => "-T", "count" => "-c", "quiet" => NULL, "size" => "-s" - ); + ]; } /* function _initArgRelation() */ } /* class Net_Ping */ @@ -597,7 +597,7 @@ class Net_Ping_Result * @var array * @access private */ - var $_icmp_sequence = array(); /* array($sequence_number => $time ) */ + public $_icmp_sequence = []; /* array($sequence_number => $time ) */ /** * The target's IP Address @@ -605,7 +605,7 @@ class Net_Ping_Result * @var string * @access private */ - var $_target_ip; + public $_target_ip; /** * Number of bytes that are sent with each ICMP request @@ -613,7 +613,7 @@ class Net_Ping_Result * @var int * @access private */ - var $_bytes_per_request; + public $_bytes_per_request; /** * The total number of bytes that are sent with all ICMP requests @@ -621,7 +621,7 @@ class Net_Ping_Result * @var int * @access private */ - var $_bytes_total; + public $_bytes_total; /** * The ICMP request's TTL @@ -629,7 +629,7 @@ class Net_Ping_Result * @var int * @access private */ - var $_ttl; + public $_ttl; /** * The raw Net_Ping::result @@ -637,7 +637,7 @@ class Net_Ping_Result * @var array * @access private */ - var $_raw_data = array(); + public $_raw_data = []; /** * The Net_Ping::_sysname @@ -645,7 +645,7 @@ class Net_Ping_Result * @var int * @access private */ - var $_sysname; + public $_sysname; /** * Statistical information about the ping @@ -653,7 +653,7 @@ class Net_Ping_Result * @var int * @access private */ - var $_round_trip = array(); /* array('min' => xxx, 'avg' => yyy, 'max' => zzz) */ + public $_round_trip = []; /* array('min' => xxx, 'avg' => yyy, 'max' => zzz) */ /** @@ -743,11 +743,11 @@ function _parseResultDetailBytesPerRequest($upper) // succesful ICMP reply which ping printed. for ( $i=1; $i_loss = (int)$matches[1]; return; } @@ -842,7 +842,7 @@ function _parseResultDetailReceived($lower) { for ( $i=1; $i_received = (int)$matches[1]; return; } @@ -869,10 +869,10 @@ function _parseResultDetailRoundTrip($lower) // separated by slashes. $p2 = '[0-9\.]+/[0-9\.]+/[0-9\.]+/?[0-9\.]*'; - $results = array(); - $matches = array(); + $results = []; + $matches = []; for ( $i=(count($lower)-1); $i>=0; $i-- ) { - if ( preg_match('|('.$p1.')[^0-9]+('.$p2.')|i', $lower[$i], $matches) ) { + if ( preg_match('|('.$p1.')[^0-9]+('.$p2.')|i', (string) $lower[$i], $matches) ) { break; } } @@ -906,8 +906,8 @@ function _parseResultDetailRoundTrip($lower) // layout. $p3 = '[a-z]+\s*=\s*([0-9\.]+).*'; for ( $i=(count($lower)-1); $i>=0; $i-- ) { - if ( preg_match('/min.*max/i', $lower[$i]) ) { - if ( preg_match('/'.$p3.$p3.$p3.'/i', $lower[$i], $matches) ) { + if ( preg_match('/min.*max/i', (string) $lower[$i]) ) { + if ( preg_match('/'.$p3.$p3.$p3.'/i', (string) $lower[$i], $matches) ) { $results['min'] = $matches[1]; $results['max'] = $matches[2]; $results['avg'] = $matches[3]; @@ -932,7 +932,7 @@ function _parseResultDetailTargetIp($upper) // put the target IP on the first line, but some only list it // in successful ping packet lines. for ( $i=0; $i_transmitted = (int)$matches[1]; return; } @@ -966,7 +966,7 @@ function _parseResultDetailTtl($upper) { //extract TTL from first icmp echo line for ( $i=1; $i 0 ) { return( (int)$matches[1] ); @@ -990,11 +990,11 @@ function _parseResultTrimLines(&$data) exit; } // Trim empty elements from the front - while ( preg_match('/^\s*$/', $data[0]) ) { + while ( preg_match('/^\s*$/', (string) $data[0]) ) { array_splice($data, 0, 1); } // Trim empty elements from the back - while ( preg_match('/^\s*$/', $data[(count($data)-1)]) ) { + while ( preg_match('/^\s*$/', (string) $data[(count($data)-1)]) ) { array_splice($data, -1, 1); } } @@ -1008,12 +1008,12 @@ function _parseResultTrimLines(&$data) */ function _parseResultSeparateParts($data, &$upper, &$lower) { - $upper = array(); - $lower = array(); + $upper = []; + $lower = []; // find the blank line closest to the end $dividerIndex = count($data) - 1; - while ( !preg_match('/^\s*$/', $data[$dividerIndex]) ) { + while ( !preg_match('/^\s*$/', (string) $data[$dividerIndex]) ) { $dividerIndex--; if ( $dividerIndex < 0 ) { break; diff --git a/functions/PEAR/OLE/ChainedBlockStream.php b/functions/PEAR/OLE/ChainedBlockStream.php index 87481c05d..16a079af5 100755 --- a/functions/PEAR/OLE/ChainedBlockStream.php +++ b/functions/PEAR/OLE/ChainedBlockStream.php @@ -45,25 +45,25 @@ class OLE_ChainedBlockStream extends PEAR * The OLE container of the file that is being read. * @var OLE */ - var $ole; + public $ole; /** * Parameters specified by fopen(). * @var array */ - var $params; + public $params; /** * The binary data of the file. * @var string */ - var $data; + public $data; /** * The file pointer. * @var int byte offset */ - var $pos; + public $pos; /** * Implements support for fopen(). @@ -85,7 +85,7 @@ function stream_open($path, $mode, $options, &$openedPath) } // 25 is length of "ole-chainedblockstream://" - parse_str(substr($path, 25), $this->params); + parse_str(substr((string) $path, 25), $this->params); if (!isset($this->params['oleInstanceId'], $this->params['blockId'], $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) { @@ -209,9 +209,9 @@ function stream_seek($offset, $whence) */ function stream_stat() { - return array( + return [ 'size' => strlen($this->data), - ); + ]; } // Methods used by stream_wrapper_register() that are not implemented: diff --git a/functions/PEAR/OLE/OLE.php b/functions/PEAR/OLE/OLE.php index 2d4e43f96..423c5d593 100755 --- a/functions/PEAR/OLE/OLE.php +++ b/functions/PEAR/OLE/OLE.php @@ -37,7 +37,7 @@ * OLE_ChainedBlockStream::stream_open(). * @var array */ -$GLOBALS['_OLE_INSTANCES'] = array(); +$GLOBALS['_OLE_INSTANCES'] = []; /** * OLE package base class. @@ -55,43 +55,43 @@ class OLE extends PEAR * The file handle for reading an OLE container * @var resource */ - var $_file_handle; + public $_file_handle; /** * Array of PPS's found on the OLE container * @var array */ - var $_list; + public $_list; /** * Root directory of OLE container * @var OLE_PPS_Root */ - var $root; + public $root; /** * Big Block Allocation Table * @var array (blockId => nextBlockId) */ - var $bbat; + public $bbat; /** * Short Block Allocation Table * @var array (blockId => nextBlockId) */ - var $sbat; + public $sbat; /** * Size of big blocks. This is usually 512. * @var int number of octets per block. */ - var $bigBlockSize; + public $bigBlockSize; /** * Size of small blocks. This is usually 64. * @var int number of octets per block */ - var $smallBlockSize; + public $smallBlockSize; /** @@ -99,7 +99,7 @@ class OLE extends PEAR * @access public */ public function __construct() { - $this->_list = array(); + $this->_list = []; } /** @@ -170,11 +170,11 @@ function read($file) $mbatFirstBlockId = $this->_readInt4($fh); // Number of blocks in Master Block Allocation Table $mbbatBlockCount = $this->_readInt4($fh); - $this->bbat = array(); + $this->bbat = []; // Remaining 4 * 109 bytes of current block is beginning of Master // Block Allocation Table - $mbatBlocks = array(); + $mbatBlocks = []; for ($i = 0; $i < 109; $i++) { $mbatBlocks[] = $this->_readInt4($fh); } @@ -201,7 +201,7 @@ function read($file) } // Read short block allocation table (SBAT) - $this->sbat = array(); + $this->sbat = []; $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4; $sbatFh = $this->getStream($sbatFirstBlockId); for ($blockId = 0; $blockId < $shortBlockCount; $blockId++) { @@ -314,12 +314,12 @@ function _readPpsWks($blockId) switch ($type) { case OLE_PPS_TYPE_ROOT: require_once 'OLE/PPS/Root.php'; - $pps = new OLE_PPS_Root(null, null, array()); + $pps = new OLE_PPS_Root(null, null, []); $this->root = $pps; break; case OLE_PPS_TYPE_DIR: $pps = new OLE_PPS(null, null, null, null, null, - null, null, null, null, array()); + null, null, null, null, []); break; case OLE_PPS_TYPE_FILE: require_once 'OLE/PPS/File.php'; @@ -335,8 +335,8 @@ function _readPpsWks($blockId) $pps->NextPps = $this->_readInt4($fh); $pps->DirPps = $this->_readInt4($fh); fseek($fh, 20, SEEK_CUR); - $pps->Time1st = OLE::OLE2LocalDate(fread($fh, 8)); - $pps->Time2nd = OLE::OLE2LocalDate(fread($fh, 8)); + $pps->Time1st = $this->OLE2LocalDate(fread($fh, 8)); + $pps->Time2nd = $this->OLE2LocalDate(fread($fh, 8)); $pps->_StartBlock = $this->_readInt4($fh); $pps->Size = $this->_readInt4($fh); $pps->No = count($this->_list); @@ -354,8 +354,8 @@ function _readPpsWks($blockId) // Initialize $pps->children on directories foreach ($this->_list as $pps) { if ($pps->Type == OLE_PPS_TYPE_DIR || $pps->Type == OLE_PPS_TYPE_ROOT) { - $nos = array($pps->DirPps); - $pps->children = array(); + $nos = [$pps->DirPps]; + $pps->children = []; while ($nos) { $no = array_pop($nos); if ($no != -1) { @@ -553,14 +553,14 @@ function OLE2LocalDate($string) $factor = pow(2,32); $high_part = 0; for ($i = 0; $i < 4; $i++) { - list(, $high_part) = unpack('C', $string[(7 - $i)]); + list(, $high_part) = unpack('C', (string) $string[(7 - $i)]); if ($i < 3) { $high_part *= 0x100; } } $low_part = 0; for ($i = 4; $i < 8; $i++) { - list(, $low_part) = unpack('C', $string[(7 - $i)]); + list(, $low_part) = unpack('C', (string) $string[(7 - $i)]); if ($i < 7) { $low_part *= 0x100; } diff --git a/functions/PEAR/OLE/PPS.php b/functions/PEAR/OLE/PPS.php index 9b9dcc421..b91db5a1d 100755 --- a/functions/PEAR/OLE/PPS.php +++ b/functions/PEAR/OLE/PPS.php @@ -37,79 +37,79 @@ class OLE_PPS extends PEAR * The PPS index * @var integer */ - var $No; + public $No; /** * The PPS name (in Unicode) * @var string */ - var $Name; + public $Name; /** * The PPS type. Dir, Root or File * @var integer */ - var $Type; + public $Type; /** * The index of the previous PPS * @var integer */ - var $PrevPps; + public $PrevPps; /** * The index of the next PPS * @var integer */ - var $NextPps; + public $NextPps; /** * The index of it's first child if this is a Dir or Root PPS * @var integer */ - var $DirPps; + public $DirPps; /** * A timestamp * @var integer */ - var $Time1st; + public $Time1st; /** * A timestamp * @var integer */ - var $Time2nd; + public $Time2nd; /** * Starting block (small or big) for this PPS's data inside the container * @var integer */ - var $_StartBlock; + public $_StartBlock; /** * The size of the PPS's data (in bytes) * @var integer */ - var $Size; + public $Size; /** * The PPS's data (only used if it's not using a temporary file) * @var string */ - var $_data; + public $_data; /** * Array of child PPS's (only used by Root and Dir PPS's) * @var array */ - var $children = array(); + public $children = []; /** * Pointer to OLE container * @var OLE */ - var $ole; + public $ole; /** * The constructor diff --git a/functions/PEAR/OLE/PPS/File.php b/functions/PEAR/OLE/PPS/File.php index 998c2eeb4..d53fa5dbf 100755 --- a/functions/PEAR/OLE/PPS/File.php +++ b/functions/PEAR/OLE/PPS/File.php @@ -20,7 +20,7 @@ // $Id: File.php,v 1.12 2008/02/02 21:00:37 schmidt Exp $ -require_once( dirname(__FILE__) . '/../PPS.php'); +require_once( __DIR__ . '/../PPS.php'); require_once 'System.php'; /** @@ -36,7 +36,7 @@ class OLE_PPS_File extends OLE_PPS * The temporary dir for storing the OLE file * @var string */ - var $_tmp_dir; + public $_tmp_dir; /** * The constructor @@ -59,7 +59,7 @@ public function __construct($name) null, null, '', - array()); + []); } /** diff --git a/functions/PEAR/OLE/PPS/Root.php b/functions/PEAR/OLE/PPS/Root.php index 803b7630d..35f8162fc 100755 --- a/functions/PEAR/OLE/PPS/Root.php +++ b/functions/PEAR/OLE/PPS/Root.php @@ -20,7 +20,7 @@ // $Id: Root.php,v 1.10 2008/02/02 21:00:37 schmidt Exp $ -require_once( dirname(__FILE__) . '/../PPS.php'); +require_once( __DIR__ . '/../PPS.php'); require_once 'System.php'; /** @@ -36,7 +36,7 @@ class OLE_PPS_Root extends OLE_PPS * The temporary dir for storing the OLE file * @var string */ - var $_tmp_dir; + public $_tmp_dir; /** * Constructor @@ -132,7 +132,7 @@ function save($filename) } } // Make an array of PPS's (for Save) - $aList = array(); + $aList = []; $this->_savePpsSetPnt($aList); // calculate values for header list($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo); @@ -172,7 +172,7 @@ function save($filename) function _calcSize(&$raList) { // Calculate Basic Setting - list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0); + list($iSBDcnt, $iBBcnt, $iPPScnt) = [0,0,0]; $iSmallLen = 0; $iSBcnt = 0; for ($i = 0; $i < count($raList); $i++) { @@ -196,7 +196,7 @@ function _calcSize(&$raList) $iBdCnt = $this->_BIG_BLOCK_SIZE / OLE_PPS_SIZE; $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0)); - return array($iSBDcnt, $iBBcnt, $iPPScnt); + return [$iSBDcnt, $iBBcnt, $iPPScnt]; } /** @@ -318,7 +318,7 @@ function _saveBigData($iStBlk, &$raList) fwrite($FILE, $sBuff); } } else { - fwrite($FILE, $raList[$i]->_data); + fwrite($FILE, (string) $raList[$i]->_data); } if ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE) { @@ -408,7 +408,7 @@ function _savePps(&$raList) { // Save each PPS WK for ($i = 0; $i < count($raList); $i++) { - fwrite($this->_FILEH_, $raList[$i]->_getPpsWk()); + fwrite($this->_FILEH_, (string) $raList[$i]->_getPpsWk()); } // Adjust for Block $iCnt = count($raList); diff --git a/functions/PEAR/Spreadsheet/Excel/Writer.php b/functions/PEAR/Spreadsheet/Excel/Writer.php index 110e9982e..5d3606e31 100755 --- a/functions/PEAR/Spreadsheet/Excel/Writer.php +++ b/functions/PEAR/Spreadsheet/Excel/Writer.php @@ -32,7 +32,7 @@ */ require_once 'PEAR.php'; -require_once( dirname(__FILE__) . '/Writer/Workbook.php'); +require_once( __DIR__ . '/Writer/Workbook.php'); /** diff --git a/functions/PEAR/Spreadsheet/Excel/Writer/BIFFwriter.php b/functions/PEAR/Spreadsheet/Excel/Writer/BIFFwriter.php index a33f541cc..24460f616 100755 --- a/functions/PEAR/Spreadsheet/Excel/Writer/BIFFwriter.php +++ b/functions/PEAR/Spreadsheet/Excel/Writer/BIFFwriter.php @@ -57,38 +57,38 @@ class Spreadsheet_Excel_Writer_BIFFwriter extends PEAR * The BIFF/Excel version (5). * @var integer */ - var $_BIFF_version = 0x0500; + public $_BIFF_version = 0x0500; /** * The byte order of this architecture. 0 => little endian, 1 => big endian * @var integer */ - var $_byte_order; + public $_byte_order; /** * The string containing the data of the BIFF stream * @var string */ - var $_data; + public $_data; /** * The size of the data in bytes. Should be the same as strlen($this->_data) * @var integer */ - var $_datasize; + public $_datasize; /** * The maximum length for a BIFF record. See _addContinue() * @var integer * @see _addContinue() */ - var $_limit; + public $_limit; /** * The temporary dir for storing the OLE file * @var string */ - var $_tmp_dir; + public $_tmp_dir; /** * Constructor diff --git a/functions/PEAR/Spreadsheet/Excel/Writer/Format.php b/functions/PEAR/Spreadsheet/Excel/Writer/Format.php index 8403af5d7..b9216a617 100755 --- a/functions/PEAR/Spreadsheet/Excel/Writer/Format.php +++ b/functions/PEAR/Spreadsheet/Excel/Writer/Format.php @@ -49,199 +49,199 @@ class Spreadsheet_Excel_Writer_Format extends PEAR * The index given by the workbook when creating a new format. * @var integer */ - var $_xf_index; + public $_xf_index; /** * Index to the FONT record. * @var integer */ - var $font_index; + public $font_index; /** * The font name (ASCII). * @var string */ - var $_font_name; + public $_font_name; /** * Height of font (1/20 of a point) * @var integer */ - var $_size; + public $_size; /** * Bold style * @var integer */ - var $_bold; + public $_bold; /** * Bit specifiying if the font is italic. * @var integer */ - var $_italic; + public $_italic; /** * Index to the cell's color * @var integer */ - var $_color; + public $_color; /** * The text underline property * @var integer */ - var $_underline; + public $_underline; /** * Bit specifiying if the font has strikeout. * @var integer */ - var $_font_strikeout; + public $_font_strikeout; /** * Bit specifiying if the font has outline. * @var integer */ - var $_font_outline; + public $_font_outline; /** * Bit specifiying if the font has shadow. * @var integer */ - var $_font_shadow; + public $_font_shadow; /** * 2 bytes specifiying the script type for the font. * @var integer */ - var $_font_script; + public $_font_script; /** * Byte specifiying the font family. * @var integer */ - var $_font_family; + public $_font_family; /** * Byte specifiying the font charset. * @var integer */ - var $_font_charset; + public $_font_charset; /** * An index (2 bytes) to a FORMAT record (number format). * @var integer */ - var $_num_format; + public $_num_format; /** * Bit specifying if formulas are hidden. * @var integer */ - var $_hidden; + public $_hidden; /** * Bit specifying if the cell is locked. * @var integer */ - var $_locked; + public $_locked; /** * The three bits specifying the text horizontal alignment. * @var integer */ - var $_text_h_align; + public $_text_h_align; /** * Bit specifying if the text is wrapped at the right border. * @var integer */ - var $_text_wrap; + public $_text_wrap; /** * The three bits specifying the text vertical alignment. * @var integer */ - var $_text_v_align; + public $_text_v_align; /** * 1 bit, apparently not used. * @var integer */ - var $_text_justlast; + public $_text_justlast; /** * The two bits specifying the text rotation. * @var integer */ - var $_rotation; + public $_rotation; /** * The cell's foreground color. * @var integer */ - var $_fg_color; + public $_fg_color; /** * The cell's background color. * @var integer */ - var $_bg_color; + public $_bg_color; /** * The cell's background fill pattern. * @var integer */ - var $_pattern; + public $_pattern; /** * Style of the bottom border of the cell * @var integer */ - var $_bottom; + public $_bottom; /** * Color of the bottom border of the cell. * @var integer */ - var $_bottom_color; + public $_bottom_color; /** * Style of the top border of the cell * @var integer */ - var $_top; + public $_top; /** * Color of the top border of the cell. * @var integer */ - var $_top_color; + public $_top_color; /** * Style of the left border of the cell * @var integer */ - var $_left; + public $_left; /** * Color of the left border of the cell. * @var integer */ - var $_left_color; + public $_left_color; /** * Style of the right border of the cell * @var integer */ - var $_right; + public $_right; /** * Color of the right border of the cell. * @var integer */ - var $_right_color; + public $_right_color; /** * Constructor @@ -250,7 +250,7 @@ class Spreadsheet_Excel_Writer_Format extends PEAR * @param integer $index the XF index for the format. * @param array $properties array with properties to be set on initialization. */ - function __construct($BIFF_version, $index = 0, $properties = array()) + function __construct($BIFF_version, $index = 0, $properties = []) { $this->_xf_index = $index; $this->_BIFF_version = $BIFF_version; @@ -299,14 +299,14 @@ function __construct($BIFF_version, $index = 0, $properties = array()) // Set properties passed to Spreadsheet_Excel_Writer_Workbook::addFormat() foreach ($properties as $property => $value) { - if (method_exists($this, 'set'.ucwords($property))) { - $method_name = 'set'.ucwords($property); + if (method_exists($this, 'set'.ucwords((string) $property))) { + $method_name = 'set'.ucwords((string) $property); $this->{$method_name}($value); } } } - public function Spreadsheet_Excel_Writer_Format($BIFF_version, $index = 0, $properties = array()) { + public function Spreadsheet_Excel_Writer_Format($BIFF_version, $index = 0, $properties = []) { self::__construct($BIFF_version, $index, $properties); } @@ -537,7 +537,7 @@ function getXfIndex() */ function _getColor($name_color = '') { - $colors = array( + $colors = [ 'aqua' => 0x0F, 'cyan' => 0x0F, 'black' => 0x08, @@ -556,7 +556,7 @@ function _getColor($name_color = '') 'silver' => 0x16, 'white' => 0x09, 'yellow' => 0x0D - ); + ]; // Return the default color, 0x7FFF, if undef, if ($name_color == '') { diff --git a/functions/PEAR/Spreadsheet/Excel/Writer/Parser.php b/functions/PEAR/Spreadsheet/Excel/Writer/Parser.php index 9254a9634..0d63d37b2 100755 --- a/functions/PEAR/Spreadsheet/Excel/Writer/Parser.php +++ b/functions/PEAR/Spreadsheet/Excel/Writer/Parser.php @@ -114,55 +114,55 @@ class Spreadsheet_Excel_Writer_Parser extends PEAR * The index of the character we are currently looking at * @var integer */ - var $_current_char; + public $_current_char; /** * The token we are working on. * @var string */ - var $_current_token; + public $_current_token; /** * The formula to parse * @var string */ - var $_formula; + public $_formula; /** * The character ahead of the current char * @var string */ - var $_lookahead; + public $_lookahead; /** * The parse tree to be generated * @var string */ - var $_parse_tree; + public $_parse_tree; /** * The byte order. 1 => big endian, 0 => little endian. * @var integer */ - var $_byte_order; + public $_byte_order; /** * Array of external sheets * @var array */ - var $_ext_sheets; + public $_ext_sheets; /** * Array of sheet references in the form of REF structures * @var array */ - var $_references; + public $_references; /** * The BIFF version for the workbook * @var integer */ - var $_BIFF_version; + public $_BIFF_version; /** * The class constructor @@ -180,8 +180,8 @@ function __construct($byte_order, $biff_version) $this->_parse_tree = ''; // The parse tree to be generated. $this->_initializeHashes(); // Initialize the hashes: ptg's and function's ptg's $this->_byte_order = $byte_order; // Little Endian or Big Endian - $this->_ext_sheets = array(); - $this->_references = array(); + $this->_ext_sheets = []; + $this->_references = []; } function Spreadsheet_Excel_Writer_Parser($byte_order, $biff_version) @@ -198,7 +198,7 @@ function Spreadsheet_Excel_Writer_Parser($byte_order, $biff_version) function _initializeHashes() { // The Excel ptg indices - $this->ptg = array( + $this->ptg = [ 'ptgExp' => 0x01, 'ptgTbl' => 0x02, 'ptgAdd' => 0x03, @@ -294,7 +294,7 @@ function _initializeHashes() 'ptgArea3dA' => 0x7B, 'ptgRefErr3dA' => 0x7C, 'ptgAreaErr3d' => 0x7D - ); + ]; // Thanks to Michael Meeks and Gnumeric for the initial arg values. // @@ -309,234 +309,234 @@ function _initializeHashes() // class: The reference, value or array class of the function args. // vol: The function is volatile. // - $this->_functions = array( + $this->_functions = [ // function ptg args class vol - 'COUNT' => array( 0, -1, 0, 0 ), - 'IF' => array( 1, -1, 1, 0 ), - 'ISNA' => array( 2, 1, 1, 0 ), - 'ISERROR' => array( 3, 1, 1, 0 ), - 'SUM' => array( 4, -1, 0, 0 ), - 'AVERAGE' => array( 5, -1, 0, 0 ), - 'MIN' => array( 6, -1, 0, 0 ), - 'MAX' => array( 7, -1, 0, 0 ), - 'ROW' => array( 8, -1, 0, 0 ), - 'COLUMN' => array( 9, -1, 0, 0 ), - 'NA' => array( 10, 0, 0, 0 ), - 'NPV' => array( 11, -1, 1, 0 ), - 'STDEV' => array( 12, -1, 0, 0 ), - 'DOLLAR' => array( 13, -1, 1, 0 ), - 'FIXED' => array( 14, -1, 1, 0 ), - 'SIN' => array( 15, 1, 1, 0 ), - 'COS' => array( 16, 1, 1, 0 ), - 'TAN' => array( 17, 1, 1, 0 ), - 'ATAN' => array( 18, 1, 1, 0 ), - 'PI' => array( 19, 0, 1, 0 ), - 'SQRT' => array( 20, 1, 1, 0 ), - 'EXP' => array( 21, 1, 1, 0 ), - 'LN' => array( 22, 1, 1, 0 ), - 'LOG10' => array( 23, 1, 1, 0 ), - 'ABS' => array( 24, 1, 1, 0 ), - 'INT' => array( 25, 1, 1, 0 ), - 'SIGN' => array( 26, 1, 1, 0 ), - 'ROUND' => array( 27, 2, 1, 0 ), - 'LOOKUP' => array( 28, -1, 0, 0 ), - 'INDEX' => array( 29, -1, 0, 1 ), - 'REPT' => array( 30, 2, 1, 0 ), - 'MID' => array( 31, 3, 1, 0 ), - 'LEN' => array( 32, 1, 1, 0 ), - 'VALUE' => array( 33, 1, 1, 0 ), - 'TRUE' => array( 34, 0, 1, 0 ), - 'FALSE' => array( 35, 0, 1, 0 ), - 'AND' => array( 36, -1, 0, 0 ), - 'OR' => array( 37, -1, 0, 0 ), - 'NOT' => array( 38, 1, 1, 0 ), - 'MOD' => array( 39, 2, 1, 0 ), - 'DCOUNT' => array( 40, 3, 0, 0 ), - 'DSUM' => array( 41, 3, 0, 0 ), - 'DAVERAGE' => array( 42, 3, 0, 0 ), - 'DMIN' => array( 43, 3, 0, 0 ), - 'DMAX' => array( 44, 3, 0, 0 ), - 'DSTDEV' => array( 45, 3, 0, 0 ), - 'VAR' => array( 46, -1, 0, 0 ), - 'DVAR' => array( 47, 3, 0, 0 ), - 'TEXT' => array( 48, 2, 1, 0 ), - 'LINEST' => array( 49, -1, 0, 0 ), - 'TREND' => array( 50, -1, 0, 0 ), - 'LOGEST' => array( 51, -1, 0, 0 ), - 'GROWTH' => array( 52, -1, 0, 0 ), - 'PV' => array( 56, -1, 1, 0 ), - 'FV' => array( 57, -1, 1, 0 ), - 'NPER' => array( 58, -1, 1, 0 ), - 'PMT' => array( 59, -1, 1, 0 ), - 'RATE' => array( 60, -1, 1, 0 ), - 'MIRR' => array( 61, 3, 0, 0 ), - 'IRR' => array( 62, -1, 0, 0 ), - 'RAND' => array( 63, 0, 1, 1 ), - 'MATCH' => array( 64, -1, 0, 0 ), - 'DATE' => array( 65, 3, 1, 0 ), - 'TIME' => array( 66, 3, 1, 0 ), - 'DAY' => array( 67, 1, 1, 0 ), - 'MONTH' => array( 68, 1, 1, 0 ), - 'YEAR' => array( 69, 1, 1, 0 ), - 'WEEKDAY' => array( 70, -1, 1, 0 ), - 'HOUR' => array( 71, 1, 1, 0 ), - 'MINUTE' => array( 72, 1, 1, 0 ), - 'SECOND' => array( 73, 1, 1, 0 ), - 'NOW' => array( 74, 0, 1, 1 ), - 'AREAS' => array( 75, 1, 0, 1 ), - 'ROWS' => array( 76, 1, 0, 1 ), - 'COLUMNS' => array( 77, 1, 0, 1 ), - 'OFFSET' => array( 78, -1, 0, 1 ), - 'SEARCH' => array( 82, -1, 1, 0 ), - 'TRANSPOSE' => array( 83, 1, 1, 0 ), - 'TYPE' => array( 86, 1, 1, 0 ), - 'ATAN2' => array( 97, 2, 1, 0 ), - 'ASIN' => array( 98, 1, 1, 0 ), - 'ACOS' => array( 99, 1, 1, 0 ), - 'CHOOSE' => array( 100, -1, 1, 0 ), - 'HLOOKUP' => array( 101, -1, 0, 0 ), - 'VLOOKUP' => array( 102, -1, 0, 0 ), - 'ISREF' => array( 105, 1, 0, 0 ), - 'LOG' => array( 109, -1, 1, 0 ), - 'CHAR' => array( 111, 1, 1, 0 ), - 'LOWER' => array( 112, 1, 1, 0 ), - 'UPPER' => array( 113, 1, 1, 0 ), - 'PROPER' => array( 114, 1, 1, 0 ), - 'LEFT' => array( 115, -1, 1, 0 ), - 'RIGHT' => array( 116, -1, 1, 0 ), - 'EXACT' => array( 117, 2, 1, 0 ), - 'TRIM' => array( 118, 1, 1, 0 ), - 'REPLACE' => array( 119, 4, 1, 0 ), - 'SUBSTITUTE' => array( 120, -1, 1, 0 ), - 'CODE' => array( 121, 1, 1, 0 ), - 'FIND' => array( 124, -1, 1, 0 ), - 'CELL' => array( 125, -1, 0, 1 ), - 'ISERR' => array( 126, 1, 1, 0 ), - 'ISTEXT' => array( 127, 1, 1, 0 ), - 'ISNUMBER' => array( 128, 1, 1, 0 ), - 'ISBLANK' => array( 129, 1, 1, 0 ), - 'T' => array( 130, 1, 0, 0 ), - 'N' => array( 131, 1, 0, 0 ), - 'DATEVALUE' => array( 140, 1, 1, 0 ), - 'TIMEVALUE' => array( 141, 1, 1, 0 ), - 'SLN' => array( 142, 3, 1, 0 ), - 'SYD' => array( 143, 4, 1, 0 ), - 'DDB' => array( 144, -1, 1, 0 ), - 'INDIRECT' => array( 148, -1, 1, 1 ), - 'CALL' => array( 150, -1, 1, 0 ), - 'CLEAN' => array( 162, 1, 1, 0 ), - 'MDETERM' => array( 163, 1, 2, 0 ), - 'MINVERSE' => array( 164, 1, 2, 0 ), - 'MMULT' => array( 165, 2, 2, 0 ), - 'IPMT' => array( 167, -1, 1, 0 ), - 'PPMT' => array( 168, -1, 1, 0 ), - 'COUNTA' => array( 169, -1, 0, 0 ), - 'PRODUCT' => array( 183, -1, 0, 0 ), - 'FACT' => array( 184, 1, 1, 0 ), - 'DPRODUCT' => array( 189, 3, 0, 0 ), - 'ISNONTEXT' => array( 190, 1, 1, 0 ), - 'STDEVP' => array( 193, -1, 0, 0 ), - 'VARP' => array( 194, -1, 0, 0 ), - 'DSTDEVP' => array( 195, 3, 0, 0 ), - 'DVARP' => array( 196, 3, 0, 0 ), - 'TRUNC' => array( 197, -1, 1, 0 ), - 'ISLOGICAL' => array( 198, 1, 1, 0 ), - 'DCOUNTA' => array( 199, 3, 0, 0 ), - 'ROUNDUP' => array( 212, 2, 1, 0 ), - 'ROUNDDOWN' => array( 213, 2, 1, 0 ), - 'RANK' => array( 216, -1, 0, 0 ), - 'ADDRESS' => array( 219, -1, 1, 0 ), - 'DAYS360' => array( 220, -1, 1, 0 ), - 'TODAY' => array( 221, 0, 1, 1 ), - 'VDB' => array( 222, -1, 1, 0 ), - 'MEDIAN' => array( 227, -1, 0, 0 ), - 'SUMPRODUCT' => array( 228, -1, 2, 0 ), - 'SINH' => array( 229, 1, 1, 0 ), - 'COSH' => array( 230, 1, 1, 0 ), - 'TANH' => array( 231, 1, 1, 0 ), - 'ASINH' => array( 232, 1, 1, 0 ), - 'ACOSH' => array( 233, 1, 1, 0 ), - 'ATANH' => array( 234, 1, 1, 0 ), - 'DGET' => array( 235, 3, 0, 0 ), - 'INFO' => array( 244, 1, 1, 1 ), - 'DB' => array( 247, -1, 1, 0 ), - 'FREQUENCY' => array( 252, 2, 0, 0 ), - 'ERROR.TYPE' => array( 261, 1, 1, 0 ), - 'REGISTER.ID' => array( 267, -1, 1, 0 ), - 'AVEDEV' => array( 269, -1, 0, 0 ), - 'BETADIST' => array( 270, -1, 1, 0 ), - 'GAMMALN' => array( 271, 1, 1, 0 ), - 'BETAINV' => array( 272, -1, 1, 0 ), - 'BINOMDIST' => array( 273, 4, 1, 0 ), - 'CHIDIST' => array( 274, 2, 1, 0 ), - 'CHIINV' => array( 275, 2, 1, 0 ), - 'COMBIN' => array( 276, 2, 1, 0 ), - 'CONFIDENCE' => array( 277, 3, 1, 0 ), - 'CRITBINOM' => array( 278, 3, 1, 0 ), - 'EVEN' => array( 279, 1, 1, 0 ), - 'EXPONDIST' => array( 280, 3, 1, 0 ), - 'FDIST' => array( 281, 3, 1, 0 ), - 'FINV' => array( 282, 3, 1, 0 ), - 'FISHER' => array( 283, 1, 1, 0 ), - 'FISHERINV' => array( 284, 1, 1, 0 ), - 'FLOOR' => array( 285, 2, 1, 0 ), - 'GAMMADIST' => array( 286, 4, 1, 0 ), - 'GAMMAINV' => array( 287, 3, 1, 0 ), - 'CEILING' => array( 288, 2, 1, 0 ), - 'HYPGEOMDIST' => array( 289, 4, 1, 0 ), - 'LOGNORMDIST' => array( 290, 3, 1, 0 ), - 'LOGINV' => array( 291, 3, 1, 0 ), - 'NEGBINOMDIST' => array( 292, 3, 1, 0 ), - 'NORMDIST' => array( 293, 4, 1, 0 ), - 'NORMSDIST' => array( 294, 1, 1, 0 ), - 'NORMINV' => array( 295, 3, 1, 0 ), - 'NORMSINV' => array( 296, 1, 1, 0 ), - 'STANDARDIZE' => array( 297, 3, 1, 0 ), - 'ODD' => array( 298, 1, 1, 0 ), - 'PERMUT' => array( 299, 2, 1, 0 ), - 'POISSON' => array( 300, 3, 1, 0 ), - 'TDIST' => array( 301, 3, 1, 0 ), - 'WEIBULL' => array( 302, 4, 1, 0 ), - 'SUMXMY2' => array( 303, 2, 2, 0 ), - 'SUMX2MY2' => array( 304, 2, 2, 0 ), - 'SUMX2PY2' => array( 305, 2, 2, 0 ), - 'CHITEST' => array( 306, 2, 2, 0 ), - 'CORREL' => array( 307, 2, 2, 0 ), - 'COVAR' => array( 308, 2, 2, 0 ), - 'FORECAST' => array( 309, 3, 2, 0 ), - 'FTEST' => array( 310, 2, 2, 0 ), - 'INTERCEPT' => array( 311, 2, 2, 0 ), - 'PEARSON' => array( 312, 2, 2, 0 ), - 'RSQ' => array( 313, 2, 2, 0 ), - 'STEYX' => array( 314, 2, 2, 0 ), - 'SLOPE' => array( 315, 2, 2, 0 ), - 'TTEST' => array( 316, 4, 2, 0 ), - 'PROB' => array( 317, -1, 2, 0 ), - 'DEVSQ' => array( 318, -1, 0, 0 ), - 'GEOMEAN' => array( 319, -1, 0, 0 ), - 'HARMEAN' => array( 320, -1, 0, 0 ), - 'SUMSQ' => array( 321, -1, 0, 0 ), - 'KURT' => array( 322, -1, 0, 0 ), - 'SKEW' => array( 323, -1, 0, 0 ), - 'ZTEST' => array( 324, -1, 0, 0 ), - 'LARGE' => array( 325, 2, 0, 0 ), - 'SMALL' => array( 326, 2, 0, 0 ), - 'QUARTILE' => array( 327, 2, 0, 0 ), - 'PERCENTILE' => array( 328, 2, 0, 0 ), - 'PERCENTRANK' => array( 329, -1, 0, 0 ), - 'MODE' => array( 330, -1, 2, 0 ), - 'TRIMMEAN' => array( 331, 2, 0, 0 ), - 'TINV' => array( 332, 2, 1, 0 ), - 'CONCATENATE' => array( 336, -1, 1, 0 ), - 'POWER' => array( 337, 2, 1, 0 ), - 'RADIANS' => array( 342, 1, 1, 0 ), - 'DEGREES' => array( 343, 1, 1, 0 ), - 'SUBTOTAL' => array( 344, -1, 0, 0 ), - 'SUMIF' => array( 345, -1, 0, 0 ), - 'COUNTIF' => array( 346, 2, 0, 0 ), - 'COUNTBLANK' => array( 347, 1, 0, 0 ), - 'ROMAN' => array( 354, -1, 1, 0 ) - ); + 'COUNT' => [ 0, -1, 0, 0 ], + 'IF' => [ 1, -1, 1, 0 ], + 'ISNA' => [ 2, 1, 1, 0 ], + 'ISERROR' => [ 3, 1, 1, 0 ], + 'SUM' => [ 4, -1, 0, 0 ], + 'AVERAGE' => [ 5, -1, 0, 0 ], + 'MIN' => [ 6, -1, 0, 0 ], + 'MAX' => [ 7, -1, 0, 0 ], + 'ROW' => [ 8, -1, 0, 0 ], + 'COLUMN' => [ 9, -1, 0, 0 ], + 'NA' => [ 10, 0, 0, 0 ], + 'NPV' => [ 11, -1, 1, 0 ], + 'STDEV' => [ 12, -1, 0, 0 ], + 'DOLLAR' => [ 13, -1, 1, 0 ], + 'FIXED' => [ 14, -1, 1, 0 ], + 'SIN' => [ 15, 1, 1, 0 ], + 'COS' => [ 16, 1, 1, 0 ], + 'TAN' => [ 17, 1, 1, 0 ], + 'ATAN' => [ 18, 1, 1, 0 ], + 'PI' => [ 19, 0, 1, 0 ], + 'SQRT' => [ 20, 1, 1, 0 ], + 'EXP' => [ 21, 1, 1, 0 ], + 'LN' => [ 22, 1, 1, 0 ], + 'LOG10' => [ 23, 1, 1, 0 ], + 'ABS' => [ 24, 1, 1, 0 ], + 'INT' => [ 25, 1, 1, 0 ], + 'SIGN' => [ 26, 1, 1, 0 ], + 'ROUND' => [ 27, 2, 1, 0 ], + 'LOOKUP' => [ 28, -1, 0, 0 ], + 'INDEX' => [ 29, -1, 0, 1 ], + 'REPT' => [ 30, 2, 1, 0 ], + 'MID' => [ 31, 3, 1, 0 ], + 'LEN' => [ 32, 1, 1, 0 ], + 'VALUE' => [ 33, 1, 1, 0 ], + 'TRUE' => [ 34, 0, 1, 0 ], + 'FALSE' => [ 35, 0, 1, 0 ], + 'AND' => [ 36, -1, 0, 0 ], + 'OR' => [ 37, -1, 0, 0 ], + 'NOT' => [ 38, 1, 1, 0 ], + 'MOD' => [ 39, 2, 1, 0 ], + 'DCOUNT' => [ 40, 3, 0, 0 ], + 'DSUM' => [ 41, 3, 0, 0 ], + 'DAVERAGE' => [ 42, 3, 0, 0 ], + 'DMIN' => [ 43, 3, 0, 0 ], + 'DMAX' => [ 44, 3, 0, 0 ], + 'DSTDEV' => [ 45, 3, 0, 0 ], + 'VAR' => [ 46, -1, 0, 0 ], + 'DVAR' => [ 47, 3, 0, 0 ], + 'TEXT' => [ 48, 2, 1, 0 ], + 'LINEST' => [ 49, -1, 0, 0 ], + 'TREND' => [ 50, -1, 0, 0 ], + 'LOGEST' => [ 51, -1, 0, 0 ], + 'GROWTH' => [ 52, -1, 0, 0 ], + 'PV' => [ 56, -1, 1, 0 ], + 'FV' => [ 57, -1, 1, 0 ], + 'NPER' => [ 58, -1, 1, 0 ], + 'PMT' => [ 59, -1, 1, 0 ], + 'RATE' => [ 60, -1, 1, 0 ], + 'MIRR' => [ 61, 3, 0, 0 ], + 'IRR' => [ 62, -1, 0, 0 ], + 'RAND' => [ 63, 0, 1, 1 ], + 'MATCH' => [ 64, -1, 0, 0 ], + 'DATE' => [ 65, 3, 1, 0 ], + 'TIME' => [ 66, 3, 1, 0 ], + 'DAY' => [ 67, 1, 1, 0 ], + 'MONTH' => [ 68, 1, 1, 0 ], + 'YEAR' => [ 69, 1, 1, 0 ], + 'WEEKDAY' => [ 70, -1, 1, 0 ], + 'HOUR' => [ 71, 1, 1, 0 ], + 'MINUTE' => [ 72, 1, 1, 0 ], + 'SECOND' => [ 73, 1, 1, 0 ], + 'NOW' => [ 74, 0, 1, 1 ], + 'AREAS' => [ 75, 1, 0, 1 ], + 'ROWS' => [ 76, 1, 0, 1 ], + 'COLUMNS' => [ 77, 1, 0, 1 ], + 'OFFSET' => [ 78, -1, 0, 1 ], + 'SEARCH' => [ 82, -1, 1, 0 ], + 'TRANSPOSE' => [ 83, 1, 1, 0 ], + 'TYPE' => [ 86, 1, 1, 0 ], + 'ATAN2' => [ 97, 2, 1, 0 ], + 'ASIN' => [ 98, 1, 1, 0 ], + 'ACOS' => [ 99, 1, 1, 0 ], + 'CHOOSE' => [ 100, -1, 1, 0 ], + 'HLOOKUP' => [ 101, -1, 0, 0 ], + 'VLOOKUP' => [ 102, -1, 0, 0 ], + 'ISREF' => [ 105, 1, 0, 0 ], + 'LOG' => [ 109, -1, 1, 0 ], + 'CHAR' => [ 111, 1, 1, 0 ], + 'LOWER' => [ 112, 1, 1, 0 ], + 'UPPER' => [ 113, 1, 1, 0 ], + 'PROPER' => [ 114, 1, 1, 0 ], + 'LEFT' => [ 115, -1, 1, 0 ], + 'RIGHT' => [ 116, -1, 1, 0 ], + 'EXACT' => [ 117, 2, 1, 0 ], + 'TRIM' => [ 118, 1, 1, 0 ], + 'REPLACE' => [ 119, 4, 1, 0 ], + 'SUBSTITUTE' => [ 120, -1, 1, 0 ], + 'CODE' => [ 121, 1, 1, 0 ], + 'FIND' => [ 124, -1, 1, 0 ], + 'CELL' => [ 125, -1, 0, 1 ], + 'ISERR' => [ 126, 1, 1, 0 ], + 'ISTEXT' => [ 127, 1, 1, 0 ], + 'ISNUMBER' => [ 128, 1, 1, 0 ], + 'ISBLANK' => [ 129, 1, 1, 0 ], + 'T' => [ 130, 1, 0, 0 ], + 'N' => [ 131, 1, 0, 0 ], + 'DATEVALUE' => [ 140, 1, 1, 0 ], + 'TIMEVALUE' => [ 141, 1, 1, 0 ], + 'SLN' => [ 142, 3, 1, 0 ], + 'SYD' => [ 143, 4, 1, 0 ], + 'DDB' => [ 144, -1, 1, 0 ], + 'INDIRECT' => [ 148, -1, 1, 1 ], + 'CALL' => [ 150, -1, 1, 0 ], + 'CLEAN' => [ 162, 1, 1, 0 ], + 'MDETERM' => [ 163, 1, 2, 0 ], + 'MINVERSE' => [ 164, 1, 2, 0 ], + 'MMULT' => [ 165, 2, 2, 0 ], + 'IPMT' => [ 167, -1, 1, 0 ], + 'PPMT' => [ 168, -1, 1, 0 ], + 'COUNTA' => [ 169, -1, 0, 0 ], + 'PRODUCT' => [ 183, -1, 0, 0 ], + 'FACT' => [ 184, 1, 1, 0 ], + 'DPRODUCT' => [ 189, 3, 0, 0 ], + 'ISNONTEXT' => [ 190, 1, 1, 0 ], + 'STDEVP' => [ 193, -1, 0, 0 ], + 'VARP' => [ 194, -1, 0, 0 ], + 'DSTDEVP' => [ 195, 3, 0, 0 ], + 'DVARP' => [ 196, 3, 0, 0 ], + 'TRUNC' => [ 197, -1, 1, 0 ], + 'ISLOGICAL' => [ 198, 1, 1, 0 ], + 'DCOUNTA' => [ 199, 3, 0, 0 ], + 'ROUNDUP' => [ 212, 2, 1, 0 ], + 'ROUNDDOWN' => [ 213, 2, 1, 0 ], + 'RANK' => [ 216, -1, 0, 0 ], + 'ADDRESS' => [ 219, -1, 1, 0 ], + 'DAYS360' => [ 220, -1, 1, 0 ], + 'TODAY' => [ 221, 0, 1, 1 ], + 'VDB' => [ 222, -1, 1, 0 ], + 'MEDIAN' => [ 227, -1, 0, 0 ], + 'SUMPRODUCT' => [ 228, -1, 2, 0 ], + 'SINH' => [ 229, 1, 1, 0 ], + 'COSH' => [ 230, 1, 1, 0 ], + 'TANH' => [ 231, 1, 1, 0 ], + 'ASINH' => [ 232, 1, 1, 0 ], + 'ACOSH' => [ 233, 1, 1, 0 ], + 'ATANH' => [ 234, 1, 1, 0 ], + 'DGET' => [ 235, 3, 0, 0 ], + 'INFO' => [ 244, 1, 1, 1 ], + 'DB' => [ 247, -1, 1, 0 ], + 'FREQUENCY' => [ 252, 2, 0, 0 ], + 'ERROR.TYPE' => [ 261, 1, 1, 0 ], + 'REGISTER.ID' => [ 267, -1, 1, 0 ], + 'AVEDEV' => [ 269, -1, 0, 0 ], + 'BETADIST' => [ 270, -1, 1, 0 ], + 'GAMMALN' => [ 271, 1, 1, 0 ], + 'BETAINV' => [ 272, -1, 1, 0 ], + 'BINOMDIST' => [ 273, 4, 1, 0 ], + 'CHIDIST' => [ 274, 2, 1, 0 ], + 'CHIINV' => [ 275, 2, 1, 0 ], + 'COMBIN' => [ 276, 2, 1, 0 ], + 'CONFIDENCE' => [ 277, 3, 1, 0 ], + 'CRITBINOM' => [ 278, 3, 1, 0 ], + 'EVEN' => [ 279, 1, 1, 0 ], + 'EXPONDIST' => [ 280, 3, 1, 0 ], + 'FDIST' => [ 281, 3, 1, 0 ], + 'FINV' => [ 282, 3, 1, 0 ], + 'FISHER' => [ 283, 1, 1, 0 ], + 'FISHERINV' => [ 284, 1, 1, 0 ], + 'FLOOR' => [ 285, 2, 1, 0 ], + 'GAMMADIST' => [ 286, 4, 1, 0 ], + 'GAMMAINV' => [ 287, 3, 1, 0 ], + 'CEILING' => [ 288, 2, 1, 0 ], + 'HYPGEOMDIST' => [ 289, 4, 1, 0 ], + 'LOGNORMDIST' => [ 290, 3, 1, 0 ], + 'LOGINV' => [ 291, 3, 1, 0 ], + 'NEGBINOMDIST' => [ 292, 3, 1, 0 ], + 'NORMDIST' => [ 293, 4, 1, 0 ], + 'NORMSDIST' => [ 294, 1, 1, 0 ], + 'NORMINV' => [ 295, 3, 1, 0 ], + 'NORMSINV' => [ 296, 1, 1, 0 ], + 'STANDARDIZE' => [ 297, 3, 1, 0 ], + 'ODD' => [ 298, 1, 1, 0 ], + 'PERMUT' => [ 299, 2, 1, 0 ], + 'POISSON' => [ 300, 3, 1, 0 ], + 'TDIST' => [ 301, 3, 1, 0 ], + 'WEIBULL' => [ 302, 4, 1, 0 ], + 'SUMXMY2' => [ 303, 2, 2, 0 ], + 'SUMX2MY2' => [ 304, 2, 2, 0 ], + 'SUMX2PY2' => [ 305, 2, 2, 0 ], + 'CHITEST' => [ 306, 2, 2, 0 ], + 'CORREL' => [ 307, 2, 2, 0 ], + 'COVAR' => [ 308, 2, 2, 0 ], + 'FORECAST' => [ 309, 3, 2, 0 ], + 'FTEST' => [ 310, 2, 2, 0 ], + 'INTERCEPT' => [ 311, 2, 2, 0 ], + 'PEARSON' => [ 312, 2, 2, 0 ], + 'RSQ' => [ 313, 2, 2, 0 ], + 'STEYX' => [ 314, 2, 2, 0 ], + 'SLOPE' => [ 315, 2, 2, 0 ], + 'TTEST' => [ 316, 4, 2, 0 ], + 'PROB' => [ 317, -1, 2, 0 ], + 'DEVSQ' => [ 318, -1, 0, 0 ], + 'GEOMEAN' => [ 319, -1, 0, 0 ], + 'HARMEAN' => [ 320, -1, 0, 0 ], + 'SUMSQ' => [ 321, -1, 0, 0 ], + 'KURT' => [ 322, -1, 0, 0 ], + 'SKEW' => [ 323, -1, 0, 0 ], + 'ZTEST' => [ 324, -1, 0, 0 ], + 'LARGE' => [ 325, 2, 0, 0 ], + 'SMALL' => [ 326, 2, 0, 0 ], + 'QUARTILE' => [ 327, 2, 0, 0 ], + 'PERCENTILE' => [ 328, 2, 0, 0 ], + 'PERCENTRANK' => [ 329, -1, 0, 0 ], + 'MODE' => [ 330, -1, 2, 0 ], + 'TRIMMEAN' => [ 331, 2, 0, 0 ], + 'TINV' => [ 332, 2, 1, 0 ], + 'CONCATENATE' => [ 336, -1, 1, 0 ], + 'POWER' => [ 337, 2, 1, 0 ], + 'RADIANS' => [ 342, 1, 1, 0 ], + 'DEGREES' => [ 343, 1, 1, 0 ], + 'SUBTOTAL' => [ 344, -1, 0, 0 ], + 'SUMIF' => [ 345, -1, 0, 0 ], + 'COUNTIF' => [ 346, 2, 0, 0 ], + 'COUNTBLANK' => [ 347, 1, 0, 0 ], + 'ROMAN' => [ 354, -1, 1, 0 ] + ]; } /** @@ -549,38 +549,38 @@ function _initializeHashes() */ function _convert($token) { - if (preg_match("/^\"[^\"]{0,255}\"$/", $token)) { + if (preg_match("/^\"[^\"]{0,255}\"$/", (string) $token)) { return $this->_convertString($token); } elseif (is_numeric($token)) { return $this->_convertNumber($token); // match references like A1 or $A$1 - } elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/',$token)) { + } elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/',(string) $token)) { return $this->_convertRef2d($token); // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 - } elseif (preg_match("/^\w+(\:\w+)?\![A-Ia-i]?[A-Za-z](\d+)$/u",$token)) { + } elseif (preg_match("/^\w+(\:\w+)?\![A-Ia-i]?[A-Za-z](\d+)$/u",(string) $token)) { return $this->_convertRef3d($token); // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 - } elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\![A-Ia-i]?[A-Za-z](\d+)$/u",$token)) { + } elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\![A-Ia-i]?[A-Za-z](\d+)$/u",(string) $token)) { return $this->_convertRef3d($token); // match ranges like A1:B2 - } elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/",$token)) { + } elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/",(string) $token)) { return $this->_convertRange2d($token); // match ranges like A1..B2 - } elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/",$token)) { + } elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/",(string) $token)) { return $this->_convertRange2d($token); // match external ranges like Sheet1!A1 or Sheet1:Sheet2!A1:B2 - } elseif (preg_match("/^\w+(\:\w+)?\!([A-Ia-i]?[A-Za-z])?(\d+)\:([A-Ia-i]?[A-Za-z])?(\d+)$/u",$token)) { + } elseif (preg_match("/^\w+(\:\w+)?\!([A-Ia-i]?[A-Za-z])?(\d+)\:([A-Ia-i]?[A-Za-z])?(\d+)$/u",(string) $token)) { return $this->_convertRange3d($token); // match external ranges like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1:B2 - } elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\!([A-Ia-i]?[A-Za-z])?(\d+)\:([A-Ia-i]?[A-Za-z])?(\d+)$/u",$token)) { + } elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\!([A-Ia-i]?[A-Za-z])?(\d+)\:([A-Ia-i]?[A-Za-z])?(\d+)$/u",(string) $token)) { return $this->_convertRange3d($token); // operators (including parentheses) @@ -610,11 +610,11 @@ function _convert($token) function _convertNumber($num) { // Integer in the range 0..2**16-1 - if ((preg_match("/^\d+$/", $num)) and ($num <= 65535)) { + if ((preg_match("/^\d+$/", (string) $num)) and ($num <= 65535)) { return pack("Cv", $this->ptg['ptgInt'], $num); } else { // A float if ($this->_byte_order) { // if it's Big Endian - $num = strrev($num); + $num = strrev((string) $num); } return pack("Cd", $this->ptg['ptgNum'], $num); } @@ -868,11 +868,11 @@ function _convertRef3d($cell) function _packExtRef($ext_ref) { $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any. - $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any. + $ext_ref = preg_replace("/'$/", '', (string) $ext_ref); // Remove trailing ' if any. // Check if there is a sheet range eg., Sheet1:Sheet2. - if (preg_match("/:/", $ext_ref)) { - list($sheet_name1, $sheet_name2) = preg_split('/:/', $ext_ref); + if (preg_match("/:/", (string) $ext_ref)) { + list($sheet_name1, $sheet_name2) = preg_split('/:/', (string) $ext_ref); $sheet1 = $this->_getSheetIndex($sheet_name1); if ($sheet1 == -1) { @@ -885,7 +885,7 @@ function _packExtRef($ext_ref) // Reverse max and min sheet numbers if necessary if ($sheet1 > $sheet2) { - list($sheet1, $sheet2) = array($sheet2, $sheet1); + list($sheet1, $sheet2) = [$sheet2, $sheet1]; } } else { // Single sheet name only. $sheet1 = $this->_getSheetIndex($ext_ref); @@ -914,11 +914,11 @@ function _packExtRef($ext_ref) function _getRefIndex($ext_ref) { $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any. - $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any. + $ext_ref = preg_replace("/'$/", '', (string) $ext_ref); // Remove trailing ' if any. // Check if there is a sheet range eg., Sheet1:Sheet2. - if (preg_match("/:/", $ext_ref)) { - list($sheet_name1, $sheet_name2) = preg_split('/:/', $ext_ref); + if (preg_match("/:/", (string) $ext_ref)) { + list($sheet_name1, $sheet_name2) = preg_split('/:/', (string) $ext_ref); $sheet1 = $this->_getSheetIndex($sheet_name1); if ($sheet1 == -1) { @@ -931,7 +931,7 @@ function _getRefIndex($ext_ref) // Reverse max and min sheet numbers if necessary if ($sheet1 > $sheet2) { - list($sheet1, $sheet2) = array($sheet2, $sheet1); + list($sheet1, $sheet2) = [$sheet2, $sheet1]; } } else { // Single sheet name only. $sheet1 = $this->_getSheetIndex($ext_ref); @@ -1024,7 +1024,7 @@ function _cellToPackedRowcol($cell) } $row = pack('v', $row); - return array($row, $col); + return [$row, $col]; } /** @@ -1070,7 +1070,7 @@ function _rangeToPackedRange($range) $row1 = pack('v', $row1); $row2 = pack('v', $row2); - return array($row1, $col1, $row2, $col2); + return [$row1, $col1, $row2, $col2]; } /** @@ -1104,7 +1104,7 @@ function _cellToRowcol($cell) $row--; $col--; - return array($row, $col, $row_rel, $col_rel); + return [$row, $col, $row_rel, $col_rel]; } /** @@ -1219,7 +1219,7 @@ function _match($token) break; default: // if it's a reference - if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$token) and + if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',(string) $token) and !preg_match("/[0-9]/",$this->_lookahead) and ($this->_lookahead != ':') and ($this->_lookahead != '.') and ($this->_lookahead != '!')) @@ -1227,39 +1227,39 @@ function _match($token) return $token; } // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1) - elseif (preg_match("/^\w+(\:\w+)?\![A-Ia-i]?[A-Za-z][0-9]+$/u",$token) and + elseif (preg_match("/^\w+(\:\w+)?\![A-Ia-i]?[A-Za-z][0-9]+$/u",(string) $token) and !preg_match("/[0-9]/",$this->_lookahead) and ($this->_lookahead != ':') and ($this->_lookahead != '.')) { return $token; } // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1) - elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\![A-Ia-i]?[A-Za-z][0-9]+$/u",$token) and + elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\![A-Ia-i]?[A-Za-z][0-9]+$/u",(string) $token) and !preg_match("/[0-9]/",$this->_lookahead) and ($this->_lookahead != ':') and ($this->_lookahead != '.')) { return $token; } // if it's a range (A1:A2) - elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",$token) and + elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",(string) $token) and !preg_match("/[0-9]/",$this->_lookahead)) { return $token; } // if it's a range (A1..A2) - elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",$token) and + elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",(string) $token) and !preg_match("/[0-9]/",$this->_lookahead)) { return $token; } // If it's an external range like Sheet1!A1 or Sheet1:Sheet2!A1:B2 - elseif (preg_match("/^\w+(\:\w+)?\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/u",$token) and + elseif (preg_match("/^\w+(\:\w+)?\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/u",(string) $token) and !preg_match("/[0-9]/",$this->_lookahead)) { return $token; } // If it's an external range like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1:B2 - elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/u",$token) and + elseif (preg_match("/^'[\w -]+(\:[\w -]+)?'\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/u",(string) $token) and !preg_match("/[0-9]/",$this->_lookahead)) { return $token; @@ -1272,12 +1272,12 @@ function _match($token) return $token; } // If it's a string (of maximum 255 characters) - elseif (preg_match("/^\"[^\"]{0,255}\"$/",$token)) + elseif (preg_match("/^\"[^\"]{0,255}\"$/",(string) $token)) { return $token; } // if it's a function call - elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$token) and ($this->_lookahead == "(")) + elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",(string) $token) and ($this->_lookahead == "(")) { return $token; } @@ -1617,7 +1617,7 @@ function _func() */ function _createTree($value, $left, $right) { - return array('value' => $value, 'left' => $left, 'right' => $right); + return ['value' => $value, 'left' => $left, 'right' => $right]; } /** @@ -1647,7 +1647,7 @@ function _createTree($value, $left, $right) * @param array $tree The optional tree to convert. * @return string The tree in reverse polish notation */ - function toReversePolish($tree = array()) + function toReversePolish($tree = []) { $polish = ""; // the string we are going to return if (empty($tree)) { // If it's the first call use _parse_tree @@ -1680,9 +1680,9 @@ function toReversePolish($tree = array()) $polish .= $converted_tree; } // if it's a function convert it here (so we can set it's arguments) - if (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/",$tree['value']) and - !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/',$tree['value']) and - !preg_match("/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/",$tree['value']) and + if (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/",(string) $tree['value']) and + !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/',(string) $tree['value']) and + !preg_match("/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/",(string) $tree['value']) and !is_numeric($tree['value']) and !isset($this->ptg[$tree['value']])) { diff --git a/functions/PEAR/Spreadsheet/Excel/Writer/Validator.php b/functions/PEAR/Spreadsheet/Excel/Writer/Validator.php index 107997cc8..44c35316a 100755 --- a/functions/PEAR/Spreadsheet/Excel/Writer/Validator.php +++ b/functions/PEAR/Spreadsheet/Excel/Writer/Validator.php @@ -47,25 +47,25 @@ */ class Spreadsheet_Excel_Writer_Validator { - var $_type; - var $_style; - var $_fixedList; - var $_blank; - var $_incell; - var $_showprompt; - var $_showerror; - var $_title_prompt; - var $_descr_prompt; - var $_title_error; - var $_descr_error; - var $_operator; - var $_formula1; - var $_formula2; + public $_type; + public $_style; + public $_fixedList; + public $_blank; + public $_incell; + public $_showprompt; + public $_showerror; + public $_title_prompt; + public $_descr_prompt; + public $_title_error; + public $_descr_error; + public $_operator; + public $_formula1; + public $_formula2; /** * The parser from the workbook. Used to parse validation formulas also * @var Spreadsheet_Excel_Writer_Parser */ - var $_parser; + public $_parser; function __construct(&$parser) { @@ -180,13 +180,13 @@ function _getOptions() function _getData() { - $title_prompt_len = strlen($this->_title_prompt); - $descr_prompt_len = strlen($this->_descr_prompt); - $title_error_len = strlen($this->_title_error); - $descr_error_len = strlen($this->_descr_error); + $title_prompt_len = strlen((string) $this->_title_prompt); + $descr_prompt_len = strlen((string) $this->_descr_prompt); + $title_error_len = strlen((string) $this->_title_error); + $descr_error_len = strlen((string) $this->_descr_error); - $formula1_size = strlen($this->_formula1); - $formula2_size = strlen($this->_formula2); + $formula1_size = strlen((string) $this->_formula1); + $formula2_size = strlen((string) $this->_formula2); $data = pack("V", $this->_getOptions()); $data .= pack("vC", $title_prompt_len, 0x00) . $this->_title_prompt; diff --git a/functions/PEAR/Spreadsheet/Excel/Writer/Workbook.php b/functions/PEAR/Spreadsheet/Excel/Writer/Workbook.php index 6cd72019a..4dce20600 100755 --- a/functions/PEAR/Spreadsheet/Excel/Writer/Workbook.php +++ b/functions/PEAR/Spreadsheet/Excel/Writer/Workbook.php @@ -32,12 +32,12 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -require_once( dirname(__FILE__) . '/Format.php'); -require_once( dirname(__FILE__) . '/BIFFwriter.php'); -require_once( dirname(__FILE__) . '/Worksheet.php'); -require_once( dirname(__FILE__) . '/Parser.php'); -require_once( dirname(__FILE__) . '/../../../OLE/PPS/Root.php'); -require_once( dirname(__FILE__) . '/../../../OLE/PPS/File.php'); +require_once( __DIR__ . '/Format.php'); +require_once( __DIR__ . '/BIFFwriter.php'); +require_once( __DIR__ . '/Worksheet.php'); +require_once( __DIR__ . '/Parser.php'); +require_once( __DIR__ . '/../../../OLE/PPS/Root.php'); +require_once( __DIR__ . '/../../../OLE/PPS/File.php'); /** * Class for generating Excel Spreadsheets @@ -53,117 +53,117 @@ class Spreadsheet_Excel_Writer_Workbook extends Spreadsheet_Excel_Writer_BIFFwri * Filename for the Workbook * @var string */ - var $_filename; + public $_filename; /** * Formula parser * @var object Parser */ - var $_parser; + public $_parser; /** * Flag for 1904 date system (0 => base date is 1900, 1 => base date is 1904) * @var integer */ - var $_1904; + public $_1904; /** * The active worksheet of the workbook (0 indexed) * @var integer */ - var $_activesheet; + public $_activesheet; /** * 1st displayed worksheet in the workbook (0 indexed) * @var integer */ - var $_firstsheet; + public $_firstsheet; /** * Number of workbook tabs selected * @var integer */ - var $_selected; + public $_selected; /** * Index for creating adding new formats to the workbook * @var integer */ - var $_xf_index; + public $_xf_index; /** * Flag for preventing close from being called twice. * @var integer * @see close() */ - var $_fileclosed; + public $_fileclosed; /** * The BIFF file size for the workbook. * @var integer * @see _calcSheetOffsets() */ - var $_biffsize; + public $_biffsize; /** * The default sheetname for all sheets created. * @var string */ - var $_sheetname; + public $_sheetname; /** * The default XF format. * @var object Format */ - var $_tmp_format; + public $_tmp_format; /** * Array containing references to all of this workbook's worksheets * @var array */ - var $_worksheets; + public $_worksheets; /** * Array of sheetnames for creating the EXTERNSHEET records * @var array */ - var $_sheetnames; + public $_sheetnames; /** * Array containing references to all of this workbook's formats * @var array */ - var $_formats; + public $_formats; /** * Array containing the colour palette * @var array */ - var $_palette; + public $_palette; /** * The default format for URLs. * @var object Format */ - var $_url_format; + public $_url_format; /** * The codepage indicates the text encoding used for strings * @var integer */ - var $_codepage; + public $_codepage; /** * The country code used for localization * @var integer */ - var $_country_code; + public $_country_code; /** * number of bytes for sizeinfo of strings * @var integer */ - var $_string_sizeinfo_size; + public $_string_sizeinfo_size; /** * Class constructor @@ -187,19 +187,19 @@ function __construct($filename) $this->_biffsize = 0; $this->_sheetname = 'Sheet'; $this->_tmp_format = new Spreadsheet_Excel_Writer_Format($this->_BIFF_version); - $this->_worksheets = array(); - $this->_sheetnames = array(); - $this->_formats = array(); - $this->_palette = array(); + $this->_worksheets = []; + $this->_sheetnames = []; + $this->_formats = []; + $this->_palette = []; $this->_codepage = 0x04E4; // FIXME: should change for BIFF8 $this->_country_code = -1; $this->_string_sizeinfo = 3; // Add the default format for hyperlinks - $this->_url_format = $this->addFormat(array('color' => 'blue', 'underline' => 1)); + $this->_url_format = $this->addFormat(['color' => 'blue', 'underline' => 1]); $this->_str_total = 0; $this->_str_unique = 0; - $this->_str_table = array(); + $this->_str_table = []; $this->_setPaletteXl97(); } public function Spreadsheet_Excel_Writer_Workbook($filename) @@ -361,7 +361,7 @@ function &addWorksheet($name = '') * @param array $properties array with properties for initializing the format. * @return &Spreadsheet_Excel_Writer_Format reference to an Excel Format */ - function &addFormat($properties = array()) + function &addFormat($properties = []) { $format = new Spreadsheet_Excel_Writer_Format($this->_BIFF_version, $this->_xf_index, $properties); $this->_xf_index += 1; @@ -417,7 +417,7 @@ function setCustomColor($index, $red, $green, $blue) $index -= 8; // Adjust colour index (wingless dragonfly) // Set the RGB value - $this->_palette[$index] = array($red, $green, $blue, 0); + $this->_palette[$index] = [$red, $green, $blue, 0]; return($index + 8); } @@ -428,64 +428,64 @@ function setCustomColor($index, $red, $green, $blue) */ function _setPaletteXl97() { - $this->_palette = array( - array(0x00, 0x00, 0x00, 0x00), // 8 - array(0xff, 0xff, 0xff, 0x00), // 9 - array(0xff, 0x00, 0x00, 0x00), // 10 - array(0x00, 0xff, 0x00, 0x00), // 11 - array(0x00, 0x00, 0xff, 0x00), // 12 - array(0xff, 0xff, 0x00, 0x00), // 13 - array(0xff, 0x00, 0xff, 0x00), // 14 - array(0x00, 0xff, 0xff, 0x00), // 15 - array(0x80, 0x00, 0x00, 0x00), // 16 - array(0x00, 0x80, 0x00, 0x00), // 17 - array(0x00, 0x00, 0x80, 0x00), // 18 - array(0x80, 0x80, 0x00, 0x00), // 19 - array(0x80, 0x00, 0x80, 0x00), // 20 - array(0x00, 0x80, 0x80, 0x00), // 21 - array(0xc0, 0xc0, 0xc0, 0x00), // 22 - array(0x80, 0x80, 0x80, 0x00), // 23 - array(0x99, 0x99, 0xff, 0x00), // 24 - array(0x99, 0x33, 0x66, 0x00), // 25 - array(0xff, 0xff, 0xcc, 0x00), // 26 - array(0xcc, 0xff, 0xff, 0x00), // 27 - array(0x66, 0x00, 0x66, 0x00), // 28 - array(0xff, 0x80, 0x80, 0x00), // 29 - array(0x00, 0x66, 0xcc, 0x00), // 30 - array(0xcc, 0xcc, 0xff, 0x00), // 31 - array(0x00, 0x00, 0x80, 0x00), // 32 - array(0xff, 0x00, 0xff, 0x00), // 33 - array(0xff, 0xff, 0x00, 0x00), // 34 - array(0x00, 0xff, 0xff, 0x00), // 35 - array(0x80, 0x00, 0x80, 0x00), // 36 - array(0x80, 0x00, 0x00, 0x00), // 37 - array(0x00, 0x80, 0x80, 0x00), // 38 - array(0x00, 0x00, 0xff, 0x00), // 39 - array(0x00, 0xcc, 0xff, 0x00), // 40 - array(0xcc, 0xff, 0xff, 0x00), // 41 - array(0xcc, 0xff, 0xcc, 0x00), // 42 - array(0xff, 0xff, 0x99, 0x00), // 43 - array(0x99, 0xcc, 0xff, 0x00), // 44 - array(0xff, 0x99, 0xcc, 0x00), // 45 - array(0xcc, 0x99, 0xff, 0x00), // 46 - array(0xff, 0xcc, 0x99, 0x00), // 47 - array(0x33, 0x66, 0xff, 0x00), // 48 - array(0x33, 0xcc, 0xcc, 0x00), // 49 - array(0x99, 0xcc, 0x00, 0x00), // 50 - array(0xff, 0xcc, 0x00, 0x00), // 51 - array(0xff, 0x99, 0x00, 0x00), // 52 - array(0xff, 0x66, 0x00, 0x00), // 53 - array(0x66, 0x66, 0x99, 0x00), // 54 - array(0x96, 0x96, 0x96, 0x00), // 55 - array(0x00, 0x33, 0x66, 0x00), // 56 - array(0x33, 0x99, 0x66, 0x00), // 57 - array(0x00, 0x33, 0x00, 0x00), // 58 - array(0x33, 0x33, 0x00, 0x00), // 59 - array(0x99, 0x33, 0x00, 0x00), // 60 - array(0x99, 0x33, 0x66, 0x00), // 61 - array(0x33, 0x33, 0x99, 0x00), // 62 - array(0x33, 0x33, 0x33, 0x00), // 63 - ); + $this->_palette = [ + [0x00, 0x00, 0x00, 0x00], // 8 + [0xff, 0xff, 0xff, 0x00], // 9 + [0xff, 0x00, 0x00, 0x00], // 10 + [0x00, 0xff, 0x00, 0x00], // 11 + [0x00, 0x00, 0xff, 0x00], // 12 + [0xff, 0xff, 0x00, 0x00], // 13 + [0xff, 0x00, 0xff, 0x00], // 14 + [0x00, 0xff, 0xff, 0x00], // 15 + [0x80, 0x00, 0x00, 0x00], // 16 + [0x00, 0x80, 0x00, 0x00], // 17 + [0x00, 0x00, 0x80, 0x00], // 18 + [0x80, 0x80, 0x00, 0x00], // 19 + [0x80, 0x00, 0x80, 0x00], // 20 + [0x00, 0x80, 0x80, 0x00], // 21 + [0xc0, 0xc0, 0xc0, 0x00], // 22 + [0x80, 0x80, 0x80, 0x00], // 23 + [0x99, 0x99, 0xff, 0x00], // 24 + [0x99, 0x33, 0x66, 0x00], // 25 + [0xff, 0xff, 0xcc, 0x00], // 26 + [0xcc, 0xff, 0xff, 0x00], // 27 + [0x66, 0x00, 0x66, 0x00], // 28 + [0xff, 0x80, 0x80, 0x00], // 29 + [0x00, 0x66, 0xcc, 0x00], // 30 + [0xcc, 0xcc, 0xff, 0x00], // 31 + [0x00, 0x00, 0x80, 0x00], // 32 + [0xff, 0x00, 0xff, 0x00], // 33 + [0xff, 0xff, 0x00, 0x00], // 34 + [0x00, 0xff, 0xff, 0x00], // 35 + [0x80, 0x00, 0x80, 0x00], // 36 + [0x80, 0x00, 0x00, 0x00], // 37 + [0x00, 0x80, 0x80, 0x00], // 38 + [0x00, 0x00, 0xff, 0x00], // 39 + [0x00, 0xcc, 0xff, 0x00], // 40 + [0xcc, 0xff, 0xff, 0x00], // 41 + [0xcc, 0xff, 0xcc, 0x00], // 42 + [0xff, 0xff, 0x99, 0x00], // 43 + [0x99, 0xcc, 0xff, 0x00], // 44 + [0xff, 0x99, 0xcc, 0x00], // 45 + [0xcc, 0x99, 0xff, 0x00], // 46 + [0xff, 0xcc, 0x99, 0x00], // 47 + [0x33, 0x66, 0xff, 0x00], // 48 + [0x33, 0xcc, 0xcc, 0x00], // 49 + [0x99, 0xcc, 0x00, 0x00], // 50 + [0xff, 0xcc, 0x00, 0x00], // 51 + [0xff, 0x99, 0x00, 0x00], // 52 + [0xff, 0x66, 0x00, 0x00], // 53 + [0x66, 0x66, 0x99, 0x00], // 54 + [0x96, 0x96, 0x96, 0x00], // 55 + [0x00, 0x33, 0x66, 0x00], // 56 + [0x33, 0x99, 0x66, 0x00], // 57 + [0x00, 0x33, 0x00, 0x00], // 58 + [0x33, 0x33, 0x00, 0x00], // 59 + [0x99, 0x33, 0x00, 0x00], // 60 + [0x99, 0x33, 0x66, 0x00], // 61 + [0x33, 0x33, 0x99, 0x00], // 62 + [0x33, 0x33, 0x33, 0x00], // 63 + ]; } /** @@ -594,7 +594,7 @@ function _storeOLEFile() } } - $root = new OLE_PPS_Root(time(), time(), array($OLE)); + $root = new OLE_PPS_Root(time(), time(), [$OLE]); if ($this->_tmp_dir != '') { $root->setTempDir($this->_tmp_dir); } @@ -634,7 +634,7 @@ function _calcSheetOffsets() $total_worksheets = count($this->_worksheets); // add the length of the BOUNDSHEET records for ($i = 0; $i < $total_worksheets; $i++) { - $offset += $boundsheet_length + strlen($this->_worksheets[$i]->name); + $offset += $boundsheet_length + strlen((string) $this->_worksheets[$i]->name); } $offset += $EOF; @@ -666,7 +666,7 @@ function _storeAllFonts() // Iterate through the XF objects and write a FONT record if it isn't the // same as the default FONT and if it hasn't already been used. // - $fonts = array(); + $fonts = []; $index = 6; // The first user defined FONT $key = $format->getFontKey(); // The default font from _tmp_format @@ -697,8 +697,8 @@ function _storeAllFonts() function _storeAllNumFormats() { // Leaning num_format syndrome - $hash_num_formats = array(); - $num_formats = array(); + $hash_num_formats = []; + $num_formats = []; $index = 164; // Iterate through the XF objects and write a FORMAT record if it isn't a @@ -711,8 +711,8 @@ function _storeAllNumFormats() // Also check for a string of zeros, which is a valid format string // but would evaluate to zero. // - if (!preg_match("/^0+\d/", $num_format)) { - if (preg_match("/^\d+$/", $num_format)) { // built-in format + if (!preg_match("/^0+\d/", (string) $num_format)) { + if (preg_match("/^\d+$/", (string) $num_format)) { // built-in format continue; } } @@ -1314,12 +1314,12 @@ function _calculateSharedStringsSizes() $continue_limit = 8208; $block_length = 0; $written = 0; - $this->_block_sizes = array(); + $this->_block_sizes = []; $continue = 0; foreach (array_keys($this->_str_table) as $string) { - $string_length = strlen($string); - $headerinfo = unpack("vlength/Cencoding", $string); + $string_length = strlen((string) $string); + $headerinfo = unpack("vlength/Cencoding", (string) $string); $encoding = $headerinfo["encoding"]; $split_string = 0; @@ -1423,7 +1423,7 @@ function _calculateSharedStringsSizes() they must be written before the SST records */ - $tmp_block_sizes = array(); + $tmp_block_sizes = []; $tmp_block_sizes = $this->_block_sizes; $length = 12; @@ -1488,8 +1488,8 @@ function _storeSharedStringsTable() /* TODO: not good for performance */ foreach (array_keys($this->_str_table) as $string) { - $string_length = strlen($string); - $headerinfo = unpack("vlength/Cencoding", $string); + $string_length = strlen((string) $string); + $headerinfo = unpack("vlength/Cencoding", (string) $string); $encoding = $headerinfo["encoding"]; $split_string = 0; @@ -1548,11 +1548,11 @@ function _storeSharedStringsTable() if ($space_remaining > $header_length) { // Write as much as possible of the string in the current block - $tmp = substr($string, 0, $space_remaining); + $tmp = substr((string) $string, 0, $space_remaining); $this->_append($tmp); // The remainder will be written in the next block(s) - $string = substr($string, $space_remaining); + $string = substr((string) $string, $space_remaining); // Reduce the current block length by the amount written $block_length -= $continue_limit - $continue - $align; diff --git a/functions/PEAR/Spreadsheet/Excel/Writer/Worksheet.php b/functions/PEAR/Spreadsheet/Excel/Writer/Worksheet.php index 31bb991a5..487013182 100755 --- a/functions/PEAR/Spreadsheet/Excel/Writer/Worksheet.php +++ b/functions/PEAR/Spreadsheet/Excel/Writer/Worksheet.php @@ -32,8 +32,8 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -require_once( dirname(__FILE__) . '/Parser.php'); -require_once( dirname(__FILE__) . '/BIFFwriter.php'); +require_once( __DIR__ . '/Parser.php'); +require_once( __DIR__ . '/BIFFwriter.php'); /** * Class for generating Excel Spreadsheets @@ -49,311 +49,311 @@ class Spreadsheet_Excel_Writer_Worksheet extends Spreadsheet_Excel_Writer_BIFFwr * Name of the Worksheet * @var string */ - var $name; + public $name; /** * Index for the Worksheet * @var integer */ - var $index; + public $index; /** * Reference to the (default) Format object for URLs * @var object Format */ - var $_url_format; + public $_url_format; /** * Reference to the parser used for parsing formulas * @var object Format */ - var $_parser; + public $_parser; /** * Filehandle to the temporary file for storing data * @var resource */ - var $_filehandle; + public $_filehandle; /** * Boolean indicating if we are using a temporary file for storing data * @var bool */ - var $_using_tmpfile; + public $_using_tmpfile; /** * Maximum number of rows for an Excel spreadsheet (BIFF5) * @var integer */ - var $_xls_rowmax; + public $_xls_rowmax; /** * Maximum number of columns for an Excel spreadsheet (BIFF5) * @var integer */ - var $_xls_colmax; + public $_xls_colmax; /** * Maximum number of characters for a string (LABEL record in BIFF5) * @var integer */ - var $_xls_strmax; + public $_xls_strmax; /** * First row for the DIMENSIONS record * @var integer * @see _storeDimensions() */ - var $_dim_rowmin; + public $_dim_rowmin; /** * Last row for the DIMENSIONS record * @var integer * @see _storeDimensions() */ - var $_dim_rowmax; + public $_dim_rowmax; /** * First column for the DIMENSIONS record * @var integer * @see _storeDimensions() */ - var $_dim_colmin; + public $_dim_colmin; /** * Last column for the DIMENSIONS record * @var integer * @see _storeDimensions() */ - var $_dim_colmax; + public $_dim_colmax; /** * Array containing format information for columns * @var array */ - var $_colinfo; + public $_colinfo; /** * Array containing the selected area for the worksheet * @var array */ - var $_selection; + public $_selection; /** * Array containing the panes for the worksheet * @var array */ - var $_panes; + public $_panes; /** * The active pane for the worksheet * @var integer */ - var $_active_pane; + public $_active_pane; /** * Bit specifying if panes are frozen * @var integer */ - var $_frozen; + public $_frozen; /** * Bit specifying if the worksheet is selected * @var integer */ - var $selected; + public $selected; /** * The paper size (for printing) (DOCUMENT!!!) * @var integer */ - var $_paper_size; + public $_paper_size; /** * Bit specifying paper orientation (for printing). 0 => landscape, 1 => portrait * @var integer */ - var $_orientation; + public $_orientation; /** * The page header caption * @var string */ - var $_header; + public $_header; /** * The page footer caption * @var string */ - var $_footer; + public $_footer; /** * The horizontal centering value for the page * @var integer */ - var $_hcenter; + public $_hcenter; /** * The vertical centering value for the page * @var integer */ - var $_vcenter; + public $_vcenter; /** * The margin for the header * @var float */ - var $_margin_head; + public $_margin_head; /** * The margin for the footer * @var float */ - var $_margin_foot; + public $_margin_foot; /** * The left margin for the worksheet in inches * @var float */ - var $_margin_left; + public $_margin_left; /** * The right margin for the worksheet in inches * @var float */ - var $_margin_right; + public $_margin_right; /** * The top margin for the worksheet in inches * @var float */ - var $_margin_top; + public $_margin_top; /** * The bottom margin for the worksheet in inches * @var float */ - var $_margin_bottom; + public $_margin_bottom; /** * First row to reapeat on each printed page * @var integer */ - var $title_rowmin; + public $title_rowmin; /** * Last row to reapeat on each printed page * @var integer */ - var $title_rowmax; + public $title_rowmax; /** * First column to reapeat on each printed page * @var integer */ - var $title_colmin; + public $title_colmin; /** * First row of the area to print * @var integer */ - var $print_rowmin; + public $print_rowmin; /** * Last row to of the area to print * @var integer */ - var $print_rowmax; + public $print_rowmax; /** * First column of the area to print * @var integer */ - var $print_colmin; + public $print_colmin; /** * Last column of the area to print * @var integer */ - var $print_colmax; + public $print_colmax; /** * Whether to use outline. * @var integer */ - var $_outline_on; + public $_outline_on; /** * Auto outline styles. * @var bool */ - var $_outline_style; + public $_outline_style; /** * Whether to have outline summary below. * @var bool */ - var $_outline_below; + public $_outline_below; /** * Whether to have outline summary at the right. * @var bool */ - var $_outline_right; + public $_outline_right; /** * Outline row level. * @var integer */ - var $_outline_row_level; + public $_outline_row_level; /** * Whether to fit to page when printing or not. * @var bool */ - var $_fit_page; + public $_fit_page; /** * Number of pages to fit wide * @var integer */ - var $_fit_width; + public $_fit_width; /** * Number of pages to fit high * @var integer */ - var $_fit_height; + public $_fit_height; /** * Reference to the total number of strings in the workbook * @var integer */ - var $_str_total; + public $_str_total; /** * Reference to the number of unique strings in the workbook * @var integer */ - var $_str_unique; + public $_str_unique; /** * Reference to the array containing all the unique strings in the workbook * @var array */ - var $_str_table; + public $_str_table; /** * Merged cell ranges * @var array */ - var $_merged_ranges; + public $_merged_ranges; /** * Charset encoding currently used when calling writeString() * @var string */ - var $_input_encoding; + public $_input_encoding; /** * Constructor @@ -402,9 +402,9 @@ function __construct($BIFF_version, $name, $this->_dim_rowmax = 0; $this->_dim_colmin = $colmax + 1; $this->_dim_colmax = 0; - $this->_colinfo = array(); - $this->_selection = array(0,0,0,0); - $this->_panes = array(); + $this->_colinfo = []; + $this->_selection = [0,0,0,0]; + $this->_panes = []; $this->_active_pane = 3; $this->_frozen = 0; $this->selected = 0; @@ -439,14 +439,14 @@ function __construct($BIFF_version, $name, $this->_fit_width = 0; $this->_fit_height = 0; - $this->_hbreaks = array(); - $this->_vbreaks = array(); + $this->_hbreaks = []; + $this->_vbreaks = []; $this->_protect = 0; $this->_password = null; - $this->col_sizes = array(); - $this->_row_sizes = array(); + $this->col_sizes = []; + $this->_row_sizes = []; $this->_zoom = 100; $this->_print_scale = 100; @@ -457,11 +457,11 @@ function __construct($BIFF_version, $name, $this->_outline_right = 1; $this->_outline_on = 1; - $this->_merged_ranges = array(); + $this->_merged_ranges = []; $this->_input_encoding = ''; - $this->_dv = array(); + $this->_dv = []; $this->_tmp_dir = $tmp_dir; @@ -697,7 +697,7 @@ function setMerge($first_row, $first_col, $last_row, $last_col) } // don't check rowmin, rowmax, etc... because we don't know when this // is going to be called - $this->_merged_ranges[] = array($first_row, $first_col, $last_row, $last_col); + $this->_merged_ranges[] = [$first_row, $first_col, $last_row, $last_col]; } /** @@ -763,7 +763,7 @@ function protect($password) */ function setColumn($firstcol, $lastcol, $width, $format = null, $hidden = 0, $level = 0) { - $this->_colinfo[] = array($firstcol, $lastcol, $width, &$format, $hidden, $level); + $this->_colinfo[] = [$firstcol, $lastcol, $width, &$format, $hidden, $level]; // Set width to zero if column is hidden $width = ($hidden) ? 0 : $width; @@ -784,7 +784,7 @@ function setColumn($firstcol, $lastcol, $width, $format = null, $hidden = 0, $le */ function setSelection($first_row,$first_column,$last_row,$last_column) { - $this->_selection = array($first_row,$first_column,$last_row,$last_column); + $this->_selection = [$first_row,$first_column,$last_row,$last_column]; } /** @@ -1175,19 +1175,19 @@ function write($row, $col, $token, $format = null) if (is_null($token)) $token = ''; - if (preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/", $token)) { + if (preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/", (string) $token)) { // Match number return $this->writeNumber($row, $col, $token, $format); - } elseif (preg_match("/^[fh]tt?p:\/\//", $token)) { + } elseif (preg_match("/^[fh]tt?p:\/\//", (string) $token)) { // Match http or ftp URL return $this->writeUrl($row, $col, $token, '', $format); - } elseif (preg_match("/^mailto:/", $token)) { + } elseif (preg_match("/^mailto:/", (string) $token)) { // Match mailto: return $this->writeUrl($row, $col, $token, '', $format); - } elseif (preg_match("/^(?:in|ex)ternal:/", $token)) { + } elseif (preg_match("/^(?:in|ex)ternal:/", (string) $token)) { // Match internal or external sheet link return $this->writeUrl($row, $col, $token, '', $format); - } elseif (preg_match("/^=/", $token)) { + } elseif (preg_match("/^=/", (string) $token)) { // Match formula return $this->writeFormula($row, $col, $token, $format); } elseif ($token == '') { @@ -1284,6 +1284,7 @@ function _XF(&$format) * @access private * @param string $data The binary data to append */ + #[\Override] function _append($data) { if ($this->_using_tmpfile) { @@ -1316,20 +1317,20 @@ function _substituteCellref($cell) if (preg_match("/([A-I]?[A-Z]):([A-I]?[A-Z])/", $cell, $match)) { list($no_use, $col1) = $this->_cellToRowcol($match[1] .'1'); // Add a dummy row list($no_use, $col2) = $this->_cellToRowcol($match[2] .'1'); // Add a dummy row - return(array($col1, $col2)); + return([$col1, $col2]); } // Convert a cell range: 'A1:B7' if (preg_match("/\$?([A-I]?[A-Z]\$?\d+):\$?([A-I]?[A-Z]\$?\d+)/", $cell, $match)) { list($row1, $col1) = $this->_cellToRowcol($match[1]); list($row2, $col2) = $this->_cellToRowcol($match[2]); - return(array($row1, $col1, $row2, $col2)); + return([$row1, $col1, $row2, $col2]); } // Convert a cell reference: 'A1' or 'AD2000' if (preg_match("/\$?([A-I]?[A-Z]\$?\d+)/", $cell)) { list($row1, $col1) = $this->_cellToRowcol($match[1]); - return(array($row1, $col1)); + return([$row1, $col1]); } // TODO use real error codes @@ -1365,7 +1366,7 @@ function _cellToRowcol($cell) $row--; $col--; - return(array($row, $col)); + return([$row, $col]); } /** @@ -1809,7 +1810,7 @@ function writeFormula($row, $col, $formula, $format = null) return -1; } - $formlen = strlen($formula); // Length of the binary string + $formlen = strlen((string) $formula); // Length of the binary string $length = 0x16 + $formlen; // Length of the record data $header = pack("vv", $record, $length); @@ -1985,7 +1986,7 @@ function _writeUrlInternal($row1, $col1, $row2, $col2, $url, $str, $format = nul $options = pack("V", 0x08); // Convert the URL type and to a null terminated wchar string - $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); + $url = join("\0", preg_split("''", (string) $url, -1, PREG_SPLIT_NO_EMPTY)); $url = $url . "\0\0\0"; // Pack the length of the URL as chars (not wchars) @@ -2041,11 +2042,11 @@ function _writeUrlExternal($row1, $col1, $row2, $col2, $url, $str, $format = nul // Strip URL type and change Unix dir separator to Dos style (if needed) // $url = preg_replace('/^external:/', '', $url); - $url = preg_replace('/\//', "\\", $url); + $url = preg_replace('/\//', "\\", (string) $url); // Write the visible label if ($str == '') { - $str = preg_replace('/\#/', ' - ', $url); + $str = preg_replace('/\#/', ' - ', (string) $url); } $str_error = $this->writeString($row1, $col1, $str, $format); if (($str_error == -2) or ($str_error == -3)) { @@ -2058,10 +2059,10 @@ function _writeUrlExternal($row1, $col1, $row2, $col2, $url, $str, $format = nul // otherwise, absolute $absolute = 0x02; // Bit mask - if (!preg_match("/\\\/", $url)) { + if (!preg_match("/\\\/", (string) $url)) { $absolute = 0x00; } - if (preg_match("/^\.\.\\\/", $url)) { + if (preg_match("/^\.\.\\\/", (string) $url)) { $absolute = 0x00; } $link_type = 0x01 | $absolute; @@ -2085,7 +2086,7 @@ function _writeUrlExternal($row1, $col1, $row2, $col2, $url, $str, $format = nul $sheet = ''; }*/ $dir_long = $url; - if (preg_match("/\#/", $url)) { + if (preg_match("/\#/", (string) $url)) { $link_type |= 0x08; } @@ -2095,11 +2096,11 @@ function _writeUrlExternal($row1, $col1, $row2, $col2, $url, $str, $format = nul $link_type = pack("V", $link_type); // Calculate the up-level dir count e.g.. (..\..\..\ == 3) - $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless); + $up_count = preg_match_all("/\.\.\\\/", (string) $dir_long, $useless); $up_count = pack("v", $up_count); // Store the short dos dir name (null terminated) - $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0"; + $dir_short = preg_replace("/\.\.\\\/", '', (string) $dir_long) . "\0"; // Store the long dir name as a wchar string (non-null terminated) //$dir_long = join("\0", preg_split('//', $dir_long)); @@ -2392,11 +2393,11 @@ function _storeSelection($array) // Swap last row/col for first row/col as necessary if ($rwFirst > $rwLast) { - list($rwFirst, $rwLast) = array($rwLast, $rwFirst); + list($rwFirst, $rwLast) = [$rwLast, $rwFirst]; } if ($colFirst > $colLast) { - list($colFirst, $colLast) = array($colLast, $colFirst); + list($colFirst, $colLast) = [$colLast, $colFirst]; } $header = pack("vv", $record, $length); @@ -2820,11 +2821,11 @@ function mergeCells($first_row, $first_col, $last_row, $last_col) // Swap last row/col for first row/col as necessary if ($first_row > $last_row) { - list($first_row, $last_row) = array($last_row, $first_row); + list($first_row, $last_row) = [$last_row, $first_row]; } if ($first_col > $last_col) { - list($first_col, $last_col) = array($last_col, $first_col); + list($first_col, $last_col) = [$last_col, $first_col]; } $header = pack("vv", $record, $length); @@ -3470,7 +3471,7 @@ function _processBitmap($bitmap) $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18); $data = $header . $data; - return (array($width, $height, $size, $data)); + return ([$width, $height, $size, $data]); } /** diff --git a/functions/PHPMailer b/functions/PHPMailer deleted file mode 160000 index 829def338..000000000 --- a/functions/PHPMailer +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 829def33886c827e1622f965a8813d7bf453f15a diff --git a/functions/adLDAP/src/adLDAP.php b/functions/adLDAP/src/adLDAP.php index f6b5d8de7..fd758aaa5 100755 --- a/functions/adLDAP/src/adLDAP.php +++ b/functions/adLDAP/src/adLDAP.php @@ -46,14 +46,14 @@ * Before asking questions, please read the Documentation at * http://adldap.sourceforge.net/wiki/doku.php?id=api */ -require_once(dirname(__FILE__).'/collections/adLDAPCollection.php'); -require_once(dirname(__FILE__).'/classes/adLDAPGroups.php'); -require_once(dirname(__FILE__).'/classes/adLDAPUsers.php'); -require_once(dirname(__FILE__).'/classes/adLDAPFolders.php'); -require_once(dirname(__FILE__).'/classes/adLDAPUtils.php'); -require_once(dirname(__FILE__).'/classes/adLDAPContacts.php'); -require_once(dirname(__FILE__).'/classes/adLDAPExchange.php'); -require_once(dirname(__FILE__).'/classes/adLDAPComputers.php'); +require_once(__DIR__.'/collections/adLDAPCollection.php'); +require_once(__DIR__.'/classes/adLDAPGroups.php'); +require_once(__DIR__.'/classes/adLDAPUsers.php'); +require_once(__DIR__.'/classes/adLDAPFolders.php'); +require_once(__DIR__.'/classes/adLDAPUtils.php'); +require_once(__DIR__.'/classes/adLDAPContacts.php'); +require_once(__DIR__.'/classes/adLDAPExchange.php'); +require_once(__DIR__.'/classes/adLDAPComputers.php'); class adLDAP { @@ -115,7 +115,7 @@ class adLDAP { * * @var array */ - protected $domainControllers = array("dc01.mydomain.local"); + protected $domainControllers = ["dc01.mydomain.local"]; /** * Optional account with higher privileges for searching @@ -588,7 +588,7 @@ public function setUseOpenLDAP($useOpenLDAP) * @throws Exception - if unable to bind to Domain Controller * @return bool */ - public function __construct($options = array()) { + public function __construct($options = []) { // You can specifically overide any of the default configuration options setup above if (count($options) > 0) { if (array_key_exists("account_suffix", $options)) { $this->accountSuffix = $options["account_suffix"]; } @@ -641,10 +641,11 @@ public function connect() { // Connect to the AD/LDAP server as the username/password $domainController = $this->randomController(); + $port = (int) $this->adPort; if ($this->useSSL) { - $this->ldapConnection = ldap_connect("ldaps://".$domainController, $this->adPort); + $this->ldapConnection = ldap_connect("ldaps://$domainController:$port"); } else { - $this->ldapConnection = ldap_connect($domainController, $this->adPort); + $this->ldapConnection = ldap_connect("ldap://$domainController:$port"); } // Set some ldap options for talking to AD @@ -753,7 +754,7 @@ public function authenticate($username, $password, $preventRebind = false) { */ public function findBaseDn() { - $namingContext = $this->getRootDse(array('defaultnamingcontext')); + $namingContext = $this->getRootDse(['defaultnamingcontext']); return $namingContext[0]['defaultnamingcontext'][0]; } @@ -763,7 +764,7 @@ public function findBaseDn() * @param string[] $attributes The attributes you wish to query e.g. defaultnamingcontext * @return array */ - public function getRootDse($attributes = array("*", "+")) { + public function getRootDse($attributes = ["*", "+"]) { if (!$this->ldapBind) { return (false); } $sr = @ldap_read($this->ldapConnection, "(objectclass=*)", 'objectClass=*', $attributes); @@ -824,10 +825,10 @@ public function adldap_schema($attributes) { // LDAP doesn't like NULL attributes, only set them if they have values // If you wish to remove an attribute you should set it to a space // TO DO: Adapt user_modify to use ldap_mod_delete to remove a NULL attribute - $mod = array(); + $mod = []; // Check every attribute to see if it contains 8bit characters and then UTF8 encode them - array_walk($attributes, array($this, 'encode8bit')); + array_walk($attributes, [$this, 'encode8bit']); if ($attributes["address_city"]) { $mod["l"][0] = $attributes["address_city"]; } if ($attributes["address_code"]) { $mod["postalCode"][0] = $attributes["address_code"]; } diff --git a/functions/adLDAP/src/classes/adLDAPComputers.php b/functions/adLDAP/src/classes/adLDAPComputers.php index 314e64aed..c6b29b3bd 100755 --- a/functions/adLDAP/src/classes/adLDAPComputers.php +++ b/functions/adLDAP/src/classes/adLDAPComputers.php @@ -34,8 +34,8 @@ * @version 4.0.4 * @link http://adldap.sourceforge.net/ */ -require_once(dirname(__FILE__).'/../adLDAP.php'); -require_once(dirname(__FILE__).'/../collections/adLDAPComputerCollection.php'); +require_once(__DIR__.'/../adLDAP.php'); +require_once(__DIR__.'/../collections/adLDAPComputerCollection.php'); /** * COMPUTER MANAGEMENT FUNCTIONS @@ -67,7 +67,7 @@ public function info($computerName, $fields = NULL) $filter = "(&(objectClass=computer)(cn=".$computerName."))"; if ($fields === NULL) { - $fields = array("memberof", "cn", "displayname", "dnshostname", "distinguishedname", "objectcategory", "operatingsystem", "operatingsystemservicepack", "operatingsystemversion"); + $fields = ["memberof", "cn", "displayname", "dnshostname", "distinguishedname", "objectcategory", "operatingsystem", "operatingsystemservicepack", "operatingsystemversion"]; } $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); @@ -112,7 +112,7 @@ public function inGroup($computerName, $group, $recursive = NULL) if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } // use the default option if they haven't set it //get a list of the groups - $groups = $this->groups($computerName, array("memberof"), $recursive); + $groups = $this->groups($computerName, ["memberof"], $recursive); //return true if the specified group is in the group list if (in_array($group, $groups)) { @@ -136,7 +136,7 @@ public function groups($computerName, $recursive = NULL) if (!$this->adldap->getLdapBind()) { return false; } //search the directory for their information - $info = @$this->info($computerName, array("memberof", "primarygroupid")); + $info = @$this->info($computerName, ["memberof", "primarygroupid"]); $groups = $this->adldap->utilities()->niceNames($info[0]["memberof"]); //presuming the entry returned is our guy (unique usernames) if ($recursive === true) { diff --git a/functions/adLDAP/src/classes/adLDAPContacts.php b/functions/adLDAP/src/classes/adLDAPContacts.php index 94e01de2a..fe60e5f3b 100755 --- a/functions/adLDAP/src/classes/adLDAPContacts.php +++ b/functions/adLDAP/src/classes/adLDAPContacts.php @@ -35,8 +35,8 @@ * @link http://adldap.sourceforge.net/ */ -require_once(dirname(__FILE__).'/../adLDAP.php'); -require_once(dirname(__FILE__).'/../collections/adLDAPContactCollection.php'); +require_once(__DIR__.'/../adLDAP.php'); +require_once(__DIR__.'/../collections/adLDAPContactCollection.php'); class adLDAPContacts { /** @@ -108,7 +108,7 @@ public function groups($distinguishedName, $recursive = NULL) if (!$this->adldap->getLdapBind()) { return false; } // Search the directory for their information - $info = @$this->info($distinguishedName, array("memberof", "primarygroupid")); + $info = @$this->info($distinguishedName, ["memberof", "primarygroupid"]); $groups = $this->adldap->utilities()->niceNames($info[0]["memberof"]); //presuming the entry returned is our contact if ($recursive === true) { @@ -135,7 +135,7 @@ public function info($distinguishedName, $fields = NULL) $filter = "distinguishedName=".$distinguishedName; if ($fields === NULL) { - $fields = array("distinguishedname", "mail", "memberof", "department", "displayname", "telephonenumber", "primarygroupid", "objectsid"); + $fields = ["distinguishedname", "mail", "memberof", "department", "displayname", "telephonenumber", "primarygroupid", "objectsid"]; } $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); @@ -191,7 +191,7 @@ public function inGroup($distinguisedName, $group, $recursive = NULL) if ($recursive === NULL) { $recursive = $this->adldap->getRecursiveGroups(); } //use the default option if they haven't set it // Get a list of the groups - $groups = $this->groups($distinguisedName, array("memberof"), $recursive); + $groups = $this->groups($distinguisedName, ["memberof"], $recursive); // Return true if the specified group is in the group list if (in_array($group, $groups)) { @@ -256,13 +256,13 @@ public function all($includeDescription = false, $search = "*", $sorted = true) // Perform the search and grab all their details $filter = "(&(objectClass=contact)(cn=".$search."))"; - $fields = array("displayname", "distinguishedname"); + $fields = ["displayname", "distinguishedname"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); - $usersArray = array(); + $usersArray = []; for ($i = 0; $i < $entries["count"]; $i++) { - if ($includeDescription && strlen($entries[$i]["displayname"][0]) > 0) { + if ($includeDescription && strlen((string) $entries[$i]["displayname"][0]) > 0) { $usersArray[$entries[$i]["distinguishedname"][0]] = $entries[$i]["displayname"][0]; } elseif ($includeDescription) { $usersArray[$entries[$i]["distinguishedname"][0]] = $entries[$i]["distinguishedname"][0]; diff --git a/functions/adLDAP/src/classes/adLDAPExchange.php b/functions/adLDAP/src/classes/adLDAPExchange.php index c931ce664..fe52f53c7 100755 --- a/functions/adLDAP/src/classes/adLDAPExchange.php +++ b/functions/adLDAP/src/classes/adLDAPExchange.php @@ -34,7 +34,7 @@ * @version 4.0.4 * @link http://adldap.sourceforge.net/ */ -require_once(dirname(__FILE__).'/../adLDAP.php'); +require_once(__DIR__.'/../adLDAP.php'); /** * MICROSOFT EXCHANGE FUNCTIONS @@ -82,12 +82,12 @@ public function createMailbox($username, $storageGroup, $emailAddress, $mailNick } $mdbUseDefaults = $this->adldap->utilities()->boolToStr($useDefaults); - $attributes = array( + $attributes = [ 'exchange_homemdb'=>$container.",".$baseDn, 'exchange_proxyaddress'=>'SMTP:'.$emailAddress, 'exchange_mailnickname'=>$mailNickname, 'exchange_usedefaults'=>$mdbUseDefaults - ); + ]; $result = $this->adldap->user()->modify($username, $attributes, $isGUID); if ($result == false) { return false; @@ -117,7 +117,7 @@ public function addX400($username, $country, $admd, $pdmd, $org, $surname, $give $proxyValue = 'X400:'; // Find the dn of the user - $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID); + $user = $this->adldap->user()->info($username, ["cn","proxyaddresses"], $isGUID); if ($user[0]["dn"] === NULL) { return false; } $userDn = $user[0]["dn"]; @@ -160,15 +160,15 @@ public function addAddress($username, $emailAddress, $default = FALSE, $isGUID = } // Find the dn of the user - $user = $this->adldap->user()->info($username, array("cn","proxyaddresses"), $isGUID); + $user = $this->adldap->user()->info($username, ["cn","proxyaddresses"], $isGUID); if ($user[0]["dn"] === NULL){ return false; } $userDn = $user[0]["dn"]; // We need to scan existing proxy addresses and demote the default one if (is_array($user[0]["proxyaddresses"]) && $default === true) { - $modAddresses = array(); + $modAddresses = []; for ($i=0;$iadldap->user()->info($username, array("cn","proxyaddresses"), $isGUID); + $user = $this->adldap->user()->info($username, ["cn","proxyaddresses"], $isGUID); if ($user[0]["dn"] === NULL) { return false; } $userDn = $user[0]["dn"]; if (is_array($user[0]["proxyaddresses"])) { - $mod = array(); + $mod = []; for ($i=0;$iadldap->user()->info($username, array("cn","proxyaddresses"), $isGUID); + $user = $this->adldap->user()->info($username, ["cn","proxyaddresses"], $isGUID); if ($user[0]["dn"] === NULL){ return false; } $userDn = $user[0]["dn"]; if (is_array($user[0]["proxyaddresses"])) { - $modAddresses = array(); + $modAddresses = []; for ($i=0;$iadldap->contact()->info($distinguishedName, array("cn","displayname")); + $user = $this->adldap->contact()->info($distinguishedName, ["cn","displayname"]); if ($user[0]["displayname"] === NULL) { return false; } $mailNickname = $user[0]['displayname'][0]; } - $attributes = array("email"=>$emailAddress,"contact_email"=>"SMTP:" . $emailAddress,"exchange_proxyaddress"=>"SMTP:" . $emailAddress,"exchange_mailnickname" => $mailNickname); + $attributes = ["email"=>$emailAddress,"contact_email"=>"SMTP:" . $emailAddress,"exchange_proxyaddress"=>"SMTP:" . $emailAddress,"exchange_mailnickname" => $mailNickname]; // Translate the update to the LDAP schema $mod = $this->adldap->adldap_schema($attributes); @@ -330,11 +330,11 @@ public function contactMailEnable($distinguishedName, $emailAddress, $mailNickna * @param array $attributes An array of the AD attributes you wish to return * @return array */ - public function servers($attributes = array('cn','distinguishedname','serialnumber')) + public function servers($attributes = ['cn','distinguishedname','serialnumber']) { if (!$this->adldap->getLdapBind()){ return false; } - $configurationNamingContext = $this->adldap->getRootDse(array('configurationnamingcontext')); + $configurationNamingContext = $this->adldap->getRootDse(['configurationnamingcontext']); $sr = @ldap_search($this->adldap->getLdapConnection(), $configurationNamingContext[0]['configurationnamingcontext'][0],'(&(objectCategory=msExchExchangeServer))', $attributes); $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr); return $entries; @@ -348,7 +348,7 @@ public function servers($attributes = array('cn','distinguishedname','serialnumb * @param bool $recursive If enabled this will automatically query the databases within a storage group * @return array */ - public function storageGroups($exchangeServer, $attributes = array('cn','distinguishedname'), $recursive = NULL) + public function storageGroups($exchangeServer, $attributes = ['cn','distinguishedname'], $recursive = NULL) { if (!$this->adldap->getLdapBind()){ return false; } if ($exchangeServer === NULL) { return "Missing compulsory field [exchangeServer]"; } @@ -374,7 +374,7 @@ public function storageGroups($exchangeServer, $attributes = array('cn','disting * @param array $attributes An array of the AD attributes you wish to return * @return array */ - public function storageDatabases($storageGroup, $attributes = array('cn','distinguishedname','displayname')) { + public function storageDatabases($storageGroup, $attributes = ['cn','distinguishedname','displayname']) { if (!$this->adldap->getLdapBind()){ return false; } if ($storageGroup === NULL) { return "Missing compulsory field [storageGroup]"; } diff --git a/functions/adLDAP/src/classes/adLDAPFolders.php b/functions/adLDAP/src/classes/adLDAPFolders.php index cbdf97253..597a83660 100755 --- a/functions/adLDAP/src/classes/adLDAPFolders.php +++ b/functions/adLDAP/src/classes/adLDAPFolders.php @@ -34,7 +34,7 @@ * @version 4.0.4 * @link http://adldap.sourceforge.net/ */ -require_once(dirname(__FILE__) . '/../adLDAP.php'); +require_once(__DIR__ . '/../adLDAP.php'); /** * FOLDER / OU MANAGEMENT FUNCTIONS @@ -125,14 +125,14 @@ public function listing($folderName = NULL, $dnType = adLDAP::ADLDAP_FOLDER, $re } if ($recursive === true) { - $sr = ldap_search($this->adldap->getLdapConnection(), $searchOu, $filter, array('objectclass', 'distinguishedname', 'samaccountname')); + $sr = ldap_search($this->adldap->getLdapConnection(), $searchOu, $filter, ['objectclass', 'distinguishedname', 'samaccountname']); $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr); if (is_array($entries)) { return $entries; } } else { - $sr = ldap_list($this->adldap->getLdapConnection(), $searchOu, $filter, array('objectclass', 'distinguishedname', 'samaccountname')); + $sr = ldap_list($this->adldap->getLdapConnection(), $searchOu, $filter, ['objectclass', 'distinguishedname', 'samaccountname']); $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr); if (is_array($entries)) { return $entries; @@ -157,7 +157,7 @@ public function create($attributes) $attributes["container"] = array_reverse($attributes["container"]); - $add=array(); + $add=[]; $add["objectClass"] = "organizationalUnit"; $add["OU"] = $attributes['ou_name']; $containers = ""; diff --git a/functions/adLDAP/src/classes/adLDAPGroups.php b/functions/adLDAP/src/classes/adLDAPGroups.php index 78d0fa957..5d9d80235 100755 --- a/functions/adLDAP/src/classes/adLDAPGroups.php +++ b/functions/adLDAP/src/classes/adLDAPGroups.php @@ -34,8 +34,8 @@ * @version 4.0.4 * @link http://adldap.sourceforge.net/ */ -require_once(dirname(__FILE__) . '/../adLDAP.php'); -require_once(dirname(__FILE__) . '/../collections/adLDAPGroupCollection.php'); +require_once(__DIR__ . '/../adLDAP.php'); +require_once(__DIR__ . '/../collections/adLDAPGroupCollection.php'); /** * GROUP FUNCTIONS @@ -62,20 +62,20 @@ public function __construct(adLDAP $adldap) { public function addGroup($parent,$child){ // Find the parent group's dn - $parentGroup = $this->info($parent, array("cn")); + $parentGroup = $this->info($parent, ["cn"]); if ($parentGroup[0]["dn"] === NULL){ return false; } $parentDn = $parentGroup[0]["dn"]; // Find the child group's dn - $childGroup = $this->info($child, array("cn")); + $childGroup = $this->info($child, ["cn"]); if ($childGroup[0]["dn"] === NULL){ return false; } $childDn = $childGroup[0]["dn"]; - $add = array(); + $add = []; $add["member"] = $childDn; $result = @ldap_mod_add($this->adldap->getLdapConnection(), $parentDn, $add); @@ -105,13 +105,13 @@ public function addUser($group, $user, $isGUID = false) } // Find the group's dn - $groupInfo = $this->info($group, array("cn")); + $groupInfo = $this->info($group, ["cn"]); if ($groupInfo[0]["dn"] === NULL) { return false; } $groupDn = $groupInfo[0]["dn"]; - $add = array(); + $add = []; $add["member"] = $userDn; $result = @ldap_mod_add($this->adldap->getLdapConnection(), $groupDn, $add); @@ -134,13 +134,13 @@ public function addContact($group, $contactDn) // and add it using the full DN of the group // Find the group's dn - $groupInfo = $this->info($group, array("cn")); + $groupInfo = $this->info($group, ["cn"]); if ($groupInfo[0]["dn"] === NULL) { return false; } $groupDn = $groupInfo[0]["dn"]; - $add = array(); + $add = []; $add["member"] = $contactDn; $result = @ldap_mod_add($this->adldap->getLdapConnection(), $groupDn, $add); @@ -169,7 +169,7 @@ public function create($attributes) //$member_array[0] = "cn=user1,cn=Users,dc=yourdomain,dc=com"; //$member_array[1] = "cn=administrator,cn=Users,dc=yourdomain,dc=com"; - $add = array(); + $add = []; $add["cn"] = $attributes["group_name"]; $add["samaccountname"] = $attributes["group_name"]; $add["objectClass"] = "Group"; @@ -195,7 +195,7 @@ public function delete($group) { if (!$this->adldap->getLdapBind()){ return false; } if ($group === null){ return "Missing compulsory field [group]"; } - $groupInfo = $this->info($group, array("*")); + $groupInfo = $this->info($group, ["*"]); $dn = $groupInfo[0]['distinguishedname'][0]; $result = $this->adldap->folder()->delete($dn); if ($result !== true) { @@ -214,20 +214,20 @@ public function removeGroup($parent , $child) { // Find the parent dn - $parentGroup = $this->info($parent, array("cn")); + $parentGroup = $this->info($parent, ["cn"]); if ($parentGroup[0]["dn"] === NULL) { return false; } $parentDn = $parentGroup[0]["dn"]; // Find the child dn - $childGroup = $this->info($child, array("cn")); + $childGroup = $this->info($child, ["cn"]); if ($childGroup[0]["dn"] === NULL) { return false; } $childDn = $childGroup[0]["dn"]; - $del = array(); + $del = []; $del["member"] = $childDn; $result = @ldap_mod_del($this->adldap->getLdapConnection(), $parentDn, $del); @@ -249,7 +249,7 @@ public function removeUser($group, $user, $isGUID = false) { // Find the parent dn - $groupInfo = $this->info($group, array("cn")); + $groupInfo = $this->info($group, ["cn"]); if ($groupInfo[0]["dn"] === NULL){ return false; } @@ -261,7 +261,7 @@ public function removeUser($group, $user, $isGUID = false) return false; } - $del = array(); + $del = []; $del["member"] = $userDn; $result = @ldap_mod_del($this->adldap->getLdapConnection(), $groupDn, $del); @@ -282,13 +282,13 @@ public function removeContact($group, $contactDn) { // Find the parent dn - $groupInfo = $this->info($group, array("cn")); + $groupInfo = $this->info($group, ["cn"]); if ($groupInfo[0]["dn"] === NULL) { return false; } $groupDn = $groupInfo[0]["dn"]; - $del = array(); + $del = []; $del["member"] = $contactDn; $result = @ldap_mod_del($this->adldap->getLdapConnection(), $groupDn, $del); @@ -311,24 +311,24 @@ public function inGroup($group, $recursive = NULL) if ($recursive === NULL){ $recursive = $this->adldap->getRecursiveGroups(); } // Use the default option if they haven't set it // Search the directory for the members of a group - $info = $this->info($group, array("member","cn")); + $info = $this->info($group, ["member","cn"]); $groups = $info[0]["member"]; if (!is_array($groups)) { return false; } - $groupArray = array(); + $groupArray = []; for ($i=0; $i<$groups["count"]; $i++){ $filter = "(&(objectCategory=group)(distinguishedName=" . $this->adldap->utilities()->ldapSlashes($groups[$i]) . "))"; - $fields = array("samaccountname", "distinguishedname", "objectClass"); + $fields = ["samaccountname", "distinguishedname", "objectClass"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); // not a person, look for a group if ($entries['count'] == 0 && $recursive == true) { $filter = "(&(objectCategory=group)(distinguishedName=" . $this->adldap->utilities()->ldapSlashes($groups[$i]) . "))"; - $fields = array("distinguishedname"); + $fields = ["distinguishedname"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); if (!isset($entries[0]['distinguishedname'][0])) { @@ -359,24 +359,24 @@ public function members($group, $recursive = NULL) if (!$this->adldap->getLdapBind()){ return false; } if ($recursive === NULL){ $recursive = $this->adldap->getRecursiveGroups(); } // Use the default option if they haven't set it // Search the directory for the members of a group - $info = $this->info($group, array("member","cn")); + $info = $this->info($group, ["member","cn"]); $users = $info[0]["member"]; if (!is_array($users)) { return false; } - $userArray = array(); + $userArray = []; for ($i=0; $i<$users["count"]; $i++){ $filter = "(&(objectCategory=person)(distinguishedName=" . $this->adldap->utilities()->ldapSlashes($users[$i]) . "))"; - $fields = array("samaccountname", "distinguishedname", "objectClass"); + $fields = ["samaccountname", "distinguishedname", "objectClass"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); // not a person, look for a group if ($entries['count'] == 0 && $recursive == true) { $filter = "(&(objectCategory=group)(distinguishedName=" . $this->adldap->utilities()->ldapSlashes($users[$i]) . "))"; - $fields = array("samaccountname"); + $fields = ["samaccountname"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); if (!isset($entries[0]['samaccountname'][0])) { @@ -422,7 +422,7 @@ public function info($groupName, $fields = NULL) $filter = "(&(objectCategory=group)(name=" . $this->adldap->utilities()->ldapSlashes($groupName) . "))"; if ($fields === NULL) { - $fields = array("member","memberof","cn","description","distinguishedname","objectcategory","samaccountname"); + $fields = ["member","memberof","cn","description","distinguishedname","objectcategory","samaccountname"]; } $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); @@ -461,16 +461,16 @@ public function recursiveGroups($group) { if ($group === NULL) { return false; } - $stack = array(); - $processed = array(); - $retGroups = array(); + $stack = []; + $processed = []; + $retGroups = []; array_push($stack, $group); // Initial Group to Start with while (count($stack) > 0) { $parent = array_pop($stack); array_push($processed, $parent); - $info = $this->info($parent, array("memberof")); + $info = $this->info($parent, ["memberof"]); if (isset($info[0]["memberof"]) && is_array($info[0]["memberof"])) { $groups = $info[0]["memberof"]; @@ -507,11 +507,11 @@ public function search($sAMAaccountType = adLDAP::ADLDAP_SECURITY_GLOBAL_GROUP, } $filter .= '(cn=' . $search . '))'; // Perform the search and grab all their details - $fields = array("samaccountname", "description"); + $fields = ["samaccountname", "description"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); - $groupsArray = array(); + $groupsArray = []; for ($i=0; $i<$entries["count"]; $i++){ if ($includeDescription && isset($entries[$i]["description"][0]) && strlen($entries[$i]["description"][0]) > 0 ) { $groupsArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["description"][0]; @@ -586,14 +586,10 @@ public function getPrimaryGroup($gid, $usersid) $gsid = substr_replace($usersid, pack('V',$gid), strlen($usersid)-4,4); $filter = '(objectsid=' . $this->adldap->utilities()->getTextSID($gsid).')'; - $fields = array("samaccountname","distinguishedname"); + $fields = ["samaccountname","distinguishedname"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); - - if (isset($entries[0]['distinguishedname'][0])) { - return $entries[0]['distinguishedname'][0]; - } - return false; + return $entries[0]['distinguishedname'][0] ?? false; } /** @@ -614,7 +610,7 @@ public function cn($gid){ $r = ''; $filter = "(&(objectCategory=group)(samaccounttype=" . adLDAP::ADLDAP_SECURITY_GLOBAL_GROUP . "))"; - $fields = array("primarygrouptoken", "samaccountname", "distinguishedname"); + $fields = ["primarygrouptoken", "samaccountname", "distinguishedname"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); diff --git a/functions/adLDAP/src/classes/adLDAPUsers.php b/functions/adLDAP/src/classes/adLDAPUsers.php index ae2442ee1..b6c07af66 100755 --- a/functions/adLDAP/src/classes/adLDAPUsers.php +++ b/functions/adLDAP/src/classes/adLDAPUsers.php @@ -34,8 +34,8 @@ * @version 4.0.4 * @link http://adldap.sourceforge.net/ */ -require_once(dirname(__FILE__) . '/../adLDAP.php'); -require_once(dirname(__FILE__) . '/../collections/adLDAPUserCollection.php'); +require_once(__DIR__ . '/../adLDAP.php'); +require_once(__DIR__ . '/../collections/adLDAPUserCollection.php'); /** * USER FUNCTIONS @@ -103,7 +103,7 @@ public function create($attributes) //$add["name"][0]=$attributes["firstname"]." ".$attributes["surname"]; // Set the account control attribute - $control_options = array("NORMAL_ACCOUNT"); + $control_options = ["NORMAL_ACCOUNT"]; if (!$attributes["enabled"]) { $control_options[] = "ACCOUNTDISABLE"; } @@ -168,7 +168,7 @@ protected function accountControl($options) */ public function delete($username, $isGUID = false) { - $userinfo = $this->info($username, array("*"), $isGUID); + $userinfo = $this->info($username, ["*"], $isGUID); $dn = $userinfo[0]['distinguishedname'][0]; $result = $this->adldap->folder()->delete($dn); if ($result != true) { @@ -192,7 +192,7 @@ public function groups($username, $recursive = NULL, $isGUID = false) if (!$this->adldap->getLdapBind()) { return false; } // Search the directory for their information - $info = @$this->info($username, array("memberof", "primarygroupid"), $isGUID); + $info = @$this->info($username, ["memberof", "primarygroupid"], $isGUID); $groups = $this->adldap->utilities()->niceNames($info[0]["memberof"]); // Presuming the entry returned is our guy (unique usernames) if ($recursive === true){ @@ -236,7 +236,7 @@ public function info($username, $fields = NULL, $isGUID = false, $type = NULL) } $filter = ($type == "NetIQ" or $type == "LDAP") ? "(&(objectClass=person)({$filter}))":"(&(objectCategory=person)({$filter}))"; if ($fields === NULL) { - $fields = array("samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"); + $fields = ["samaccountname","mail","memberof","department","displayname","telephonenumber","primarygroupid","objectsid"]; } if (!in_array("objectsid", $fields)) { $fields[] = "objectsid"; @@ -335,9 +335,9 @@ public function passwordExpiry($username, $isGUID = false) if (!$this->adldap->getLdapBind()) { return false; } if (!function_exists('bcmod')) { throw new adLDAPException("Missing function support [bcmod] http://www.php.net/manual/en/book.bc.php"); }; - $userInfo = $this->info($username, array("pwdlastset", "useraccountcontrol"), $isGUID); + $userInfo = $this->info($username, ["pwdlastset", "useraccountcontrol"], $isGUID); $pwdLastSet = $userInfo[0]['pwdlastset'][0]; - $status = array(); + $status = []; if ($userInfo[0]['useraccountcontrol'][0] == '66048') { // Password does not expire @@ -354,7 +354,7 @@ public function passwordExpiry($username, $isGUID = false) // // Although Microsoft chose to use a different base and unit for time measurements. // This function will convert them to Unix timestamps - $sr = ldap_read($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), 'objectclass=*', array('maxPwdAge')); + $sr = ldap_read($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), 'objectclass=*', ['maxPwdAge']); if (!$sr) { return false; } @@ -378,13 +378,13 @@ public function passwordExpiry($username, $isGUID = false) // // Unfortunately the maths involved are too big for PHP integers, so I've had to require // BCMath functions to work with arbitrary precision numbers. - if (bcmod($maxPwdAge, 4294967296) === '0') { + if (bcmod((string) $maxPwdAge, 4294967296) === '0') { return "Domain does not expire passwords"; } // Add maxpwdage and pwdlastset and we get password expiration time in Microsoft's // time units. Because maxpwd age is negative we need to subtract it. - $pwdExpire = bcsub($pwdLastSet, $maxPwdAge); + $pwdExpire = bcsub((string) $pwdLastSet, (string) $maxPwdAge); // Convert MS's time to Unix time $status['expiryts'] = bcsub(bcdiv($pwdExpire, '10000000'), '11644473600'); @@ -425,10 +425,10 @@ public function modify($username, $attributes, $isGUID = false) // Set the account control attribute (only if specified) if (array_key_exists("enabled", $attributes)){ if ($attributes["enabled"]){ - $controlOptions = array("NORMAL_ACCOUNT"); + $controlOptions = ["NORMAL_ACCOUNT"]; } else { - $controlOptions = array("NORMAL_ACCOUNT", "ACCOUNTDISABLE"); + $controlOptions = ["NORMAL_ACCOUNT", "ACCOUNTDISABLE"]; } $mod["userAccountControl"][0] = $this->accountControl($controlOptions); } @@ -452,7 +452,7 @@ public function modify($username, $attributes, $isGUID = false) public function disable($username, $isGUID = false) { if ($username === NULL) { return "Missing compulsory field [username]"; } - $attributes = array("enabled" => 0); + $attributes = ["enabled" => 0]; $result = $this->modify($username, $attributes, $isGUID); if ($result == false) { return false; } @@ -469,7 +469,7 @@ public function disable($username, $isGUID = false) public function enable($username, $isGUID = false) { if ($username === NULL) { return "Missing compulsory field [username]"; } - $attributes = array("enabled" => 1); + $attributes = ["enabled" => 1]; $result = $this->modify($username, $attributes, $isGUID); if ($result == false) { return false; } @@ -498,7 +498,7 @@ public function password($username, $password, $isGUID = false) return false; } - $add=array(); + $add=[]; $add["unicodePwd"][0] = $this->encodePassword($password); $result = @ldap_mod_replace($this->adldap->getLdapConnection(), $userDn, $add); @@ -543,7 +543,7 @@ public function encodePassword($password) */ public function dn($username, $isGUID=false) { - $user = $this->info($username, array("cn"), $isGUID); + $user = $this->info($username, ["cn"], $isGUID); if ($user[0]["dn"] === NULL) { return false; } @@ -565,13 +565,13 @@ public function all($includeDescription = false, $search = "*", $sorted = true) // Perform the search and grab all their details $filter = "(&(objectClass=user)(samaccounttype=" . adLDAP::ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=" . $search . "))"; - $fields = array("samaccountname","displayname"); + $fields = ["samaccountname","displayname"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); - $usersArray = array(); + $usersArray = []; for ($i=0; $i<$entries["count"]; $i++){ - if ($includeDescription && strlen($entries[$i]["displayname"][0])>0){ + if ($includeDescription && strlen((string) $entries[$i]["displayname"][0])>0){ $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["displayname"][0]; } elseif ($includeDescription){ $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["samaccountname"][0]; @@ -597,7 +597,7 @@ public function usernameToGuid($username) if ($username === null){ return "Missing compulsory field [username]"; } $filter = "samaccountname=" . $username; - $fields = array("objectGUID"); + $fields = ["objectGUID"]; $sr = @ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); if (ldap_count_entries($this->adldap->getLdapConnection(), $sr) > 0) { $entry = @ldap_first_entry($this->adldap->getLdapConnection(), $sr); @@ -626,13 +626,13 @@ public function find($includeDescription = false, $searchField = false, $searchF $searchParams = "(" . $searchField . "=" . $searchFilter . ")"; } $filter = "(&(objectClass=user)(samaccounttype=" . adLDAP::ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)" . $searchParams . ")"; - $fields = array("samaccountname","displayname"); + $fields = ["samaccountname","displayname"]; $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields); $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr); - $usersArray = array(); + $usersArray = []; for ($i=0; $i < $entries["count"]; $i++) { - if ($includeDescription && strlen($entries[$i]["displayname"][0]) > 0) { + if ($includeDescription && strlen((string) $entries[$i]["displayname"][0]) > 0) { $usersArray[$entries[$i]["samaccountname"][0]] = $entries[$i]["displayname"][0]; } else if ($includeDescription) { @@ -663,7 +663,7 @@ public function move($username, $container) if ($container === null) { return "Missing compulsory field [container]"; } if (!is_array($container)) { return "Container must be an array"; } - $userInfo = $this->info($username, array("*")); + $userInfo = $this->info($username, ["*"]); $dn = $userInfo[0]['distinguishedname'][0]; $newRDn = "cn=" . $username; $container = array_reverse($container); @@ -685,7 +685,7 @@ public function move($username, $container) public function getLastLogon($username) { if (!$this->adldap->getLdapBind()) { return false; } if ($username === null) { return "Missing compulsory field [username]"; } - $userInfo = $this->info($username, array("lastLogonTimestamp")); + $userInfo = $this->info($username, ["lastLogonTimestamp"]); $lastLogon = adLDAPUtils::convertWindowsTimeToUnixTime($userInfo[0]['lastLogonTimestamp'][0]); return $lastLogon; } diff --git a/functions/adLDAP/src/classes/adLDAPUtils.php b/functions/adLDAP/src/classes/adLDAPUtils.php index 6d757c8a1..bb903aaee 100755 --- a/functions/adLDAP/src/classes/adLDAPUtils.php +++ b/functions/adLDAP/src/classes/adLDAPUtils.php @@ -34,7 +34,7 @@ * @version 4.0.4 * @link http://adldap.sourceforge.net/ */ -require_once(dirname(__FILE__) . '/../adLDAP.php'); +require_once(__DIR__ . '/../adLDAP.php'); /** * UTILITY FUNCTIONS @@ -63,15 +63,15 @@ public function __construct(adLDAP $adldap) { public function niceNames($groups) { - $groupArray = array(); + $groupArray = []; for ($i=0; $i<$groups["count"]; $i++){ // For each group $line = $groups[$i]; - if (strlen($line)>0) { + if (strlen((string) $line)>0) { // More presumptions, they're all prefixed with CN= // so we ditch the first three characters and the group // name goes up to the first comma - $bits=explode(",", $line); + $bits=explode(",", (string) $line); $groupArray[] = substr($bits[0], 3, (strlen($bits[0])-3)); } } diff --git a/functions/adLDAP/src/collections/adLDAPCollection.php b/functions/adLDAP/src/collections/adLDAPCollection.php index c2a23ef48..e20779b17 100755 --- a/functions/adLDAP/src/collections/adLDAPCollection.php +++ b/functions/adLDAP/src/collections/adLDAPCollection.php @@ -87,12 +87,12 @@ public function __get($attribute) { if (isset($this->info[0]) && is_array($this->info[0])) { foreach ($this->info[0] as $keyAttr => $valueAttr) { - if (strtolower($keyAttr) == strtolower($attribute)) { + if (strtolower((string) $keyAttr) == strtolower($attribute)) { if ($this->info[0][strtolower($attribute)]['count'] == 1) { return $this->info[0][strtolower($attribute)][0]; } else { - $array = array(); + $array = []; foreach ($this->info[0][strtolower($attribute)] as $key => $value) { if ((string)$key != 'count') { $array[$key] = $value; @@ -126,7 +126,7 @@ abstract public function __set($attribute, $value); public function __isset($attribute) { if (isset($this->info[0]) && is_array($this->info[0])) { foreach ($this->info[0] as $keyAttr => $valueAttr) { - if (strtolower($keyAttr) == strtolower($attribute)) { + if (strtolower((string) $keyAttr) == strtolower($attribute)) { return true; } } diff --git a/functions/checks/check_db_structure.php b/functions/checks/check_db_structure.php index 490562658..802e17b54 100755 --- a/functions/checks/check_db_structure.php +++ b/functions/checks/check_db_structure.php @@ -8,7 +8,7 @@ ****************************************/ # functions -require_once( dirname(__FILE__) . '/../functions.php' ); +require_once __DIR__ . '/../functions.php'; # Classes $Database = new Database_PDO; diff --git a/functions/checks/check_php_build.php b/functions/checks/check_php_build.php index 4d8253e32..c5e59f703 100755 --- a/functions/checks/check_php_build.php +++ b/functions/checks/check_php_build.php @@ -7,23 +7,36 @@ */ # Required extensions -$requiredExt = array("session", "sockets", "filter", "openssl", "gmp", "json", "gettext", "PDO", "pdo_mysql", "mbstring", "gd", "iconv", "ctype", "curl", "dom", "pcre", "libxml"); +$requiredExt = ["session", "sockets", "filter", "openssl", "gmp", "json", "gettext", "PDO", "pdo_mysql", "mbstring", "gd", "iconv", "ctype", "curl", "dom", "pcre", "libxml"]; # Required functions (included in php-xml or php-simplexml package) -$requiredFns = array("simplexml_load_string"); +$requiredFns = ["simplexml_load_string"]; +# Required composer packages +$requiredPks = [ + "bacon/bacon-qr-code", + "dapphp/radius", + "dapphp/securimage", + "erusev/parsedown", + "firehed/cbor", + "firehed/webauthn", + "onelogin/php-saml", + "phpgangsta/googleauthenticator", + "phpmailer/phpmailer", + ]; if(!defined('PHPIPAM_PHP_MIN')) -define('PHPIPAM_PHP_MIN', "7.2"); +define('PHPIPAM_PHP_MIN', "8.2"); if(!defined('PHPIPAM_PHP_UNTESTED')) define('PHPIPAM_PHP_UNTESTED', "8.6"); // PHP 8.6 or greater is untested, use at own risk and expect issues -if (phpversion() >= PHPIPAM_PHP_UNTESTED) { +if (phpversion() < PHPIPAM_PHP_MIN || phpversion() >= PHPIPAM_PHP_UNTESTED) { $_SESSION['footer_warnings']['php_version'] = _('Unsupported PHP version ') . phpversion(); } # Empty missing arrays to prevent errors $missingExt = []; $missingFns = []; +$missingPkg = []; # Check for missing modules $availableExt = get_loaded_extensions(); @@ -54,6 +67,20 @@ $missingExt[] = "php PEAR support"; } +# Check for Composer issues +if (!class_exists('\Composer\InstalledVersions')) { + $missingPkg[] = _("Missing vendor/autoload.php."); +} else { + foreach ($requiredPks as $package) { + if (\Composer\InstalledVersions::isInstalled($package) === false) { + $missingPkg[] = _("Composer package") . " " . $package . " " . _("is not installed."); + } + } +} +if ($composer_autoload_err && !Config::ValueOf('allow_untested_php_versions', false)) { + $missingPkg[] = $composer_autoload_err; +} + if(!isset($url)) { $url = ""; } /* headers */ @@ -75,7 +102,7 @@ $error[] = ""._('Not 64-bit system')."!

"; $error[] = _('From release 1.4 on 64bit system is required!'); } -elseif ( phpversion() < PHPIPAM_PHP_MIN ) { +elseif ( phpversion() < PHPIPAM_PHP_MIN && !Config::ValueOf('allow_untested_php_versions', false) ) { $error[] = ""._('Unsupported PHP version')."!

"; $error[] = _('Minimum PHP version required').": ".PHPIPAM_PHP_MIN."
"; $error[] = _("Detected PHP version: ").phpversion(); @@ -105,6 +132,19 @@ $error[] = '
' . "\n"; $error[] = _('Please recompile PHP to include missing functions and restart Apache.'); } +elseif ( is_dir(__DIR__ . '/../vendor') ) { + $error[] = "" . _("'functions/vendor' folder found") . ":

"; + $error[] = _("Please follow the \"Prepare for composer package management\" instructions in UPDATE.md to resolve this issue."); +} +elseif ( !empty($missingPkg) ) { + $error[] = ""._('The following composer issues are present').":

"; + $error[] = '
    ' . "\n"; + foreach ($missingPkg as $missing) { + $error[] = '
  • '. $missing .'
  • ' . "\n"; + } + $error[] = '

' . "\n"; + $error[] = _("Please run 'composer install' from the project root directory."); +} elseif ( isset($Database) && !$Database->set_names ) { $error[] = ""._('Your database server does not support utf8mb4').":

"; } diff --git a/functions/classes/class.Addresses.php b/functions/classes/class.Addresses.php index 3cf983baa..38901df99 100644 --- a/functions/classes/class.Addresses.php +++ b/functions/classes/class.Addresses.php @@ -13,7 +13,7 @@ class Addresses extends Common_functions { * @var array * @access public */ - public $address_types = array(); + public $address_types = []; /** * Mail changelog or not @@ -95,7 +95,7 @@ public function addresses_types_fetch () { $types = $this->fetch_all_objects ("ipTags", "id"); # save to array - $types_out = array(); + $types_out = []; foreach($types as $t) { $types_out[$t->id] = (array) $t; } @@ -121,7 +121,7 @@ public function address_type_format_tag ($state) { } else { if($this->address_types[$state]['showtag']==1) { - return ""; + return ""; } } } @@ -162,7 +162,7 @@ public function address_type_type_to_index ($type = "Used") { # fetch address states $this->addresses_types_fetch(); # reindex - $states_assoc = array(); + $states_assoc = []; foreach($this->address_types as $s) { $states_assoc[$s['type']] = $s; } @@ -210,7 +210,7 @@ public function fetch_address ($method, $id) { return $cached; } else { - try { $address = $this->Database->getObjectQuery("ipaddresses", "SELECT * FROM `ipaddresses` where `$method` = ? limit 1;", array($id)); } + try { $address = $this->Database->getObjectQuery("ipaddresses", "SELECT * FROM `ipaddresses` where `$method` = ? limit 1;", [$id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -233,7 +233,7 @@ public function fetch_address ($method, $id) { * @return object|false */ public function fetch_address_multiple_criteria ($ip_addr, $subnetId) { - try { $address = $this->Database->getObjectQuery("ipaddresses", "SELECT * FROM `ipaddresses` where `ip_addr` = ? and `subnetId` = ? limit 1;", array($ip_addr, $subnetId)); } + try { $address = $this->Database->getObjectQuery("ipaddresses", "SELECT * FROM `ipaddresses` where `ip_addr` = ? and `subnetId` = ? limit 1;", [$ip_addr, $subnetId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -297,7 +297,7 @@ private function bulk_fetch_similar_addresses($address, $linked_field, $value) { // Fetch all similar addresses for entire subnet. try { $query = "SELECT * FROM `ipaddresses` WHERE `state`<>4 AND `$linked_field` IN (SELECT `$linked_field` FROM `ipaddresses` WHERE `subnetId`=? AND LENGTH(`$linked_field`)>0) ORDER BY LPAD(ip_addr,39,0)"; - $linked_subnet_addrs = $this->Database->getObjectsQuery('ipaddresses', $query, array($address->subnetId)); + $linked_subnet_addrs = $this->Database->getObjectsQuery('ipaddresses', $query, [$address->subnetId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -433,7 +433,7 @@ protected function modify_address_add ($address) { # log and changelog $address['id'] = $this->lastId; $this->Log->write( _("Address create"), _("New address created").".
".$this->array_to_log($this->reformat_empty_array_fields ($address, "NULL")), 0); - $this->Log->write_changelog('ip_addr', "add", 'success', array(), $address, $this->mail_changelog); + $this->Log->write_changelog('ip_addr', "add", 'success', [], $address, $this->mail_changelog); # edit DNS PTR record $this->ptr_modify ("add", $address); @@ -529,7 +529,7 @@ protected function modify_address_delete ($address) { # log and changelog $this->Log->write( _("Address delete"), _("Address")." ".$address["ip_addr"]." "._("deleted").".
".$this->array_to_log((array) $address_old), 0); - $this->Log->write_changelog('ip_addr', "delete", 'success', (array) $address_old, array(), $this->mail_changelog); + $this->Log->write_changelog('ip_addr', "delete", 'success', (array) $address_old, [], $this->mail_changelog); # edit DNS PTR record $this->ptr_modify ("delete", $address); @@ -553,7 +553,7 @@ protected function modify_address_delete ($address) { */ protected function modify_address_move ($address) { # execute - try { $this->Database->updateObject("ipaddresses", array("subnetId"=>$address['newSubnet'], "id"=>$address['id'])); } + try { $this->Database->updateObject("ipaddresses", ["subnetId"=>$address['newSubnet'], "id"=>$address['id']]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); return false; @@ -576,7 +576,7 @@ public function remove_address_nat_items ($obj_id = 0, $print = true) { # set found flag for returns $found = 0; # fetch all nats - try { $all_nats = $this->Database->getObjectsQuery ('nat', "select * from `nat` where `src` like :id or `dst` like :id", array ("id"=>'%"'.$obj_id.'"%')); } + try { $all_nats = $this->Database->getObjectsQuery ('nat', "select * from `nat` where `src` like :id or `dst` like :id", ["id"=>'%"'.$obj_id.'"%']); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -592,9 +592,9 @@ public function remove_address_nat_items ($obj_id = 0, $print = true) { $d = db_json_decode($nat->dst, true); if(is_array($s['ipaddresses'])) - $s['ipaddresses'] = array_diff($s['ipaddresses'], array($obj_id)); + $s['ipaddresses'] = array_diff($s['ipaddresses'], [$obj_id]); if(is_array($d['ipaddresses'])) - $d['ipaddresses'] = array_diff($d['ipaddresses'], array($obj_id)); + $d['ipaddresses'] = array_diff($d['ipaddresses'], [$obj_id]); # save back and update $src_new = json_encode(array_filter($s)); @@ -604,7 +604,7 @@ public function remove_address_nat_items ($obj_id = 0, $print = true) { if($s!=$src_new || $d!=$dst_new) { $found++; - if($Admin->object_modify ("nat", "edit", "id", array("id"=>$nat->id, "src"=>$src_new, "dst"=>$dst_new))!==false) { + if($Admin->object_modify ("nat", "edit", "id", ["id"=>$nat->id, "src"=>$src_new, "dst"=>$dst_new])!==false) { if($print) { $this->Result->show("success", _("Address removed from NAT"), false); } @@ -629,13 +629,13 @@ public function remove_address_nat_items ($obj_id = 0, $print = true) { */ public function update_address_hostname ($ip, $id, $hostname = "") { if(is_numeric($id) && !is_blank($hostname)) { - try { $this->Database->updateObject("ipaddresses", array("id"=>$id, "hostname"=>$hostname)); } + try { $this->Database->updateObject("ipaddresses", ["id"=>$id, "hostname"=>$hostname]); } catch (Exception $e) { return false; } // save log $this->Log->write( _("Address DNS resolved"), _("Address")." ".$ip." "._("resolved").".
".$this->array_to_log((array) $hostname), 0); - $this->Log->write_changelog('ip_addr', "edit", 'success', array ("id"=>$id, "hostname"=>""), array("id"=>$id, "hostname"=>$hostname), $this->mail_changelog); + $this->Log->write_changelog('ip_addr', "edit", 'success', ["id"=>$id, "hostname"=>""], ["id"=>$id, "hostname"=>$hostname], $this->mail_changelog); } } @@ -648,8 +648,8 @@ public function update_address_hostname ($ip, $id, $hostname = "") { */ private function threshold_check ($address) { $address = (object) $address; - $content = array(); - $content_plain = array(); + $content = []; + $content_plain = []; # fetch settings $this->get_settings (); @@ -735,7 +735,7 @@ private function threshold_check ($address) { * @return bool */ public function remove_gateway ($subnetId) { - try { $this->Database->updateObject("ipaddresses", array("subnetId"=>$subnetId, "is_gateway"=>0), "subnetId"); } + try { $this->Database->updateObject("ipaddresses", ["subnetId"=>$subnetId, "is_gateway"=>0], "subnetId"); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -774,7 +774,7 @@ public function address_exists ($address, $subnetId, $cnt = true) { if($cnt===true) { $query = "select count(*) as `cnt` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;"; } else { $query = "select `id` from `ipaddresses` where `subnetId`=? and `ip_addr`=?;"; } # fetch - try { $count = $this->Database->getObjectQuery("ipaddresses", $query, array($subnetId, $address)); } + try { $count = $this->Database->getObjectQuery("ipaddresses", $query, [$subnetId, $address]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -815,7 +815,7 @@ public function get_first_available_address ($subnetId) { } # fetch all addresses in subnet and subnet - $addresses = $this->fetch_subnet_addresses($subnetId, "ip_addr", "asc", array("ip_addr")) ?: []; + $addresses = $this->fetch_subnet_addresses($subnetId, "ip_addr", "asc", ["ip_addr"]) ?: []; # full subnet? if (gmp_cmp(sizeof($addresses), $this->Subnets->max_hosts($subnet)) >= 0) { @@ -1091,7 +1091,7 @@ public function ptr_delete ($address, $print_error) { */ public function ptr_link ($address_id, $ptr_id) { # execute - try { $this->Database->updateObject("ipaddresses", array("id"=>$address_id, "PTR"=>$ptr_id)); } + try { $this->Database->updateObject("ipaddresses", ["id"=>$address_id, "PTR"=>$ptr_id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); return false; @@ -1108,7 +1108,7 @@ public function ptr_link ($address_id, $ptr_id) { */ private function ptr_unlink ($address_id) { # execute - try { $this->Database->updateObject("ipaddresses", array("id"=>$address_id, "PTR"=>0)); } + try { $this->Database->updateObject("ipaddresses", ["id"=>$address_id, "PTR"=>0]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); return false; @@ -1124,7 +1124,7 @@ private function ptr_unlink ($address_id) { * @return bool */ public function ptr_unlink_subnet_addresses ($subnet_id) { - try { $this->Database->runQuery("update `ipaddresses` set `PTR` = 0 where `subnetId` = ?;", array($subnet_id)); } + try { $this->Database->runQuery("update `ipaddresses` set `PTR` = 0 where `subnetId` = ?;", [$subnet_id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -1152,14 +1152,14 @@ private function ptr_exists ($ptr_id = 0) { * @return void */ public function ptr_get_subnet_indexes ($subnetId) { - try { $indexes = $this->Database->getObjectsQuery('ipaddresses', "select `PTR` from `ipaddresses` where `PTR` != 0 and `subnetId` = ?;", array($subnetId)); } + try { $indexes = $this->Database->getObjectsQuery('ipaddresses', "select `PTR` from `ipaddresses` where `PTR` != 0 and `subnetId` = ?;", [$subnetId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; } # parse if (sizeof($indexes)>0) { - $out = array(); + $out = []; // loop foreach ($indexes as $i) { $out[] = $i->PTR; @@ -1167,7 +1167,7 @@ public function ptr_get_subnet_indexes ($subnetId) { return $out; } else { - return array(); + return []; } } @@ -1208,7 +1208,7 @@ public function import_address_from_csv ($address, $subnetId) { if ($this->address_exists($address[0], $subnetId)) { return _('IP address already exists').' - '.$address[0]; } # format insert array - $address_insert = array("subnetId"=>$subnetId, + $address_insert = ["subnetId"=>$subnetId, "ip_addr"=>$address[0], "state"=>$address[1], "description"=>$address[2], @@ -1218,7 +1218,7 @@ public function import_address_from_csv ($address, $subnetId) { "switch"=>$address[6], "port"=>$address[7], "note"=>$address[8] - ); + ]; # switch to 0, state to active $address_insert['switch'] = is_blank($address_insert['switch']) ? 0 : $address_insert['switch']; @@ -1274,8 +1274,8 @@ private function initialize_subnets_object () { */ public function fetch_subnet_addresses ($subnetId, $order=null, $order_direction=null, $fields = "*") { # set order - if(!is_null($order)) { $order = array($order, $order_direction); } - else { $order = array("ip_addr", "asc"); } + if(!is_null($order)) { $order = [$order, $order_direction]; } + else { $order = ["ip_addr", "asc"]; } # fields if(is_array($fields)) { @@ -1286,7 +1286,7 @@ public function fetch_subnet_addresses ($subnetId, $order=null, $order_direction $order[0] = $this->Database->escape ($order[0]); $order[1] = $this->Database->escape ($order[1]); - try { $addresses = $this->Database->getObjectsQuery('ipaddresses', "SELECT $fields FROM `ipaddresses` where `subnetId` = ? order by `$order[0]` $order[1];", array($subnetId)); } + try { $addresses = $this->Database->getObjectsQuery('ipaddresses', "SELECT $fields FROM `ipaddresses` where `subnetId` = ? order by `$order[0]` $order[1];", [$subnetId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -1298,7 +1298,7 @@ public function fetch_subnet_addresses ($subnetId, $order=null, $order_direction } } # result - return !empty($addresses) ? $addresses : array(); + return !empty($addresses) ? $addresses : []; } /** @@ -1334,7 +1334,7 @@ public function count_addresses_in_multiple_subnets ($subnets) { if(empty($subnets)) { return 0; } # create query - $tmp = array(); + $tmp = []; foreach($subnets as $k=>$s) { if (is_object($s)) { $tmp[] = " `subnetId`=$s->id "; } else { $tmp[] = " `subnetId`=$s "; } @@ -1373,14 +1373,14 @@ public function fetch_subnet_addresses_recursive ($subnetId, $count = false, $or $this->Subnets->slaves = []; # ip address order - if(!is_null($order)) { $order_addr = array($order, $order_direction); } - else { $order_addr = array("ip_addr", "asc"); } + if(!is_null($order)) { $order_addr = [$order, $order_direction]; } + else { $order_addr = ["ip_addr", "asc"]; } # escape ordering $order_addr[0] = $this->Database->escape ($order_addr[0]); $order_addr[1] = $this->Database->escape ($order_addr[1]); - $ids = array(); + $ids = []; $ids[] = $subnetId; # set query to fetch all ip addresses for specified subnets or just count @@ -1568,7 +1568,7 @@ public function compress_address_ranges ($addresses, $state=4) { # set size $size = sizeof($addresses); // vars - $addresses_formatted = array(); + $addresses_formatted = []; $fIndex = null; # loop through IP addresses @@ -1635,7 +1635,7 @@ public function compress_address_ranges ($addresses, $state=4) { */ public function find_invalid_addresses () { // init - $false = array(); + $false = []; // find unique ids $ids = $this->find_unique_subnetids (); @@ -1675,7 +1675,7 @@ private function find_unique_subnetids () { * * @access private * @param mixed $id - * @return void + * @return bool */ private function verify_subnet_id ($id) { try { $res = $this->Database->numObjectsFilter("subnets", "id", $id ); } @@ -1793,11 +1793,11 @@ public function check_permission ($user, $subnetId) { * @return void */ public function reformat_number ($number) { - $length = strlen($number); + $length = strlen((string) $number); $pos = $length - 3; if ($length > 8) { - $number = "~". substr($number, 0, $length - $pos) . "·10^". $pos .""; + $number = "~". substr((string) $number, 0, $length - $pos) . "·10^". $pos .""; } return $number; } @@ -1832,7 +1832,7 @@ public function print_nat_link ($all_nats, $all_nats_per_object, $subnet, $addre $address = new Params($address); // cnt - $html = array(); + $html = []; $html[] = ''; $cnt = 0; @@ -1891,19 +1891,19 @@ public function print_nat_link_line ($n, $nat_id = false, $object_type = false, // no src/dst if ($sources===false) - $sources = array(""._("None").""); + $sources = [""._("None").""]; if ($destinations===false) - $destinations = array(""._("None").""); + $destinations = [""._("None").""]; // icon $icon = $n->type=="static" ? "fa-arrows-h" : "fa-long-arrow-right"; // to html - $html = array(); + $html = []; $html[] = ""; $html[] = ""; $html[] = ""; @@ -1947,7 +1947,7 @@ public function translate_nat_objects_for_popup ($json_objects, $nat_id = false, // to array "subnets"=>array(1,2,3) $objects = db_json_decode($json_objects, true); // init out array - $out = array(); + $out = []; // check if(is_array($objects)) { if(sizeof($objects)>0) { diff --git a/functions/classes/class.Admin.php b/functions/classes/class.Admin.php index 7d9dad90a..b41ff6a49 100644 --- a/functions/classes/class.Admin.php +++ b/functions/classes/class.Admin.php @@ -291,7 +291,7 @@ public function remove_object_references ($table, $field, $old_value, $new_value $table = $this->Database->escape($table); $field = $this->Database->escape($field); - try { $this->Database->runQuery("update `$table` set `$field` = ? where `$field` = ?;", array($new_value, $old_value)); } + try { $this->Database->runQuery("update `$table` set `$field` = ? where `$field` = ?;", [$new_value, $old_value]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); return false; @@ -312,7 +312,7 @@ public function update_object_references ($table, $field, $old_value, $new_value $table = $this->Database->escape($table); $field = $this->Database->escape($field); - try { $this->Database->runQuery("update `$table` set `$field` = ? where `$field` = ?;", array($new_value, $old_value)); } + try { $this->Database->runQuery("update `$table` set `$field` = ? where `$field` = ?;", [$new_value, $old_value]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); return false; @@ -362,7 +362,7 @@ public function truncate_table ($table = null) { * @return array */ public function groups_parse ($group_ids) { - $out = array (); + $out = []; // check if(!is_null($group_ids)) { if(sizeof($group_ids)>0) { @@ -388,7 +388,7 @@ public function groups_parse ($group_ids) { * @return array */ public function groups_parse_ids ($group_ids) { - $out = array (); + $out = []; // check if(!is_null($group_ids)) { if(sizeof($group_ids) >0) { @@ -409,7 +409,7 @@ public function groups_parse_ids ($group_ids) { * @return array of user ids */ public function group_fetch_users ($group_id) { - $out = array (); + $out = []; # get all users $users = $this->fetch_all_objects("users"); # check if $gid in array @@ -428,7 +428,7 @@ public function group_fetch_users ($group_id) { } } # return - return isset($out) ? $out : array(); + return isset($out) ? $out : []; } /** @@ -439,7 +439,7 @@ public function group_fetch_users ($group_id) { * @return array */ public function group_fetch_missing_users ($group_id) { - $out = array (); + $out = []; # get all users $users = $this->fetch_all_objects("users"); @@ -515,7 +515,7 @@ public function remove_group_from_user($gid, $uid) { * @return void */ public function update_user_groups ($uid, $groups) { - return $this->object_modify ("users", "edit", "id", array("id"=>$uid, "groups"=>$groups)); + return $this->object_modify ("users", "edit", "id", ["id"=>$uid, "groups"=>$groups]); } /** @@ -527,7 +527,7 @@ public function update_user_groups ($uid, $groups) { * @return void */ public function update_section_groups($sid, $groups) { - return $this->object_modify ("sections", "edit", "id", array("id"=>$sid, "permissions"=>$groups)); + return $this->object_modify ("sections", "edit", "id", ["id"=>$sid, "permissions"=>$groups]); } /** @@ -577,7 +577,7 @@ public function remove_group_from_sections ($gid) { if(is_array($g)) { if(sizeof($g)>0) { - if(array_key_exists($gid, $g)) { + if(array_key_exists((string) $gid, $g)) { unset($g[$gid]); $ng = json_encode($g); $this->update_section_groups($s->id,$ng); @@ -621,7 +621,7 @@ public function replace_fields ($field, $search, $replace) { # if some exist update if($count>0) { # update - try { $this->Database->runQuery("update `ipaddresses` set `$field` = replace(`$field`, ?, ?);", array($search, $replace)); } + try { $this->Database->runQuery("update `ipaddresses` set `$field` = replace(`$field`, ?, ?);", [$search, $replace]); } catch (Exception $e) { $this->Result->show("danger alert-absolute", _("Error: ").$e->getMessage(), true); } @@ -696,7 +696,7 @@ public function update_custom_field_definition ($field) { $this->Result->show("danger", _("Error: ") . _("SET functionality not fully implemented, please change to ENUM")); return false; case "enum": - $data = str_getcsv($field['fieldSize'], ",", "'", "\\"); + $data = str_getcsv((string) $field['fieldSize'], ",", "'", "\\"); foreach ($data as $i => $v) { $data[$i] = "'" . $this->Database->escape($v) . "'"; } @@ -738,7 +738,7 @@ public function update_custom_field_definition ($field) { } # set parametized values - $params = array(); + $params = []; if (strpos($query, ":default")>0) $params['default'] = $field['fieldDefault']; if (strpos($query, ":comment")>0) $params['comment'] = $field['Comment']; @@ -764,7 +764,7 @@ public function update_custom_field_definition ($field) { */ public function save_custom_fields_filter ($table, $filtered_fields) { # old custom fields, save them to array - $hidden_array = !is_blank($this->settings->hiddenCustomFields) ? db_json_decode($this->settings->hiddenCustomFields, true) : array(); + $hidden_array = !is_blank($this->settings->hiddenCustomFields) ? db_json_decode($this->settings->hiddenCustomFields, true) : []; # set new array for table if(is_null($filtered_fields)) { unset($hidden_array[$table]); } @@ -774,7 +774,7 @@ public function save_custom_fields_filter ($table, $filtered_fields) { $hidden_json = json_encode($hidden_array, JSON_UNESCAPED_UNICODE); # update database - try { $this->object_edit ("settings", $key="id", array("id"=>1,"hiddenCustomFields"=>$hidden_json)); } + try { $this->object_edit ("settings", $key="id", ["id"=>1,"hiddenCustomFields"=>$hidden_json]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), true); } diff --git a/functions/classes/class.Common.php b/functions/classes/class.Common.php index 650b004f2..d2839f11d 100644 --- a/functions/classes/class.Common.php +++ b/functions/classes/class.Common.php @@ -37,12 +37,6 @@ class Common_functions { public $json_error = false; /** - * Composer error flag - * @var bool - */ - public $composer_err = false; - - /** * Default font * * (default value: "Database->escape($method); - try { $res = $this->Database->getObjectQuery($table, "SELECT * from `$table` where `$method` = ? limit 1;", array($value)); } + try { $res = $this->Database->getObjectQuery($table, "SELECT * from `$table` where `$method` = ? limit 1;", [$value]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -392,7 +386,7 @@ public function changelog_mail_get_recipients ($subnetId = false) { // fetch all users with mailNotify $notification_users = $this->fetch_multiple_objects ("users", "mailChangelog", "Yes", "id", true); // recipients array - $recipients = array(); + $recipients = []; // any ? if (is_array($notification_users)) { if(sizeof($notification_users)>0) { @@ -520,7 +514,7 @@ protected function cache_check_add_ip ($table) { $ip_tables = ["subnets"=>"subnet", "ipaddresses"=>"ip_addr"]; // check - return array_key_exists ($table, $ip_tables) ? $ip_tables[$table] : false; + return array_key_exists ((string) $table, $ip_tables) ? $ip_tables[$table] : false; } /** @@ -594,7 +588,7 @@ public function get_debugging () { public function initialize_pear_net_IPv4 () { //initialize NET object if(!is_object($this->Net_IPv4)) { - require_once( dirname(__FILE__) . '/../../functions/PEAR/Net/IPv4.php' ); + require_once __DIR__ . '/../PEAR/Net/IPv4.php'; //initialize object $this->Net_IPv4 = new Net_IPv4(); } @@ -609,7 +603,7 @@ public function initialize_pear_net_IPv4 () { public function initialize_pear_net_IPv6 () { //initialize NET object if(!is_object($this->Net_IPv6)) { - require_once( dirname(__FILE__) . '/../../functions/PEAR/Net/IPv6.php' ); + require_once __DIR__ . '/../PEAR/Net/IPv6.php'; //initialize object $this->Net_IPv6 = new Net_IPv6(); } @@ -624,9 +618,9 @@ public function initialize_pear_net_IPv6 () { public function initialize_pear_net_DNS2 () { //initialize NET object if(!is_object($this->DNS2)) { - require_once( dirname(__FILE__) . '/../../functions/PEAR/Net/DNS2.php' ); + require_once __DIR__ . '/../PEAR/Net/DNS2.php'; //initialize object - $this->DNS2 = new Net_DNS2_Resolver(array("timeout"=>2)); + $this->DNS2 = new Net_DNS2_Resolver(["timeout"=>2]); } } @@ -644,7 +638,7 @@ public function strip_input_tags ($input) { $input[$k] = $this->strip_input_tags($v); continue; } - $input[$k] = is_null($v) ? NULL : strip_tags($v); + $input[$k] = is_null($v) ? NULL : strip_tags((string) $v); } # stripped array return $input; @@ -663,7 +657,7 @@ public function strip_input_tags ($input) { * @return array */ public function reformat_empty_array_fields ($fields, $char = "/") { - $out = array(); + $out = []; // loop foreach($fields as $k=>$v) { if(is_array($v)) { @@ -690,7 +684,7 @@ public function reformat_empty_array_fields ($fields, $char = "/") { */ public function remove_empty_array_fields ($fields) { // init - $out = array(); + $out = []; // loop if(is_array($fields)) { foreach($fields as $k=>$v) { @@ -737,8 +731,8 @@ public function verify_checkbox ($field) { */ public function identify_address ($address) { # dotted representation - if (strpos($address, ':') !== false) return 'IPv6'; - if (strpos($address, '.') !== false) return 'IPv4'; + if (strpos((string) $address, ':') !== false) return 'IPv6'; + if (strpos((string) $address, '.') !== false) return 'IPv4'; # numeric representation if (is_numeric($address)) { if($address <= 4294967295) return 'IPv4'; // 4294967295 = '255.255.255.255' @@ -777,7 +771,7 @@ public function array_to_log ($logs, $changelog = false) { foreach($logs as $key=>$req) { # ignore __ and PHPSESSID - if( substr($key,0,2)=='__' || substr($key,0,9)=='PHPSESSID' || substr($key,0,4)=='pass' || $key=='plainpass' || $key=='values') + if( substr((string) $key,0,2)=='__' || substr((string) $key,0,9)=='PHPSESSID' || substr((string) $key,0,4)=='pass' || $key=='plainpass' || $key=='values') continue; // NOTE The colon character ":" is reserved as it used in array_to_log for implode/explode. @@ -845,10 +839,10 @@ public function shorten_text($text, $chars = 25) { // minimum length = 8 if ($chars < 8) $chars = 8; // count input text size - $origLen = mb_strlen($text); + $origLen = mb_strlen((string) $text); // cut unwanted chars if ($origLen > $chars) { - $text = mb_substr($text, 0, $chars-3) . '...'; + $text = mb_substr((string) $text, 0, $chars-3) . '...'; } return $text; } @@ -867,7 +861,7 @@ public function shorten_text($text, $chars = 25) { */ public function reformat_mac_address ($mac, $format = 1) { // strip al tags first - $mac = strtolower(str_replace(array(":",".","-"), "", $mac)); + $mac = strtolower(str_replace([":",".","-"], "", (string) $mac)); // format 4 if ($format==4) { return $mac; @@ -1023,7 +1017,7 @@ public function create_links ($text, $field_type = "varchar") { * @return string[] */ private function get_valid_actions () { - return array( + return [ "add", "all-add", "edit", @@ -1035,7 +1029,7 @@ private function get_valid_actions () { "move", "remove", "assign" - ); + ]; } /** @@ -1065,7 +1059,7 @@ public function get_post_action() { $valid_actions = $this->get_valid_actions(); if (in_array($action, $valid_actions)) { - return escape_input(ucwords(_($action))); + return escape_input(ucwords(_((string) $action))); } else { return _('Invalid $_POST action'); } @@ -1111,7 +1105,7 @@ public function validate_hostname($hostname = "", $permit_root_domain=true) { return $valid; } else { - if(strpos($hostname, ".")!==false) { return $valid; } + if(strpos((string) $hostname, ".")!==false) { return $valid; } else { return false; } } } @@ -1175,9 +1169,9 @@ public function validate_json_string($string) { */ public function validate_postcode ($value = "", $country = 'united kingdom') { // to lower - $country = strtolower($country); + $country = strtolower((string) $country); // set regexes - $country_regex = array( + $country_regex = [ 'united kingdom' => '/^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$/i', 'isle of man' => '/\\A\\bIM[0-9][0-9]? [0-9][A-Z][A-Z]\\b\\z/i', 'england' => '/^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$/i', @@ -1188,14 +1182,14 @@ public function validate_postcode ($value = "", $country = 'united kingdom') { 'belgium' => '/^[1-9]{1}[0-9]{3}$/i', 'united states' => '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i', 'default' => '/^[0-9]/i', - ); + ]; // check for country if ( isset($country_regex[$country]) ) { - return preg_match($country_regex[$country], $value); + return preg_match($country_regex[$country], (string) $value); } // default - return preg_match($country_regex['default'], $value); + return preg_match($country_regex['default'], (string) $value); } /** @@ -1324,7 +1318,7 @@ protected function get_addresses_types () { return; # save to array - $types_out = array(); + $types_out = []; foreach($types as $t) { $types_out[$t->id] = (array) $t; } @@ -1355,7 +1349,7 @@ protected function translate_address_type ($index) { */ public function json_error_decode ($error_int) { // init - $error = array(); + $error = []; // error definitions $error[0] = "JSON_ERROR_NONE"; $error[1] = "JSON_ERROR_DEPTH"; @@ -1412,8 +1406,11 @@ public function curl_fetch_url($url, $headers=false, $timeout=30) { $result['result_code'] = curl_getinfo($curl, CURLINFO_HTTP_CODE); $result['error_msg'] = curl_error($curl); - // close - curl_close ($curl); + if (version_compare(PHP_VERSION, '8.5.0', '<')) { + // phpcs:ignore + curl_close ($curl); + // phpcs:ignore + } } catch (Exception $e) { $result['error_msg'] = $e->getMessage(); @@ -1433,7 +1430,7 @@ public function curl_fetch_url($url, $headers=false, $timeout=30) { */ public function update_latlng ($id, $lat, $lng) { # execute - try { $this->Database->updateObject("locations", array("id"=>$id, "lat"=>$lat, "long"=>$lng), "id"); } + try { $this->Database->updateObject("locations", ["id"=>$id, "lat"=>$lat, "long"=>$lng], "id"); } catch (Exception $e) { return false; } @@ -1460,7 +1457,7 @@ public function create_custom_field_input ($field, $object, $timepicker_index, $ // disabled $disabled_text = $disabled ? "readonly" : ""; // replace spaces with | - $field['nameNew'] = str_replace(" ", "___", $field['name']); + $field['nameNew'] = str_replace(" ", "___", (string) $field['name']); // required $required = $field['Null']=="NO" ? "*" : ""; // set default value if adding new object @@ -1469,7 +1466,7 @@ public function create_custom_field_input ($field, $object, $timepicker_index, $ } //set, enum - if(substr($field['type'], 0,3) == "set" || substr($field['type'], 0,4) == "enum") { + if(substr((string) $field['type'], 0,3) == "set" || substr((string) $field['type'], 0,4) == "enum") { $html = $this->create_custom_field_input_set_enum ($field, $object, $disabled_text, $set_delimiter, $nameSuffix); } //date and time picker @@ -1490,11 +1487,11 @@ public function create_custom_field_input ($field, $object, $timepicker_index, $ } # result - return array( + return [ "required" => $required, "field" => implode("\n", $html), "timepicker_index" => $timepicker_index - ); + ]; } /** @@ -1509,10 +1506,10 @@ public function create_custom_field_input ($field, $object, $timepicker_index, $ * @return array */ private function create_custom_field_input_set_enum ($field, $object, $disabled_text, $set_delimiter = "", $nameSuffix = "") { - $html = array(); + $html = []; //parse values - $field['type'] = trim(substr($field['type'],0,-1)); - $tmp = substr($field['type'], 0,3)=="set" ? pf_explode(",", str_replace(array("set(", "'"), "", $field['type'])) : pf_explode(",", str_replace(array("enum(", "'"), "", $field['type'])); + $field['type'] = trim(substr((string) $field['type'],0,-1)); + $tmp = substr($field['type'], 0,3)=="set" ? explode(",", str_replace(["set(", "'"], "", $field['type'])) : explode(",", str_replace(["enum(", "'"], "", $field['type'])); //null if($field['Null']!="NO") { array_unshift($tmp, ""); } @@ -1553,7 +1550,7 @@ private function create_custom_field_input_set_enum ($field, $object, $disabled_ * @return array */ private function create_custom_field_input_date ($field, $object, &$timepicker_index, $disabled_text, $nameSuffix = "") { - $html = array (); + $html = []; // just for first if($timepicker_index==0) { $html[] = ''; @@ -1592,9 +1589,9 @@ private function create_custom_field_input_date ($field, $object, &$timepicker_i * @return array */ private function create_custom_field_input_boolean ($field, $object, $disabled_text, $nameSuffix = "") { - $html = array (); + $html = []; $html[] = "'. "\n"; // result return $html; @@ -1636,14 +1633,14 @@ private function create_custom_field_input_textarea ($field, $object, $disabled_ * @return array */ private function create_custom_field_input_input ($field, $object, $disabled_text, $nameSuffix = "") { - $html = array (); + $html = []; // max length $maxlength = 100; - if(strpos($field['type'],"varchar")!==false) { - $maxlength = str_replace(array("varchar","(",")"),"", $field['type']); + if(strpos((string) $field['type'],"varchar")!==false) { + $maxlength = str_replace(["varchar","(",")"],"", (string) $field['type']); } - if(strpos($field['type'],"int")!==false) { - $maxlength = str_replace(array("int","(",")"),"", $field['type']); + if(strpos((string) $field['type'],"int")!==false) { + $maxlength = str_replace(["int","(",")"],"", (string) $field['type']); } // print $html[] = ' '. "\n"; @@ -1668,7 +1665,7 @@ public function print_custom_field ($type, $value, $delimiter = false, $replacem // delimiter ? if($delimiter !== false && $replacement !== false) { - $value = str_replace($delimiter, $replacement, $value); + $value = str_replace($delimiter, (string) $replacement, $value); } //booleans @@ -1765,7 +1762,7 @@ public function get_mac_address_vendor_details($mac, &$prefix=null) { // Generated from vendorMac.xml // Unique MAC address: 51316 // Updated: 05 April 2024 - $data = file_get_contents(dirname(__FILE__) . "/../vendormacs.json"); + $data = file_get_contents(__DIR__ . '/../vendormacs.json'); if (is_string($data)) { $this->mac_address_vendors = json_decode($data, true); } @@ -1795,14 +1792,14 @@ public function get_mac_address_vendor_details($mac, &$prefix=null) { * @return array */ public function get_permission_changes ($post_permissions, $old_permissions) { - $new_permissions = array(); - $removed_permissions = array(); - $changed_permissions = array(); + $new_permissions = []; + $removed_permissions = []; + $changed_permissions = []; # set new posted permissions foreach($post_permissions as $key=>$val) { - if(substr($key, 0,5) == "group") { - if($val != "0") $new_permissions[substr($key,5)] = $val; + if(substr((string) $key, 0,5) == "group") { + if($val != "0") $new_permissions[substr((string) $key,5)] = $val; } } @@ -1818,7 +1815,7 @@ public function get_permission_changes ($post_permissions, $old_permissions) { } } } else { - $old_permissions = array(); // fix for adding + $old_permissions = []; // fix for adding } // add also new groups if available if(is_array($new_permissions)) { @@ -1829,7 +1826,7 @@ public function get_permission_changes ($post_permissions, $old_permissions) { } } - return array($removed_permissions, $changed_permissions, $new_permissions); + return [$removed_permissions, $changed_permissions, $new_permissions]; } /** @@ -2021,7 +2018,7 @@ public function get_site_title ($get) { // remove html tags $get = $this->strip_input_tags($get); // init - $title = array(); + $title = []; $title[] = $this->settings->siteTitle; // page @@ -2289,68 +2286,4 @@ private function print_actions_buttons ($items = []) { // result return implode("\n", $html); } - - /** - * Composer auto-load error-handler. - * - * @param int $errno - * @param string $errstr - * @param string $errfile - * @param int $errline - * @return bool - */ - static function composer_autoload_error_handler($errno, $errstr, $errfile, $errline) { - $Result = new Result(); - $Result->show($errno >128 ? 'danger' : 'warning', "
" . escape_input($errfile) . ":" . escape_input($errline) . "
" . escape_input($errstr)); - return true; - } - - /** - * Composer check - * - * Checks if composer is installed and if requested checks for composer modules required - * - * @method composer_has_error - * @param array $composer_packages - * @return bool - */ - public function composer_has_errors ($composer_packages = []) { - // check for autoload file - if(!file_exists(__DIR__ . '/../vendor/autoload.php')) { - $this->composer_err = _("Composer autoload not present")." !
"._("Please install composer modules ( cd functions && composer install )."); - return true; - } - - // autoload composer files - catch and display errors. - $old_handler = set_error_handler("Common_functions::composer_autoload_error_handler", E_ALL); - require __DIR__ . '/../vendor/autoload.php'; - set_error_handler($old_handler, E_ALL); - - // check if composer is installed - if (!class_exists('\Composer\InstalledVersions')) { - $this->composer_err = _("Composer is not installed")."!
"._("Please install composer and composer modules ( cd functions && composer install )."); - return true; - } - - // validate all packages if required - if(is_array($composer_packages)) { - if(sizeof($composer_packages)>0) { - foreach ($composer_packages as $package) { - if(\Composer\InstalledVersions::isInstalled($package)===false) { - $this->composer_err .= _("Composer package")." ".$package." "._("is not installed")." !
"._("Please install required modules ( cd functions && composer install )."); - } - } - // check - if ($this->composer_err!==false) { - return true; - } - } - } - // all good - return false; - } - - } - - diff --git a/functions/classes/class.Config.php b/functions/classes/class.Config.php index fe476ea57..ab31b7d58 100644 --- a/functions/classes/class.Config.php +++ b/functions/classes/class.Config.php @@ -18,14 +18,14 @@ class Config { * * @return string */ - private static function config_file_path() { + public static function config_file_path() { // IPAM_CONFIG_FILE, alternative config.php location $alt_file = getenv('IPAM_CONFIG_FILE'); if (is_string($alt_file) && preg_match('/\.php$/', $alt_file) && is_readable($alt_file)) { return $alt_file; } - return dirname(__FILE__) . "/../../config.php"; + return __DIR__ . "/../../config.php"; } /** @@ -33,7 +33,7 @@ private static function config_file_path() { * @return void */ private static function read_config() { - require(self::config_file_path()); + require self::config_file_path(); self::$config = (object) get_defined_vars(); } diff --git a/functions/classes/class.Crypto.php b/functions/classes/class.Crypto.php index 8a2f6b511..2100798ae 100644 --- a/functions/classes/class.Crypto.php +++ b/functions/classes/class.Crypto.php @@ -4,12 +4,6 @@ * Cryptographic Code */ class Crypto { - /** - * mcrypt cipher mode. - * Change to MCRYPT_RIJNDAEL_128 to use AES-256 compliant RIJNDAEL algorithm (rijndael-128) - * @var mixed - */ - private $legacy_mcrypt_aes_mode = "rijndael-256"; // Use string value as MCRYPT_RIJNDAEL_256 constant may not be defined. /** * Result @@ -56,7 +50,7 @@ public function random_pseudo_bytes($len) { * @return string|false */ private function hash_hmac($algo, $data1, $data2, $raw_output = false) { - $hash = hash_hmac($algo, $data1, $data2, $raw_output); + $hash = hash_hmac($algo, (string) $data1, (string) $data2, $raw_output); if ($hash !== false) return $hash; @@ -77,10 +71,7 @@ private function hash_hmac($algo, $data1, $data2, $raw_output = false) { public function encrypt($rawdata, $password, $method="openssl-128-cbc") { $method = $this->supported_methods($method); - if ($method === 'mcrypt') - return $this->encrypt_using_legacy_mcrypt($rawdata, $password); - else - return $this->encrypt_using_openssl($rawdata, $password, $method); + return $this->encrypt_using_openssl($rawdata, $password, $method); } /** @@ -93,10 +84,7 @@ public function encrypt($rawdata, $password, $method="openssl-128-cbc") { public function decrypt($base64data, $password, $method="openssl-128-cbc") { $method = $this->supported_methods($method); - if ($method === "mcrypt") - return $this->decrypt_using_legacy_mcrypt($base64data, $password); - else - return $this->decrypt_using_openssl($base64data, $password, $method); + return $this->decrypt_using_openssl($base64data, $password, $method); } /** @@ -106,10 +94,6 @@ public function decrypt($base64data, $password, $method="openssl-128-cbc") { */ private function supported_methods($method) { switch ($method) { - case 'mcrypt': - $retval = 'mcrypt'; - break; - case 'openssl': case 'openssl-128': case 'openssl-128-cbc': @@ -125,10 +109,6 @@ private function supported_methods($method) { $this->Result->show("danger", _("Error: "). _("Unsupported encryption method").": ".escape_input($method), true); } - $required_ext = ($retval === 'mcrypt') ? 'mcrypt' : 'openssl'; - if (!in_array($required_ext, get_loaded_extensions())) - $this->Result->show("danger", _("Error: "). _('PHP extension not installed: ').$required_ext, true); - return $retval; } @@ -190,30 +170,6 @@ private function decrypt_using_openssl($base64data, $password, $method) { return openssl_decrypt($ciphertext_raw, $method, $key, OPENSSL_RAW_DATA, $iv); } - // Legacy mcrypt - mcrypt support may be removed in a future release. - - /** - * encrypt data and base64 encode results - * @param string $rawdata - * @param string $password - * @return string|false - */ - private function encrypt_using_legacy_mcrypt($rawdata, $password) { - // Suppress php72 mcrypt deprecation warnings (module is available in PECL). - return base64_encode(@mcrypt_encrypt($this->legacy_mcrypt_aes_mode, $password, $rawdata, MCRYPT_MODE_ECB)); - } - - /** - * decrypt base64 encoded data - * @param string $base64data - * @param string $password - * @return string|false - */ - private function decrypt_using_legacy_mcrypt($base64data, $password) { - // Suppress php72 mcrypt deprecation warnings (module is available in PECL). - return trim(@mcrypt_decrypt($this->legacy_mcrypt_aes_mode, $password, base64_decode($base64data), MCRYPT_MODE_ECB)); - } - /**** Security Tokens ****/ /** diff --git a/functions/classes/class.DHCP.kea.php b/functions/classes/class.DHCP.kea.php index db366bde6..3145a2a2b 100644 --- a/functions/classes/class.DHCP.kea.php +++ b/functions/classes/class.DHCP.kea.php @@ -30,7 +30,7 @@ class DHCP_kea extends Common_functions { * @var array * @access private */ - private $kea_settings = array(); + private $kea_settings = []; /** * Raw config file @@ -83,7 +83,7 @@ class DHCP_kea extends Common_functions { * @var array * @access public */ - public $subnets4 = array(); + public $subnets4 = []; /** * Array to store DHCP subnets, parsed from config file @@ -96,7 +96,7 @@ class DHCP_kea extends Common_functions { * @var array * @access public */ - public $subnets6 = array(); + public $subnets6 = []; /** * set available lease database types @@ -106,7 +106,7 @@ class DHCP_kea extends Common_functions { * @var array * @access public */ - public $lease_types = array("memfile", "mysql", "postgresql"); + public $lease_types = ["memfile", "mysql", "postgresql"]; /** * List of active leases @@ -116,7 +116,7 @@ class DHCP_kea extends Common_functions { * @var array * @access public */ - public $leases4 = array(); + public $leases4 = []; /** * List of active leases @@ -126,7 +126,7 @@ class DHCP_kea extends Common_functions { * @var array * @access public */ - public $leases6 = array(); + public $leases6 = []; /** * Available reservation methods @@ -136,7 +136,7 @@ class DHCP_kea extends Common_functions { * @var array * @access public */ - public $reservation_types = array("file", "mysql"); + public $reservation_types = ["file", "mysql"]; /** * Definition of hosts reservations @@ -146,8 +146,8 @@ class DHCP_kea extends Common_functions { * @var array * @access public */ - public $reservations4 = array(); - public $reservations6 = array(); + public $reservations4 = []; + public $reservations6 = []; /** * Database object for leases and hosts @@ -168,7 +168,7 @@ class DHCP_kea extends Common_functions { * @param array $kea_settings (default: array()) * @return void */ - public function __construct($kea_settings = array()) { + public function __construct($kea_settings = []) { // save settings if (is_array($kea_settings)) { $this->kea_settings = $kea_settings; } else { throw new exception ("Invalid kea settings"); } @@ -226,7 +226,7 @@ private function parse_config () { } // loop and remove comments (contains #) and replace multiple spaces - $out = array(); + $out = []; foreach ($config as $k=>$f) { if (strpos($f, "#")!==false || is_blank($f)) {} else { @@ -322,12 +322,12 @@ private function get_leases_memfile ($lease_database, $type) { // if leases are present format to array if (sizeof($leases_from_file)>0 && $leases_from_file!==false) { // init array - $leases_parsed = array(); + $leases_parsed = []; // loop and save leases foreach ($leases_from_file as $l) { if(strlen($l)>1) { // to array - $l = pf_explode(",", $l); + $l = explode(",", (string) $l); // set state switch ($l[9]) { @@ -343,7 +343,7 @@ private function get_leases_memfile ($lease_database, $type) { } // save only active if ($l[4] > time() ) { - $leases_parsed[] = array( + $leases_parsed[] = [ "address" => $l[0], "hwaddr" => $l[1], "client_id" => $l[2], @@ -354,7 +354,7 @@ private function get_leases_memfile ($lease_database, $type) { "fqdn_rev" => $l[7], "hostname" => $l[8], "state" => $l[9] - ); + ]; } } } @@ -408,7 +408,7 @@ private function get_leases_mysql ($lease_database, $type) { // save leases if (sizeof($leases)>0) { // we need array - $result = array(); + $result = []; // loop foreach ($leases as $k=>$l) { $result[$k] = (array) $l; @@ -521,28 +521,28 @@ private function get_reservations_config_file ($type, $reservations_database) { unset($s_id); $s_id = isset($s['id']) ? $s['id'] : ""; // init array - $this->reservations4 = array(); + $this->reservations4 = []; $m=0; // loop foreach ($s['reservations'] as $r) { - $this->reservations4[$m] = array( + $this->reservations4[$m] = [ "location" => "Config file", "hw-address" => $r['hw-address'], "ip-address" => $r['ip-address'], "hostname" => $r['hostname'], "dhcp4_subnet_id"=> $s_id, "subnet" => $s['subnet'] - ); + ]; // options if(isset($r['options'])) { - $this->reservations4[$m]['options'] = array(); + $this->reservations4[$m]['options'] = []; foreach ($r['options'] as $o) { $this->reservations4[$m]['options'][$o['name']] = $o['data']; } } // classes if(isset($r['client-classes'])) { - $this->reservations4[$m]['classes'] = array(); + $this->reservations4[$m]['classes'] = []; foreach ($r['client-classes'] as $c) { $this->reservations4[$m]['classes'][] = $c; } @@ -591,7 +591,7 @@ private function get_reservations_mysql ($reservations_database, $type) { // save leases if (sizeof($reservations)>0) { // we need array - $result = array(); + $result = []; // loop foreach ($reservations as $k=>$l) { // check for subnet @@ -632,7 +632,7 @@ private function get_reservations_mysql ($reservations_database, $type) { public function read_statistics () { $sock = stream_socket_client('unix:///var/lib/kea/socket', $errno, $errstr); - $cmd = array("command"=>"list-commands"); + $cmd = ["command"=>"list-commands"]; fwrite($sock, json_encode($cmd)."\r\n"); diff --git a/functions/classes/class.DHCP.php b/functions/classes/class.DHCP.php index bd1f6f3b6..27caad6d3 100644 --- a/functions/classes/class.DHCP.php +++ b/functions/classes/class.DHCP.php @@ -29,7 +29,7 @@ class DHCP extends Common_functions { * @var array * @access private */ - private $dhcp_server_types = array("kea"); + private $dhcp_server_types = ["kea"]; /** * Selected DHCP server from $dhcp_server_types to use with phpipam. @@ -51,7 +51,7 @@ class DHCP extends Common_functions { * @var array * @access private */ - private $dhcp_settings = array(); + private $dhcp_settings = []; /** * DHCP_server holder class @@ -79,7 +79,7 @@ class DHCP extends Common_functions { * @param array $dhcp_settings (default: array()) * @return void */ - public function __construct($server_type, $dhcp_settings = array()) { + public function __construct($server_type, $dhcp_settings = []) { // init Result class $this->Result = new Result (); @@ -125,11 +125,11 @@ private function init_dhcp_server_class () { * @return void */ private function verify_class_file () { - if(!file_exists(dirname(__FILE__)."/class.DHCP.".$this->dhcp_selected_type.".php")) { + if(!file_exists(__DIR__ . "/class.DHCP.".$this->dhcp_selected_type.".php")) { $this->Result->show("danger", _("Missing class file")." /functions/classes/class.DHCP.".$this->dhcp_selected_type.".php", true); } else { - include(dirname(__FILE__)."/class.DHCP.".$this->dhcp_selected_type.".php"); + require __DIR__ . "/class.DHCP.".$this->dhcp_selected_type.".php"; } } diff --git a/functions/classes/class.DNS.php b/functions/classes/class.DNS.php index 18bc275be..ee88a1d23 100644 --- a/functions/classes/class.DNS.php +++ b/functions/classes/class.DNS.php @@ -51,14 +51,14 @@ class DNS extends Common_functions { * * @var array */ - public $ns = array(); + public $ns = []; /** * Array of dead NS * * @var array */ - public $dead_ns = array(); + public $dead_ns = []; /** * Print error if DNS is not accessible @@ -150,7 +150,7 @@ private function set_nameservers ($nsid = null) { } else { // to array - $nsarray = pf_explode(";", $nameservers->namesrv1); + $nsarray = explode(";", (string) $nameservers->namesrv1); // check against dead NSes foreach ($nsarray as $k=>$nsserv) { $nsserv = trim($nsserv); @@ -163,7 +163,7 @@ private function set_nameservers ($nsid = null) { $this->ns = $nsarray; } else { - $this->ns = array(); + $this->ns = []; return false; } } @@ -190,13 +190,13 @@ public function resolve_address ($address = false, $hostname = false, $override // if both are set ignore if (!is_blank($hostname) && !is_blank($address)) { - { return array("class"=>"", "address"=>$address, "name"=>$hostname); } + { return ["class"=>"", "address"=>$address, "name"=>$hostname]; } } // if settings permits to check or override is set elseif($this->settings->enableDNSresolving == 1 || $override===true) { // ignore if remote DNS failed if ($this->dns_type=="remote" && sizeof($this->ns)==0) { - return array("class"=>"", "address"=>$address, "name"=>$hostname); + return ["class"=>"", "address"=>$address, "name"=>$hostname]; } // if address is set fetch A record elseif ($address!==false && !is_blank($address)) { @@ -206,8 +206,8 @@ public function resolve_address ($address = false, $hostname = false, $override // resolve $resolved = $this->resolve_address_net_dns ($address); // false ? - if ($resolved===false) { return array("class"=>"", "address"=>$address, "name"=>$hostname); } - else { return array("class"=>"resolved", "address"=>$address, "name"=>$resolved); } + if ($resolved===false) { return ["class"=>"", "address"=>$address, "name"=>$hostname]; } + else { return ["class"=>"resolved", "address"=>$address, "name"=>$resolved]; } } // if hostname is set fetch PTR record elseif($hostname!==false && !is_blank($hostname)) { @@ -217,12 +217,12 @@ public function resolve_address ($address = false, $hostname = false, $override // resolve $resolved = $this->resolve_address_net_dns ($hostname); // false ? - if ($resolved===false) { return array("class"=>"", "address"=>$address, "name"=>$hostname); } - else { return array("class"=>"resolved", "address"=>$resolved, "name"=>$hostname); } + if ($resolved===false) { return ["class"=>"", "address"=>$address, "name"=>$hostname]; } + else { return ["class"=>"resolved", "address"=>$resolved, "name"=>$hostname]; } } } // don't check - else { return array("class"=>"", "address"=>$address, "name"=>$hostname); } + else { return ["class"=>"", "address"=>$address, "name"=>$hostname]; } } /** @@ -238,7 +238,7 @@ public function resolve_address_net_dns ($address) { // check each , if dead remove it ! foreach ($this->ns as $ns) { if (!in_array($ns, $this->dead_ns)) { - $this->DNS2->setServers (array($ns)); + $this->DNS2->setServers ([$ns]); // try to get record try { diff --git a/functions/classes/class.FirewallZones.php b/functions/classes/class.FirewallZones.php index 2e9be5bac..e8bb2c626 100644 --- a/functions/classes/class.FirewallZones.php +++ b/functions/classes/class.FirewallZones.php @@ -276,7 +276,7 @@ public function get_zone_mappings () { if($mappings[$key]->padding == 1 && $mappings[$key]->generator != 2){ # remove leading zeros (padding) and raise the value in case of any zone name length changes # add some padding to reach the maximum zone name length - $mappings[$key]->zone = str_pad(ltrim($mappings[$key]->zone,0),$mappings[$key]->length,"0",STR_PAD_LEFT); + $mappings[$key]->zone = str_pad(ltrim((string) $mappings[$key]->zone,0),$mappings[$key]->length,"0",STR_PAD_LEFT); } # inject network informations foreach ($networkInformation as $nkey => $nval) { @@ -350,7 +350,7 @@ public function get_zone_mapping ($id) { if($mapping[$key]->padding == 1 && $mapping[$key]->generator != 2){ # remove leading zeros (padding) and raise the value in case of any zone name length changes # add some padding to reach the maximum zone name length - $mapping[$key]->zone = str_pad(ltrim($mapping[$key]->zone,0),$mapping[$key]->length,"0",STR_PAD_LEFT); + $mapping[$key]->zone = str_pad(ltrim((string) $mapping[$key]->zone,0),$mapping[$key]->length,"0",STR_PAD_LEFT); } # inject network informations foreach ($networkInformation as $nkey => $nval) { @@ -428,7 +428,7 @@ public function get_zone_subnet_info ($id) { if($info[$key]->padding == 1 && $info[$key]->generator != 2){ # remove leading zeros (padding) and raise the value in case of any zone name length changes # add some padding to reach the maximum zone name length - $info[$key]->zone = str_pad(ltrim($info[$key]->zone,0),$info[$key]->length,"0",STR_PAD_LEFT); + $info[$key]->zone = str_pad(ltrim((string) $info[$key]->zone,0),$info[$key]->length,"0",STR_PAD_LEFT); } } } @@ -479,7 +479,7 @@ public function get_zones () { if($zones[$key]->padding == 1 && $zones[$key]->generator != 2){ # remove leading zeros (padding) and raise the value in case of any zone name length changes # add some padding to reach the maximum zone name length - $zones[$key]->zone = str_pad(ltrim($zones[$key]->zone,0),$zones[$key]->length,"0",STR_PAD_LEFT); + $zones[$key]->zone = str_pad(ltrim((string) $zones[$key]->zone,0),$zones[$key]->length,"0",STR_PAD_LEFT); } # inject network informations foreach ($networkInformation as $nkey => $nval) { @@ -539,7 +539,7 @@ public function get_zone ($id) { if($zone[$key]->padding == 1 && $zone[$key]->generator != 2){ # remove leading zeros (padding) and raise the value in case of any zone name length changes # add some padding to reach the maximum zone name length - $zone[$key]->zone = str_pad(ltrim($zone[$key]->zone,0),$zone[$key]->length,"0",STR_PAD_LEFT); + $zone[$key]->zone = str_pad(ltrim((string) $zone[$key]->zone,0),$zone[$key]->length,"0",STR_PAD_LEFT); } # inject network informations foreach ($networkInformation as $nkey => $nval) { @@ -705,7 +705,7 @@ public function add_zone_network ($zoneId,$subnetId) { catch (Exception $e) {$this->Result->show("danger", _("Database error: ").$e->getMessage());} if(!sizeof($networkInformation)>0 ) { - $params = array('zoneId' => $zoneId, 'subnetId' => $subnetId); + $params = ['zoneId' => $zoneId, 'subnetId' => $subnetId]; # try to fetch all subnet and vlan informations for this zone try { $this->Database->insertObject("firewallZoneSubnet", $params);} @@ -807,7 +807,7 @@ private function zone_add ($values,$network) { if ($network) { foreach ($network as $subnetId) { - $values = array('zoneId' => $lastId[0]->id, 'subnetId' => $subnetId); + $values = ['zoneId' => $lastId[0]->id, 'subnetId' => $subnetId]; # add the network bindings if there are any try { $this->Database->insertObject("firewallZoneSubnet", $values); } catch (Exception $e) { @@ -1011,10 +1011,10 @@ public function generate_subnet_object ($id) { if (filter_var($this->Subnets->transform_to_dotted($zone->subnet), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { $firewallAddressObject = $firewallAddressObject.$this->Subnets->transform_to_dotted($zone->subnet).'-'.$zone->mask; } elseif (filter_var($this->Subnets->transform_to_dotted($zone->subnet), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { - $firewallAddressObject = $firewallAddressObject.str_replace(':',$firewallZoneSettings['separator'],$this->Subnets->transform_to_dotted($zone->subnet)).'-'.$zone->mask; + $firewallAddressObject = $firewallAddressObject.str_replace(':',(string) $firewallZoneSettings['separator'],(string) $this->Subnets->transform_to_dotted($zone->subnet)).'-'.$zone->mask; } } elseif ($firewallZoneSettings['subnetPatternValues'][$firewallZoneSettings['subnetPattern']] == 'description' ) { - $firewallAddressObject = $firewallAddressObject.str_replace(' ',$firewallZoneSettings['separator'],strtolower($zone->subnetDescription)); + $firewallAddressObject = $firewallAddressObject.str_replace(' ',(string) $firewallZoneSettings['separator'],strtolower((string) $zone->subnetDescription)); } # get subnet information to compare against the changes @@ -1023,7 +1023,7 @@ public function generate_subnet_object ($id) { # compare both versions, if there is no difference, just do nothing if ($zone->firewallAddressObject != $firewallAddressObject ) { # update field in database - $values = array('id' => $id , 'firewallAddressObject' => $firewallAddressObject); + $values = ['id' => $id , 'firewallAddressObject' => $firewallAddressObject]; try { $this->Database->updateObject("subnets", $values, "id"); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); @@ -1078,7 +1078,7 @@ public function generate_address_object ($id,$dnsName) { } break; case 'patternHost': - $hostName = pf_explode('.', $dnsName); + $hostName = explode('.', (string) $dnsName); $firewallAddressObject = $firewallAddressObject.$hostName[0]; break; case 'patternFQDN': @@ -1133,7 +1133,7 @@ public function update_address_object ($subnetId,$IPId,$dnsName) { } break; case 'patternHost': - $hostName = pf_explode('.', $dnsName); + $hostName = explode('.', (string) $dnsName); $firewallAddressObject = $firewallAddressObject.$hostName[0]; break; case 'patternFQDN': @@ -1147,7 +1147,7 @@ public function update_address_object ($subnetId,$IPId,$dnsName) { if ($address_old->firewallAddressObject != $firewallAddressObject) { # update field in database - $values = array('id' => $IPId , 'subnetId' => $subnetId, 'firewallAddressObject' => $firewallAddressObject); + $values = ['id' => $IPId , 'subnetId' => $subnetId, 'firewallAddressObject' => $firewallAddressObject]; try { $this->Database->updateObject("ipaddresses", $values, "id", "subnetId"); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); @@ -1211,7 +1211,7 @@ public function update_address_objects ($subnetId) { } break; case 'patternHost': - $hostName = pf_explode('.', $ipaddress->hostname); + $hostName = explode('.', (string) $ipaddress->hostname); $firewallAddressObject = $firewallAddressObject.$hostName[0]; break; case 'patternFQDN': @@ -1225,7 +1225,7 @@ public function update_address_objects ($subnetId) { if ($address_old->firewallAddressObject != $firewallAddressObject) { # update field in database - $values = array('id' => $ipaddress->id , 'subnetId' => $subnetId, 'firewallAddressObject' => $firewallAddressObject); + $values = ['id' => $ipaddress->id , 'subnetId' => $subnetId, 'firewallAddressObject' => $firewallAddressObject]; try { $this->Database->updateObject("ipaddresses", $values, "id", "subnetId"); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); diff --git a/functions/classes/class.Install.php b/functions/classes/class.Install.php index 0339cb5ac..68485691e 100644 --- a/functions/classes/class.Install.php +++ b/functions/classes/class.Install.php @@ -143,10 +143,10 @@ private function create_database () { * @return void */ private function create_grants () { - $esc_user = addcslashes($this->db['user'],"'"); - $esc_pass = addcslashes($this->db['pass'],"'"); + $esc_user = addcslashes((string) $this->db['user'],"'"); + $esc_pass = addcslashes((string) $this->db['pass'],"'"); $db_name = $this->db['name']; - $webhost = is_string(@$this->db['webhost']) && !is_blank(@$this->db['webhost']) ? addcslashes($this->db['webhost'],"'") : 'localhost'; + $webhost = is_string(@$this->db['webhost']) && !is_blank(@$this->db['webhost']) ? addcslashes((string) $this->db['webhost'],"'") : 'localhost'; try { # Check if user exists; @@ -172,14 +172,14 @@ private function create_grants () { private function install_database_execute ($migrate = false) { # import SCHEMA file queries if($migrate) { - $query = file_get_contents("../../db/MIGRATE.sql"); + $query = file_get_contents(__DIR__ . '/../../db/MIGRATE.sql'); } else { - $query = file_get_contents("../../db/SCHEMA.sql"); + $query = file_get_contents(__DIR__ . '/../../db/SCHEMA.sql'); } # formulate queries - $queries = array_filter(pf_explode(";\n", $query)); + $queries = array_filter(explode(";\n", (string) $query)); # append version $queries[] = "UPDATE `settings` SET `version` = '".VERSION."'"; @@ -334,7 +334,7 @@ function postauth_update($adminpass, $siteTitle, $siteURL) { * @return void */ public function postauth_update_admin_pass ($adminpass) { - try { $this->Database->updateObject("users", array("password"=>$adminpass, "passChange"=>"No","username"=>"Admin"), "username"); } + try { $this->Database->updateObject("users", ["password"=>$adminpass, "passChange"=>"No","username"=>"Admin"], "username"); } catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); } return true; } @@ -348,7 +348,7 @@ public function postauth_update_admin_pass ($adminpass) { * @return void */ private function postauth_update_settings ($siteTitle, $siteURL) { - try { $this->Database->updateObject("settings", array("siteTitle"=>$siteTitle, "siteURL"=>$siteURL,"id"=>1), "id"); } + try { $this->Database->updateObject("settings", ["siteTitle"=>$siteTitle, "siteURL"=>$siteURL,"id"=>1], "id"); } catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); } return true; } @@ -419,7 +419,7 @@ private function get_old_version () { */ private function load_all_queries () { // include upgrade files - require (dirname(__FILE__)."/../upgrade_queries.php"); + require __DIR__ . '/../upgrade_queries.php'; // add queries foreach ($upgrade_queries as $version=>$query_arr) { foreach ($query_arr as $query) { @@ -508,7 +508,7 @@ private function upgrade_database_execute () { # set queries $queries = $this->get_queries (); // create default arrays - $queries_ok = array(); // succesful queries + $queries_ok = []; // succesful queries // execute try { @@ -518,8 +518,8 @@ private function upgrade_database_execute () { # execute all queries foreach($queries as $k=>$query) { // execute - if(strpos($query, "--")!==0 && !is_blank(trim((string) $query))) { - $ignore_on_failure = (strpos($query, '-- IGNORE_ON_FAILURE')!== false); + if(strpos((string) $query, "--")!==0 && !is_blank(trim((string) $query))) { + $ignore_on_failure = (strpos((string) $query, '-- IGNORE_ON_FAILURE')!== false); if ($ignore_on_failure) $this->Database->setErrMode(\PDO::ERRMODE_SILENT); $this->Database->runQuery($query); diff --git a/functions/classes/class.LockForUpdate.php b/functions/classes/class.LockForUpdate.php index e085319b1..fc90366e9 100644 --- a/functions/classes/class.LockForUpdate.php +++ b/functions/classes/class.LockForUpdate.php @@ -73,7 +73,7 @@ public function obtain_lock($timeout_seconds) { do { $locked = flock($this->locked_res, LOCK_EX | LOCK_NB); if (!$locked) { - usleep(rand(2000, 5000)); + usleep(random_int(2000, 5000)); } } while (!$locked && ((microtime(true) - $start_time) < $timeout)); @@ -88,6 +88,7 @@ public function obtain_lock($timeout_seconds) { * * @return void */ + #[\Override] public function release_lock() { if ($this->locked_res) { $res = $this->locked_res; @@ -195,6 +196,7 @@ public function obtain_lock($timeout_seconds) { * * @return void */ + #[\Override] public function release_lock() { $this->locked_res = false; $this->Database->commit(); diff --git a/functions/classes/class.Log.php b/functions/classes/class.Log.php index c7ab5eeaf..7e08c8f5e 100644 --- a/functions/classes/class.Log.php +++ b/functions/classes/class.Log.php @@ -162,8 +162,8 @@ class Logging extends Common_functions { * @var mixed * @access protected */ - public $changelog_keys = array( - "section" => array( + public $changelog_keys = [ + "section" => [ "id" => "index", "name" => "Subnet name", "description" => "Description", @@ -174,8 +174,8 @@ class Logging extends Common_functions { "showVLAN" => "Show VLANs in side menu", "showVRF" => "Show VRF in side menu", "showSupernetOnly" => "Show only supernets" - ), - "subnet" => array( + ], + "subnet" => [ "id" => "Subnet id", "subnet" => "Subnet", "masterSubnetId" => "Master subnet", @@ -203,15 +203,15 @@ class Logging extends Common_functions { "linked_subnet" => "Linked IPv6 subnet", "location" => "Subnet location", "lastScan" => "Last scan date" - ), - "folder" => array( + ], + "folder" => [ "id" => "Folder id", "masterSubnetId" => "Master folder index", "sectionId" => "Section index", "description" => "Description", "isFolder" => "Object is folder" - ), - "address" => array( + ], + "address" => [ "id" => "Address id", "subnetId" => "Subnet", "ip_addr" => "IP address", @@ -232,8 +232,8 @@ class Logging extends Common_functions { "firewallAddressObject" => "Firewall object index", "location" => "Address location", "section" => "Section" - ) - ); + ] + ]; /** * Addresses object @@ -359,7 +359,7 @@ private function get_active_user_id () { } } else { - try { $user_id = $this->Database->getObjectQuery("users", "select * from `users` where `username` = ? limit 1", array($_SESSION['ipamusername'])); } + try { $user_id = $this->Database->getObjectQuery("users", "select * from `users` where `username` = ? limit 1", [$_SESSION['ipamusername']]); } catch (Exception $e) { $this->Result->show("danger", _("Database error: ").$e->getMessage()); } } # save id @@ -467,8 +467,8 @@ private function syslog_set_facility () { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $facility = "LOG_USER"; } else { //login, logout - if (strpos($this->log_command, "login")>0 || - strpos($this->log_command, "logged out")>0) { $facility = "LOG_AUTH"; } + if (strpos((string) $this->log_command, "login")>0 || + strpos((string) $this->log_command, "logged out")>0) { $facility = "LOG_AUTH"; } else { $facility = "LOG_USER"; } } # save @@ -483,7 +483,7 @@ private function syslog_set_facility () { */ private function syslog_set_priority () { // init - $priorities = array(); + $priorities = []; # definitions $priorities[] = "LOG_EMERG"; $priorities[] = "LOG_ALERT"; @@ -509,8 +509,8 @@ private function syslog_set_priority () { */ private function syslog_format_details () { // replace
- $this->log_details = str_replace("
", ",",$this->log_details); - $this->log_details = str_replace("
", ",",$this->log_details); + $this->log_details = str_replace("
", ",",(string) $this->log_details); + $this->log_details = str_replace("
", ",",(string) $this->log_details); // replace spaces $this->log_details = trim($this->log_details, ","); } @@ -530,11 +530,11 @@ private function syslog_write_changelog ($changelog) { else { $obj_id = $this->object_old['id']; } # format - $changelog = str_replace("
", ",",$changelog); - $changelog = str_replace("
", ",",$changelog); + $changelog = str_replace("
", ",",(string) $changelog); + $changelog = str_replace("
", ",",(string) $changelog); # formulate - $log = array(); + $log = []; if(isset($changelog)) { if (is_array($changelog)) { foreach($changelog as $k=>$l) { @@ -573,14 +573,14 @@ private function syslog_write_changelog ($changelog) { */ private function database_write_log () { # set values - $values = array( + $values = [ "command" =>$this->log_command, "severity" =>$this->log_severity, "date" =>$this->Database->toDate(), "username" =>$this->log_username, "ipaddr" =>$this->get_user_ip(), "details" =>$this->log_details - ); + ]; # null empty values $values = $this->reformat_empty_array_fields($values, null); $values = $this->strip_input_tags($values); @@ -619,9 +619,9 @@ public function fetch_logs ($logCount, $direction = NULL, $lastId = NULL, $highe } # query - $query = array(); // query - $query_severities = array(); // severities - $params = array(); // sql bind parameters + $query = []; // query + $query_severities = []; // severities + $params = []; // sql bind parameters $query[] = "select * from ("; $query[] = "select * from logs "; @@ -702,7 +702,7 @@ public function log_fetch_highest_id () { * @param bool $mail_changelog (default: true) * @return boolean|null */ - public function write_changelog ($object_type, $action, $result, $old = array(), $new = array(), $mail_changelog = true) { + public function write_changelog ($object_type, $action, $result, $old = [], $new = [], $mail_changelog = true) { //set values $this->object_type = $object_type; $this->object_action = $action; @@ -729,7 +729,7 @@ public function write_changelog ($object_type, $action, $result, $old = array(), $this->get_settings (); # default log - $log = array(); + $log = []; // check if syslog globally enabled and write log if($this->settings->enableChangelog==1) { @@ -779,7 +779,7 @@ public function write_changelog ($object_type, $action, $result, $old = array(), if(is_array($log) && sizeof($log)>0) { // reformat null foreach ($log as $k=>$v) { - $log[$k] = str_replace(":
", ": /
", $v); + $log[$k] = str_replace(":
", ": /
", (string) $v); } // execute if ($this->log_type == "syslog") { $this->syslog_write_changelog ($log); } @@ -802,7 +802,7 @@ public function write_changelog ($object_type, $action, $result, $old = array(), */ private function changelog_write_to_db ($changelog) { # log to array - $changelog = str_replace("
", "\r\n", $this->array_to_log ($changelog, true)); + $changelog = str_replace("
", "\r\n", (string) $this->array_to_log ($changelog, true)); # fetch user id $this->get_active_user_id (); @@ -825,7 +825,7 @@ private function changelog_write_to_db ($changelog) { if(is_null($obj_id) || $obj_id=="NULL") { return false; } # set values - $values = array( + $values = [ "ctype" => $object_type, "coid" => $obj_id, "cuser" => $this->user_id, @@ -833,7 +833,7 @@ private function changelog_write_to_db ($changelog) { "cresult"=> $this->object_result, "cdate" => date("Y-m-d H:i:s"), "cdiff" => $changelog - ); + ]; # null empty values $values = $this->reformat_empty_array_fields ($values, null); @@ -859,12 +859,12 @@ private function changelog_write_to_db ($changelog) { */ private function changelog_validate_object () { # set valid objects - $objects = array( + $objects = [ "ip_addr", "subnet", "folder", "section" - ); + ]; # check return in_array($this->object_type, $objects) ? true : false; } @@ -1406,23 +1406,23 @@ private function changelog_format_master_section_diff ($k, $v) { private function changelog_format_permission_diff ($k, $v) { // get old and compare if (isset($this->object_new['permissions'])) { - $this->object_new['permissions'] = db_json_decode(str_replace("\\", "", $this->object_new['permissions']), true); //Remove / + $this->object_new['permissions'] = db_json_decode(str_replace("\\", "", (string) $this->object_new['permissions']), true); //Remove / } if (isset($this->object_old['permissions'])) { - $this->object_old['permissions'] = db_json_decode(str_replace("\\", "", $this->object_old['permissions']), true); //Remove / + $this->object_old['permissions'] = db_json_decode(str_replace("\\", "", (string) $this->object_old['permissions']), true); //Remove / } # Get all groups: $groups = (array) $this->Tools->fetch_all_objects("userGroups", "g_id"); // rekey - $out = array(); + $out = []; foreach($groups as $g) { $out[$g->g_id]['g_name'] = $g->g_name; } $groups = $out; // loop - $val = array(); + $val = []; if(is_array($this->object_new['permissions'])) { foreach($this->object_new['permissions'] as $group_id=>$p) { $val[] = $groups[$group_id]['g_name'] ." : ".$this->Subnets->parse_permissions($p); @@ -1444,14 +1444,14 @@ private function changelog_format_permission_diff ($k, $v) { */ private function changelog_make_booleans ($k, $v) { // init - $keys = array(); + $keys = []; // list of keys to be changed per object - $keys['section'] = array("strictMode", "showVLAN", "showVRF", "showSupernetOnly"); - $keys['subnet'] = array("allowRequests", "showName", "pingSubnet", "discoverSubnet", "resolveDNS", "DNSrecursive", "DNSrecords", "isFull", "isPool"); - $keys['ip_addr'] = array("is_gateway", "excludePing", "PTRignore"); + $keys['section'] = ["strictMode", "showVLAN", "showVRF", "showSupernetOnly"]; + $keys['subnet'] = ["allowRequests", "showName", "pingSubnet", "discoverSubnet", "resolveDNS", "DNSrecursive", "DNSrecords", "isFull", "isPool"]; + $keys['ip_addr'] = ["is_gateway", "excludePing", "PTRignore"]; // check - if (array_key_exists($this->object_type, $keys)) { + if (array_key_exists((string) $this->object_type, $keys)) { if (in_array($k, $keys[$this->object_type])) { if ($v=="0") { $this->object_old[$k] = "True"; return "False"; } else { $this->object_old[$k] = "False"; return "True"; } @@ -1473,13 +1473,13 @@ private function changelog_make_booleans ($k, $v) { */ private function changelog_format_permission_change () { # get old and compare - $this->object_new['permissions_change'] = db_json_decode(str_replace("\\", "", $this->object_new['permissions_change']), true); //Remove / + $this->object_new['permissions_change'] = db_json_decode(str_replace("\\", "", (string) $this->object_new['permissions_change']), true); //Remove / # Get all groups: $groups = (array) $this->Tools->fetch_all_objects("userGroups", "g_id"); // rekey - $out = array(); - $log = array(); + $out = []; + $log = []; foreach($groups as $k=>$g) { // save @@ -1515,9 +1515,9 @@ public function fetch_all_changelogs ($filter, $expr, $limit = 100) { $subquery_filter1 = ""; $subquery_filter2 =""; if($filter) { /* replace * with % */ - if(substr($expr, 0, 1)=="*") { $expr[0] = "%"; } - if(substr($expr, -1, 1)=="*") { $expr = substr_replace($expr, "%", -1); } - if(substr($expr, 0, 1)!="*" && substr($expr, -1, 1)!="*") { $expr = "%".$expr."%"; } + if(substr((string) $expr, 0, 1)=="*") { $expr[0] = "%"; } + if(substr((string) $expr, -1, 1)=="*") { $expr = substr_replace($expr, "%", -1); } + if(substr((string) $expr, 0, 1)!="*" && substr((string) $expr, -1, 1)!="*") { $expr = "%".$expr."%"; } $subquery_filter1 = "AND (`coid`=:expr or `ctype`=:expr or `real_name` like :expr or `cdate` like :expr or `cdiff` like :expr or INET_NTOA(`ip_addr`) like :expr)"; $subquery_filter2 = "AND (`coid`=:expr or `ctype`=:expr or `real_name` like :expr or `cdate` like :expr or `cdiff` like :expr)"; @@ -1556,7 +1556,7 @@ public function fetch_all_changelogs ($filter, $expr, $limit = 100) { ) as `ips` order by `cid` desc limit $limit;"; # fetch - try { $logs = $this->Database->getObjectsQuery('changelog', $query, $filter ? array("expr"=>$expr) : null); } + try { $logs = $this->Database->getObjectsQuery('changelog', $query, $filter ? ["expr"=>$expr] : null); } catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; } # return results @@ -1600,7 +1600,7 @@ public function fetch_changelog ($id) { where `changelog`.`ctype` = 'section' and `changelog`.`cid` = :id ) as `ips` order by `cid` desc limit 1;"; # fetch - try { $logs = $this->Database->getObjectQuery('changelog', $query, array("id"=>$id)); } + try { $logs = $this->Database->getObjectQuery('changelog', $query, ["id"=>$id]); } catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; @@ -1620,7 +1620,7 @@ public function fetch_changelog ($id) { */ public function fetch_subnet_addresses_changelog_recursive ($subnetId, $limit = 50) { # get all addresses ids - $ips = array(); + $ips = []; if (!is_object($this->Addresses)) $this->Addresses = new Addresses ($this->Database); $ips = $this->Addresses->fetch_subnet_addresses_recursive ($subnetId, false); @@ -1634,7 +1634,7 @@ public function fetch_subnet_addresses_changelog_recursive ($subnetId, $limit = where `c`.`cuser` = `u`.`id` and `c`.`coid`=`o`.`id` and ("; - $args = array(); + $args = []; foreach($ips as $ip) { $query .= "`c`.`coid` = ? or "; $args[] = $ip->id; @@ -1699,7 +1699,7 @@ public function fetch_changlog_entries ($object_type, $coid, $long = false, $lim and `c`.`coid` = ? and `c`.`ctype` = ? order by `c`.`cid` desc limit $limit;"; } # fetch - try { $logs = $this->Database->getObjectsQuery('changelog', $query, array($coid, $object_type)); } + try { $logs = $this->Database->getObjectsQuery('changelog', $query, [$coid, $object_type]); } catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), false); return false; } # return result @@ -1738,7 +1738,7 @@ public function fetch_subnet_slaves_changlog_entries_recursive($subnetId, $limit where `c`.`cuser` = `u`.`id` and `c`.`coid`=`o`.`id` and ("; foreach($this->Subnets->slaves as $slaveId) { - if(!isset($args)) $args = array(); + if(!isset($args)) $args = []; $query .= "`c`.`coid` = ? or "; $args[] = $slaveId; //set keys } @@ -1791,8 +1791,8 @@ public function changelog_send_mail ($changelog) { $obj_details = array_merge(['id' => null, 'name' => null, 'description' => null, 'subnet' => null, 'ip_addr' => null, 'mask' => null, 'hostname' => null], (array) $obj_details); # change ip_addr - $this->object_type = str_replace("ip_addr", "address", $this->object_type); - $this->object_type = str_replace("ip_range", "address range", $this->object_type); + $this->object_type = str_replace("ip_addr", "address", (string) $this->object_type); + $this->object_type = str_replace("ip_range", "address range", (string) $this->object_type); # folder if ((isset($this->object_new['isFolder']) && $this->object_new['isFolder'] == "1") || @@ -1807,7 +1807,7 @@ public function changelog_send_mail ($changelog) { elseif($this->object_action == "delete"){ $subject = ucwords($this->object_type)." delete notification"; } // if address we need subnet details ! - $address_subnet = array(); + $address_subnet = []; if ($this->object_type=="address") { $address_subnet = (array) $this->Tools->fetch_object("subnets", "id", $this->object_orig['subnetId']); } # set object details @@ -1824,7 +1824,7 @@ public function changelog_send_mail ($changelog) { } # set content - $content = array(); + $content = []; $content[] = "
"; $content[] = "
"; - $html[] = "$n->name ".ucwords($n->type).""; + $html[] = "$n->name ".ucwords((string) $n->type).""; $html[] = "
"; $content[] = ""; @@ -1839,7 +1839,7 @@ public function changelog_send_mail ($changelog) { $content[] = "'. "\n"; print ' '. "\n"; diff --git a/app/admin/authentication-methods/check-connection.php b/public/app/admin/authentication-methods/check-connection.php similarity index 84% rename from app/admin/authentication-methods/check-connection.php rename to public/app/admin/authentication-methods/check-connection.php index b0858901b..eaf5e06a5 100644 --- a/app/admin/authentication-methods/check-connection.php +++ b/public/app/admin/authentication-methods/check-connection.php @@ -4,10 +4,8 @@ * Check connection * */ - - -/* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; +require_once __DIR__ . '/../../../../functions/adLDAP/src/adLDAP.php'; # initialize user object $Database = new Database_PDO; @@ -28,23 +26,21 @@ # AD? if($auth_settings->type=="AD" || $auth_settings->type=="LDAP" || $auth_settings->type=="NetIQ") { - # adLDAP function - include (dirname(__FILE__) . "/../../../functions/adLDAP/src/adLDAP.php"); # set controllers - $controllers = pf_explode(";", str_replace(" ", "", $parameters->domain_controllers)); + $controllers = explode(";", str_replace(" ", "", (string) $parameters->domain_controllers)); //open connection try { if($auth_settings->type == "NetIQ") { $params->account_suffix = ""; } //set options - $options = array( + $options = [ 'base_dn' =>$parameters->base_dn, 'account_suffix' =>$parameters->account_suffix, 'domain_controllers' =>$controllers, 'use_ssl' =>$parameters->use_ssl, 'use_tls' =>$parameters->use_tls, 'ad_port' =>$parameters->ad_port - ); + ]; $adldap = new adLDAP($options); //LDAP? if($auth_settings->type=="LDAP") $adldap->setUseOpenLDAP(true); diff --git a/app/admin/authentication-methods/edit-AD.php b/public/app/admin/authentication-methods/edit-AD.php similarity index 100% rename from app/admin/authentication-methods/edit-AD.php rename to public/app/admin/authentication-methods/edit-AD.php diff --git a/app/admin/authentication-methods/edit-LDAP.php b/public/app/admin/authentication-methods/edit-LDAP.php similarity index 100% rename from app/admin/authentication-methods/edit-LDAP.php rename to public/app/admin/authentication-methods/edit-LDAP.php diff --git a/app/admin/authentication-methods/edit-NetIQ.php b/public/app/admin/authentication-methods/edit-NetIQ.php similarity index 100% rename from app/admin/authentication-methods/edit-NetIQ.php rename to public/app/admin/authentication-methods/edit-NetIQ.php diff --git a/app/admin/authentication-methods/edit-Radius.php b/public/app/admin/authentication-methods/edit-Radius.php similarity index 96% rename from app/admin/authentication-methods/edit-Radius.php rename to public/app/admin/authentication-methods/edit-Radius.php index b320f9d38..a3c2a2d9c 100644 --- a/app/admin/authentication-methods/edit-Radius.php +++ b/public/app/admin/authentication-methods/edit-Radius.php @@ -130,7 +130,7 @@ "; print " "; diff --git a/app/admin/circuits/edit-circuit-submit.php b/public/app/admin/circuits/edit-circuit-submit.php similarity index 88% rename from app/admin/circuits/edit-circuit-submit.php rename to public/app/admin/circuits/edit-circuit-submit.php index 288821ade..8a0fedb93 100644 --- a/app/admin/circuits/edit-circuit-submit.php +++ b/public/app/admin/circuits/edit-circuit-submit.php @@ -5,7 +5,7 @@ ***************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -50,7 +50,7 @@ if(!in_array($POST->type, $type_id_array)) { $Result->show("danger", _('Invalid type').'!', true); } # status -$statuses = array ("Active", "Inactive", "Reserved"); +$statuses = ["Active", "Inactive", "Reserved"]; if(!in_array($POST->status, $statuses)) { $Result->show("danger", _('Invalid status').'!', true); } #Check if circuit is part of a larger circuit @@ -67,15 +67,15 @@ $POST->device1 = 0; $POST->location1 = 0; } -elseif(strpos($POST->device1,"device_")!==false) { - $deviceId = str_replace("device_", "", $POST->device1); +elseif(strpos((string) $POST->device1,"device_")!==false) { + $deviceId = str_replace("device_", "", (string) $POST->device1); if($Tools->fetch_object("devices","id",$deviceId)===false) { $Result->show("danger", _('Invalid device A').'!', true); } // save $POST->device1 = $deviceId; $POST->location1 = 0; } else { - $locationId = str_replace("location_", "", $POST->device1); + $locationId = str_replace("location_", "", (string) $POST->device1); if($Tools->fetch_object("locations","id",$locationId)===false) { $Result->show("danger", _('Invalid location A').'!', true); } // save $POST->device1 = 0; @@ -86,15 +86,15 @@ $POST->device2 = 0; $POST->location2 = 0; } -elseif(strpos($POST->device2,"device_")!==false) { - $deviceId = str_replace("device_", "", $POST->device2); +elseif(strpos((string) $POST->device2,"device_")!==false) { + $deviceId = str_replace("device_", "", (string) $POST->device2); if($Tools->fetch_object("devices","id",$deviceId)===false) { $Result->show("danger", _('Invalid device B').'!', true); } // save $POST->device2 = $deviceId; $POST->location2 = 0; } else { - $locationId = str_replace("location_", "", $POST->device2); + $locationId = str_replace("location_", "", (string) $POST->device2); if($Tools->fetch_object("locations","id",$locationId)===false) { $Result->show("danger", _('Invalid location B').'!', true); } // save $POST->device2 = 0; @@ -102,7 +102,7 @@ } # set update values -$values = array( +$values = [ "id" => $POST->id, "cid" => $POST->cid, "provider" => $POST->provider, @@ -114,7 +114,7 @@ "device2" => $POST->device2, "location2" => $POST->location2, "comment" => $POST->comment - ); + ]; # fetch custom fields $update = $Tools->update_POST_custom_fields('circuits', $POST->action, $POST); diff --git a/app/admin/circuits/edit-circuit.php b/public/app/admin/circuits/edit-circuit.php similarity index 98% rename from app/admin/circuits/edit-circuit.php rename to public/app/admin/circuits/edit-circuit.php index fe982e3a5..002250495 100644 --- a/app/admin/circuits/edit-circuit.php +++ b/public/app/admin/circuits/edit-circuit.php @@ -5,7 +5,7 @@ ************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -144,7 +144,7 @@ "; # select print " "; //title print " "; print " "; print " "; @@ -106,7 +106,7 @@ foreach($cf as $f) { # space? - $class = strpos($f['name'], " ")===false ? "" : "danger"; + $class = strpos((string) $f['name'], " ")===false ? "" : "danger"; print ""; @@ -142,7 +142,7 @@ print " "; # warning for older versions - if((is_numeric(substr($f['name'], 0, 1))) || (!preg_match('/^(\p{L}|\p{N})[(\p{L}|\p{N}) _.-]+$/u', $f['name'])) ) { print 'Warning: '._('Invalid field name').'!'; } + if((is_numeric(substr((string) $f['name'], 0, 1))) || (!preg_match('/^(\p{L}|\p{N})[(\p{L}|\p{N}) _.-]+$/u', (string) $f['name'])) ) { print 'Warning: '._('Invalid field name').'!'; } print ""; print ""; @@ -155,7 +155,7 @@ //add print ""; print ""; print ""; diff --git a/app/admin/custom-fields/order.php b/public/app/admin/custom-fields/order.php similarity index 91% rename from app/admin/custom-fields/order.php rename to public/app/admin/custom-fields/order.php index ae9ee3d1c..e0c7efb2d 100755 --- a/app/admin/custom-fields/order.php +++ b/public/app/admin/custom-fields/order.php @@ -6,7 +6,7 @@ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; diff --git a/app/admin/customers/edit-submit.php b/public/app/admin/customers/edit-submit.php similarity index 84% rename from app/admin/customers/edit-submit.php rename to public/app/admin/customers/edit-submit.php index d43d81f4e..06f316320 100644 --- a/app/admin/customers/edit-submit.php +++ b/public/app/admin/customers/edit-submit.php @@ -5,7 +5,7 @@ ***************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; // initialize user object $Database = new Database_PDO; @@ -43,10 +43,10 @@ // add / edit validations if ($POST->action!="delete") { // check strings - if(strlen($POST->title)<3) { $Result->show("danger", _("Invalid Title"), true); } - if(strlen($POST->address)<3) { $Result->show("danger", _("Invalid Address"), true); } - if(strlen($POST->city)<3) { $Result->show("danger", _("Invalid City"), true); } - if(strlen($POST->state)<3) { $Result->show("danger", _("Invalid State"), true); } + if(strlen((string) $POST->title)<3) { $Result->show("danger", _("Invalid Title"), true); } + if(strlen((string) $POST->address)<3) { $Result->show("danger", _("Invalid Address"), true); } + if(strlen((string) $POST->city)<3) { $Result->show("danger", _("Invalid City"), true); } + if(strlen((string) $POST->state)<3) { $Result->show("danger", _("Invalid State"), true); } // validate postcode if(!$Tools->validate_postcode ($POST->postcode, $POST->state)) { $Result->show("danger", _("Invalid Postcode"), true); } } @@ -56,7 +56,7 @@ */ // set update values -$values = array( +$values = [ "id" => $POST->id, "title" => $POST->title, "address" => $POST->address, @@ -67,7 +67,7 @@ "contact_phone" => $POST->contact_phone, "contact_mail" => $POST->contact_mail, "note" => $POST->note - ); + ]; // fetch custom fields $update = $Tools->update_POST_custom_fields('customers', $POST->action, $POST); diff --git a/app/admin/customers/edit.php b/public/app/admin/customers/edit.php similarity index 97% rename from app/admin/customers/edit.php rename to public/app/admin/customers/edit.php index a8dbd2c2c..f647a0719 100644 --- a/app/admin/customers/edit.php +++ b/public/app/admin/customers/edit.php @@ -5,7 +5,7 @@ *************************************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -41,7 +41,7 @@ # null ? $customer===false ? $Result->show("danger", _("Invalid ID"), true) : null; # title - $title = ucwords($POST->action) .' '._('customer').' '.$customer->title; + $title = ucwords((string) $POST->action) .' '._('customer').' '.$customer->title; } else { # generate new code $customer = new Params (); diff --git a/app/admin/customers/index.php b/public/app/admin/customers/index.php similarity index 67% rename from app/admin/customers/index.php rename to public/app/admin/customers/index.php index c906be361..a1c6fd841 100644 --- a/app/admin/customers/index.php +++ b/public/app/admin/customers/index.php @@ -15,8 +15,8 @@ # load subpage if (!isset($GET->subnetId)) { - include(dirname(__FILE__).'/../../tools/customers/all-customers.php'); + include(__DIR__.'/../../tools/customers/all-customers.php'); } else { - include(dirname(__FILE__).'/../../tools/customers/customer/index.php'); + include(__DIR__.'/../../tools/customers/customer/index.php'); } diff --git a/app/admin/customers/unlink.php b/public/app/admin/customers/unlink.php similarity index 87% rename from app/admin/customers/unlink.php rename to public/app/admin/customers/unlink.php index a63c0a78e..347a86a09 100644 --- a/app/admin/customers/unlink.php +++ b/public/app/admin/customers/unlink.php @@ -5,7 +5,7 @@ ***************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; // initialize user object $Database = new Database_PDO; @@ -22,7 +22,7 @@ $User->check_maintaneance_mode (); // make sure correct object is applied -if(!array_key_exists($POST->object, $Tools->get_customer_object_types())) { +if(!array_key_exists((string) $POST->object, $Tools->get_customer_object_types())) { $Result->show ("danger", _("Invalid object"), true, true); } // ID must be numeric diff --git a/app/admin/device-types/edit-result.php b/public/app/admin/device-types/edit-result.php similarity index 84% rename from app/admin/device-types/edit-result.php rename to public/app/admin/device-types/edit-result.php index 3a6e0d188..889b28df6 100755 --- a/app/admin/device-types/edit-result.php +++ b/public/app/admin/device-types/edit-result.php @@ -5,7 +5,7 @@ ***************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -35,17 +35,17 @@ # checks if($POST->action!="delete") { - if(strlen($POST->bgcolor)<4) { $Result->show("danger", _("Invalid bg color"), true); } - if(strlen($POST->fgcolor)<4) { $Result->show("danger", _("Invalid fg color"), true); } + if(strlen((string) $POST->bgcolor)<4) { $Result->show("danger", _("Invalid bg color"), true); } + if(strlen((string) $POST->fgcolor)<4) { $Result->show("danger", _("Invalid fg color"), true); } } # create array of values for modification -$values = array("tid"=>$POST->tid, +$values = ["tid"=>$POST->tid, "tname"=>$POST->tname, "tdescription"=>$POST->tdescription, "bgcolor"=>$POST->bgcolor, "fgcolor"=>$POST->fgcolor, - ); + ]; # update if(!$Admin->object_modify("deviceTypes", $POST->action, "tid", $values)) { diff --git a/app/admin/device-types/edit.php b/public/app/admin/device-types/edit.php similarity index 97% rename from app/admin/device-types/edit.php rename to public/app/admin/device-types/edit.php index 632cc0a03..d0d13f485 100755 --- a/app/admin/device-types/edit.php +++ b/public/app/admin/device-types/edit.php @@ -5,7 +5,7 @@ ************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -34,10 +34,10 @@ $readonly = $POST->action=="delete" ? "readonly" : ""; # set default values if($POST->action=="add") { - $device = (object) array( + $device = (object) [ "bgcolor"=>"#E6E6E6", "fgcolor"=>"#000", - ); + ]; } # fetch device type details diff --git a/app/admin/device-types/index.php b/public/app/admin/device-types/index.php similarity index 94% rename from app/admin/device-types/index.php rename to public/app/admin/device-types/index.php index 9334761f7..4bf786010 100755 --- a/app/admin/device-types/index.php +++ b/public/app/admin/device-types/index.php @@ -49,8 +49,8 @@ //print details print ''. "\n"; - print ' '. "\n"; - print ' '. "\n"; + print ' '. "\n"; + print ' '. "\n"; print ' '. "\n"; print ' '. "\n"; diff --git a/app/admin/devices/edit-rack-dropdown.php b/public/app/admin/devices/edit-rack-dropdown.php similarity index 85% rename from app/admin/devices/edit-rack-dropdown.php rename to public/app/admin/devices/edit-rack-dropdown.php index ff3f3567c..767478b10 100644 --- a/app/admin/devices/edit-rack-dropdown.php +++ b/public/app/admin/devices/edit-rack-dropdown.php @@ -1,6 +1,16 @@ check_user_session(); # perm check popup @@ -22,16 +32,7 @@ # show only for numeric (set) rackid if($POST->rackid>0 || @$device['rack']>0) { # load objects for ajax-loaded stuff - if(!isset($User) || !is_object($User)) { - # initialize user object - $Database = new Database_PDO; - $User = new User ($Database); - $Racks = new phpipam_rack ($Database); - $Result = new Result (); - - # verify that user is logged in - $User->check_user_session(); - + if($ajax_loaded) { # validate in inputs if(!is_numeric($POST->rackid)) { print ""; die(); } # fetch rack @@ -66,6 +67,23 @@ // available spaces list($available, $available_back) = $Racks->free_u($rack, $rack_devices, $rack_contents, $device); ?> + diff --git a/app/admin/devices/edit-result.php b/public/app/admin/devices/edit-result.php similarity index 95% rename from app/admin/devices/edit-result.php rename to public/app/admin/devices/edit-result.php index 8e3ecd2f4..923f5a1c6 100755 --- a/app/admin/devices/edit-result.php +++ b/public/app/admin/devices/edit-result.php @@ -5,7 +5,7 @@ ***************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -35,8 +35,8 @@ # available devices set foreach($POST as $key=>$line) { - if (!is_blank(strstr($key,"section-"))) { - $key2 = str_replace("section-", "", $key); + if (!is_blank(strstr((string) $key,"section-"))) { + $key2 = str_replace("section-", "", (string) $key); $temp[] = $key2; unset($POST->{$key}); @@ -76,7 +76,7 @@ } # set update values -$values = array( +$values = [ "id" =>$POST->switchid, "hostname" =>$POST->hostname, "ip_addr" =>$POST->ip_addr, @@ -84,7 +84,7 @@ "description" =>$POST->description, "sections" =>$POST->sections, "location" =>$POST->location - ); + ]; # fetch custom fields $update = $Tools->update_POST_custom_fields('devices', $POST->action, $POST); diff --git a/app/admin/devices/edit-snmp-result.php b/public/app/admin/devices/edit-snmp-result.php similarity index 93% rename from app/admin/devices/edit-snmp-result.php rename to public/app/admin/devices/edit-snmp-result.php index c6e9f9dd6..879893934 100644 --- a/app/admin/devices/edit-snmp-result.php +++ b/public/app/admin/devices/edit-snmp-result.php @@ -5,7 +5,7 @@ ***************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -45,8 +45,8 @@ # set snmp queries foreach($POST as $key=>$line) { - if (!is_blank(strstr($key,"query-"))) { - $key2 = str_replace("query-", "", $key); + if (!is_blank(strstr((string) $key,"query-"))) { + $key2 = str_replace("query-", "", (string) $key); $temp[] = $key2; unset($POST->$key); } @@ -55,7 +55,7 @@ $POST->snmp_queries = !empty($temp) ? implode(";", $temp) : null; # set update values -$values = array( +$values = [ "id" => $POST->device_id, "snmp_version" => $POST->snmp_version, "snmp_community" => $POST->snmp_community, @@ -69,7 +69,7 @@ "snmp_v3_priv_pass" => $POST->snmp_v3_priv_pass, "snmp_v3_ctx_name" => $POST->snmp_v3_ctx_name, "snmp_v3_ctx_engine_id" => $POST->snmp_v3_ctx_engine_id - ); + ]; # update device if(!$Admin->object_modify("devices", "edit", "id", $values)) { $Result->show("danger", _("SNMP edit failed").'!', false); } diff --git a/app/admin/devices/edit-snmp-test.php b/public/app/admin/devices/edit-snmp-test.php similarity index 96% rename from app/admin/devices/edit-snmp-test.php rename to public/app/admin/devices/edit-snmp-test.php index bed4ad057..5aba34260 100644 --- a/app/admin/devices/edit-snmp-test.php +++ b/public/app/admin/devices/edit-snmp-test.php @@ -5,7 +5,7 @@ ***************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # Don't corrupt output with php errors! disable_php_errors(); @@ -63,9 +63,9 @@ # set queries foreach($POST as $k=>$p) { - if(strpos($k, "query-")!==false) { + if(strpos((string) $k, "query-")!==false) { if($p=="on") { - $queries[] = substr($k, 6); + $queries[] = substr((string) $k, 6); } } } diff --git a/app/admin/devices/edit-snmp.php b/public/app/admin/devices/edit-snmp.php similarity index 97% rename from app/admin/devices/edit-snmp.php rename to public/app/admin/devices/edit-snmp.php index 2dbd6430e..cae1905ae 100644 --- a/app/admin/devices/edit-snmp.php +++ b/public/app/admin/devices/edit-snmp.php @@ -5,7 +5,7 @@ ************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -215,8 +215,8 @@ '. "\n"; print ' '; - print ' '; + print ' '; print ''; } ?> diff --git a/app/admin/firewall-zones/ajax.php b/public/app/admin/firewall-zones/ajax.php similarity index 91% rename from app/admin/firewall-zones/ajax.php rename to public/app/admin/firewall-zones/ajax.php index d9de6e511..6392c8682 100644 --- a/app/admin/firewall-zones/ajax.php +++ b/public/app/admin/firewall-zones/ajax.php @@ -5,7 +5,7 @@ **************************************/ # functions -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -26,7 +26,7 @@ # generate a dropdown list for all subnets within a section if ($POST->operation == 'fetchSectionSubnets') { if($POST->sectionId) { - if(preg_match('/^[0-9]+$/i',$POST->sectionId)) { + if(preg_match('/^[0-9]+$/i',(string) $POST->sectionId)) { $sectionId = $POST->sectionId; print $Subnets->print_mastersubnet_dropdown_menu($sectionId); } else { @@ -38,7 +38,7 @@ # deliver zone details if ($POST->operation == 'deliverZoneDetail') { if ($POST->zoneId) { - if(preg_match('/^[0-9]+$/i',$POST->zoneId)) { + if(preg_match('/^[0-9]+$/i',(string) $POST->zoneId)) { # return the zone details $Zones->get_zone_detail($POST->zoneId); @@ -50,7 +50,7 @@ # deliver networkinformations about a specific zone if ($POST->netZoneId) { - if(preg_match('/^[0-9]+$/i',$POST->netZoneId)) { + if(preg_match('/^[0-9]+$/i',(string) $POST->netZoneId)) { # return the zone details $Zones->get_zone_network($POST->netZoneId); } else { @@ -94,15 +94,15 @@ # generate a new firewall address object on request if ($POST->operation == 'autogen') { if ($POST->action == 'net') { - if (preg_match('/^[0-9]+$/i',$POST->subnetId)){ + if (preg_match('/^[0-9]+$/i',(string) $POST->subnetId)){ $Zones->update_address_objects($POST->subnetId); } } elseif ($POST->action == 'adr') { - if (preg_match('/^[0-9]+$/i',$POST->subnetId) && preg_match('/^[0-9a-z-.]+$/i',$POST->dnsName) && preg_match('/^[0-9]+$/i',$POST->IPId)) { + if (preg_match('/^[0-9]+$/i',(string) $POST->subnetId) && preg_match('/^[0-9a-z-.]+$/i',(string) $POST->dnsName) && preg_match('/^[0-9]+$/i',(string) $POST->IPId)) { $Zones->update_address_object($POST->subnetId,$POST->IPId,$POST->dnsName); } } elseif ($POST->action == 'subnet') { - if (preg_match('/^[0-9]+$/i',$POST->subnetId)) { + if (preg_match('/^[0-9]+$/i',(string) $POST->subnetId)) { $Zones->generate_subnet_object ($POST->subnetId); } } diff --git a/app/admin/firewall-zones/index.php b/public/app/admin/firewall-zones/index.php similarity index 83% rename from app/admin/firewall-zones/index.php rename to public/app/admin/firewall-zones/index.php index 08153f9d7..a12988278 100644 --- a/app/admin/firewall-zones/index.php +++ b/public/app/admin/firewall-zones/index.php @@ -24,7 +24,7 @@ "; print " "; - print " "; + print " "; print " "; print " "; print " "; diff --git a/app/sections/section-subnets.php b/public/app/sections/section-subnets.php similarity index 100% rename from app/sections/section-subnets.php rename to public/app/sections/section-subnets.php diff --git a/app/sections/user-menu.php b/public/app/sections/user-menu.php similarity index 94% rename from app/sections/user-menu.php rename to public/app/sections/user-menu.php index 478ae7f7f..2006f3446 100755 --- a/app/sections/user-menu.php +++ b/public/app/sections/user-menu.php @@ -6,7 +6,7 @@ # filter ip value if(!is_blank($GET->ip)) { - $GET->ip = urldecode(trim($GET->ip)); + $GET->ip = urldecode(trim((string) $GET->ip)); } # verify that user is logged in @@ -14,7 +14,7 @@ // set parameters form cookie $sp = isset($_COOKIE['search_parameters']) ? $_COOKIE['search_parameters'] : ''; -$params = json_decode($sp, true) ?: []; +$params = json_decode((string) $sp, true) ?: []; foreach ($params as $k => $p) { if ($p == "on") { $GET->{$k} = $p; @@ -72,7 +72,7 @@ ,real_name; ?>
"> user->real_name; ?>
- user->role); ?>
+ user->role); ?>
"> @@ -80,7 +80,7 @@ ">, user->real_name; ?>
- user->role); ?>
+ user->role); ?>
"> diff --git a/app/subnets/addresses/address-details-index.php b/public/app/subnets/addresses/address-details-index.php similarity index 96% rename from app/subnets/addresses/address-details-index.php rename to public/app/subnets/addresses/address-details-index.php index a8dd13d24..baeaf771c 100644 --- a/app/subnets/addresses/address-details-index.php +++ b/public/app/subnets/addresses/address-details-index.php @@ -23,17 +23,17 @@ $custom_fields = $Tools->fetch_custom_fields ('ipaddresses'); # set hidden custom fields $hidden_cfields = db_json_decode($User->settings->hiddenCustomFields, true) ? : ['ipaddresses' => null]; -$hidden_cfields = is_array($hidden_cfields['ipaddresses']) ? $hidden_cfields['ipaddresses'] : array(); +$hidden_cfields = is_array($hidden_cfields['ipaddresses']) ? $hidden_cfields['ipaddresses'] : []; # set selected address fields array $selected_ip_fields = $User->settings->IPfilter; -$selected_ip_fields = pf_explode(";", $selected_ip_fields); //format to array +$selected_ip_fields = explode(";", (string) $selected_ip_fields); //format to array $selected_ip_fields_size = in_array('state', $selected_ip_fields) ? (sizeof($selected_ip_fields)-1) : sizeof($selected_ip_fields); //set size of selected fields if($selected_ip_fields_size==1 && is_blank($selected_ip_fields[0])) { $selected_ip_fields_size = 0; } //fix for 0 # set ping statuses -$statuses = pf_explode(";", $User->settings->pingStatus); +$statuses = explode(";", (string) $User->settings->pingStatus); # permissions $subnet_permission = $Subnets->check_permission($User->user, $subnet['id']); @@ -67,8 +67,8 @@ if(sizeof($address)>1) { # NAT search - $all_nats = array(); - $all_nats_per_object = array(); + $all_nats = []; + $all_nats_per_object = []; if ($User->settings->enableNAT==1) { # fetch all object diff --git a/app/subnets/addresses/address-details/address-changelog.php b/public/app/subnets/addresses/address-details/address-changelog.php similarity index 91% rename from app/subnets/addresses/address-details/address-changelog.php rename to public/app/subnets/addresses/address-details/address-changelog.php index 30fbe3e04..333d937f3 100644 --- a/app/subnets/addresses/address-details/address-changelog.php +++ b/public/app/subnets/addresses/address-details/address-changelog.php @@ -42,7 +42,7 @@ foreach($clogs as $l) { $l = (array) $l; # format diff - $l['cdiff'] = str_replace("\n", "
", $l['cdiff']); + $l['cdiff'] = str_replace("\n", "
", (string) $l['cdiff']); # set class for badge if($l['cresult']=="success") { $bclass='alert-success'; } @@ -50,7 +50,7 @@ print "
"; print " "; - print " "; + print " "; print " "; print " "; print " "; diff --git a/app/subnets/addresses/address-details/address-details-linked.php b/public/app/subnets/addresses/address-details/address-details-linked.php similarity index 100% rename from app/subnets/addresses/address-details/address-details-linked.php rename to public/app/subnets/addresses/address-details/address-details-linked.php diff --git a/app/subnets/addresses/address-details/address-details-location.php b/public/app/subnets/addresses/address-details/address-details-location.php similarity index 91% rename from app/subnets/addresses/address-details/address-details-location.php rename to public/app/subnets/addresses/address-details/address-details-location.php index 0e356b60f..eaf4e144e 100644 --- a/app/subnets/addresses/address-details/address-details-location.php +++ b/public/app/subnets/addresses/address-details/address-details-location.php @@ -20,7 +20,7 @@ $hide_title = true; - include(dirname(__FILE__).'/../../../tools/locations/single-location.php'); + include(__DIR__.'/../../../tools/locations/single-location.php'); // back $GET->subnetId = $sid_orig; diff --git a/app/subnets/addresses/address-details/address-details-multicast.php b/public/app/subnets/addresses/address-details/address-details-multicast.php similarity index 100% rename from app/subnets/addresses/address-details/address-details-multicast.php rename to public/app/subnets/addresses/address-details/address-details-multicast.php diff --git a/app/subnets/addresses/address-details/address-details-nat.php b/public/app/subnets/addresses/address-details/address-details-nat.php similarity index 97% rename from app/subnets/addresses/address-details/address-details-nat.php rename to public/app/subnets/addresses/address-details/address-details-nat.php index 1a7bfeefe..45323d5e3 100644 --- a/app/subnets/addresses/address-details/address-details-nat.php +++ b/public/app/subnets/addresses/address-details/address-details-nat.php @@ -1,5 +1,5 @@ diff --git a/app/subnets/addresses/address-details/address-details-permissions.php b/public/app/subnets/addresses/address-details/address-details-permissions.php similarity index 86% rename from app/subnets/addresses/address-details/address-details-permissions.php rename to public/app/subnets/addresses/address-details/address-details-permissions.php index 3388f506d..f24498baa 100644 --- a/app/subnets/addresses/address-details/address-details-permissions.php +++ b/public/app/subnets/addresses/address-details/address-details-permissions.php @@ -17,7 +17,7 @@ // show permissions if ($groups!==false) { # parse permissions - if(strlen($subnet['permissions'])>1) { $permissons = $Sections->parse_section_permissions($subnet['permissions']); } + if(strlen((string) $subnet['permissions'])>1) { $permissons = $Sections->parse_section_permissions($subnet['permissions']); } else { $permissons = ""; } print "
$this->mail_font_style"._("The following change was made on ipam").":
"; // add changelog $changelog = str_replace("\r\n", "
",$changelog); - $changelog = array_filter(pf_explode("
", $changelog)); + $changelog = array_filter(explode("
", $changelog)); $content[] = ""; foreach ($changelog as $c) { @@ -1848,7 +1848,7 @@ public function changelog_send_mail ($changelog) { $value = array_pad(explode("=>", $field[1]), 2, ''); // format field - $field = trim(str_replace(array("[","]"), "", $field[0])); + $field = trim(str_replace(["[","]"], "", $field[0])); // no isFolder if($field!=="isFolder") { @@ -1875,7 +1875,7 @@ public function changelog_send_mail ($changelog) { $content[] = ""; # set plain content - $content_plain = array(); + $content_plain = []; $content_plain[] = _("Object type").": ".$this->object_type; $content_plain[] = _("Object details").": ".strip_tags($details); $content_plain[] = _("User").": ".$this->user->real_name." (".$this->user->username.")"; @@ -1916,7 +1916,7 @@ public function changelog_send_mail ($changelog) { $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName); foreach($recipients as $r) { - $phpipam_mail->Php_mailer->addAddress(addslashes(trim($r->email))); + $phpipam_mail->Php_mailer->addAddress(addslashes(trim((string) $r->email))); } $phpipam_mail->Php_mailer->Subject = $subject; $phpipam_mail->Php_mailer->msgHTML($content); diff --git a/functions/classes/class.Mail.php b/functions/classes/class.Mail.php index 86d522e39..0d2dd20b6 100644 --- a/functions/classes/class.Mail.php +++ b/functions/classes/class.Mail.php @@ -43,25 +43,7 @@ public function __construct ($settings, $mail_settings) { # set settings and mailsettings $this->settings = $settings; $this->mail_settings = $mail_settings; - - # we need phpmailer - if(file_exists(dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php')) { - // legacy versions - require_once( dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php'); - - # initialize object - $this->Php_mailer = new PHPMailer(true); //localhost by default - } - elseif (file_exists(dirname(__FILE__).'/../PHPMailer/src/Exception.php')) { - require_once( dirname(__FILE__).'/../PHPMailer/src/Exception.php'); - require_once( dirname(__FILE__).'/../PHPMailer/src/PHPMailer.php'); - require_once( dirname(__FILE__).'/../PHPMailer/src/SMTP.php'); - - $this->Php_mailer = new PHPMailer\PHPMailer\PHPMailer(); - } else { - throw new Exception(_('PHPMailer submodule is missing.')); - } - + $this->Php_mailer = new \PHPMailer\PHPMailer\PHPMailer(); $this->Php_mailer->CharSet="UTF-8"; //set utf8 $this->Php_mailer->SMTPDebug = 0; //default no debugging @@ -91,7 +73,7 @@ private function set_smtp() { $this->Php_mailer->Host = $this->mail_settings->mserver; $this->Php_mailer->Port = $this->mail_settings->mport; //permit self-signed certs and don't verify certs - $this->Php_mailer->SMTPOptions = array("ssl"=>array("verify_peer"=>false, "verify_peer_name"=>false, "allow_self_signed"=>true)); + $this->Php_mailer->SMTPOptions = ["ssl"=>["verify_peer"=>false, "verify_peer_name"=>false, "allow_self_signed"=>true]]; // uncomment this to disable AUTOTLS if security is set to none $this->Php_mailer->SMTPAutoTLS = false; //set smtp auth @@ -134,7 +116,8 @@ public function override_settings($override_settings) { * @param int $level (default: 2) * @return void */ - public function set_debugging ($level = 2) { + #[\Override] + public function set_debugging ($level = 2) { $this->Php_mailer->SMTPDebug = $level == 1 ? 1 : 2; // output $this->Php_mailer->Debugoutput = 'html'; @@ -155,7 +138,7 @@ public function set_debugging ($level = 2) { * @return string */ public function generate_message ($body) { - $html = array(); + $html = []; $html[] = $this->set_header (); //set header $html[] = $this->set_body_start (); //start body $html[] = $body; //set body @@ -173,7 +156,7 @@ public function generate_message ($body) { * @return void */ public function generate_message_plain ($body) { - $html = array(); + $html = []; $html[] = $body; //set body $html[] = $this->set_footer_plain (); //set footer } @@ -185,7 +168,7 @@ public function generate_message_plain ($body) { * @return string */ private function set_header () { - $html = array(); + $html = []; $html[] = ""; $html[] = ""; $html[] = ""; @@ -208,16 +191,16 @@ private function set_body_start () { // set width $logo_width = isset($config['logo_width']) ? $config['logo_width'] : 220; - $html = array(); + $html = []; $html[] = ""; # logo - if(!file_exists( dirname(__FILE__)."/../../css/images/logo/logo.png")) { + if(!file_exists(__DIR__ . '/../../public/css/images/logo/logo.png')) { $img = ''; // Load built-in image - require( dirname(__FILE__).'/../../app/admin/settings/logo/logo-builtin.php' ); + require __DIR__ . '/../../public/app/admin/settings/logo/logo-builtin.php'; $html[] = $img; } else { - $html[] = "phpipam"; + $html[] = "phpipam"; } # return @@ -252,7 +235,7 @@ private function set_body_end () { * @return string */ public function set_footer () { - $html = array(); + $html = []; $html[] = "
"; $html[] = "
"; $html[] = "      $this->mail_font_style_light "._("This email was automatically generated. You can change your notification settings in account details")."!
"; diff --git a/functions/classes/class.OpenStreetMap.php b/functions/classes/class.OpenStreetMap.php index 5e978e292..423dc890e 100644 --- a/functions/classes/class.OpenStreetMap.php +++ b/functions/classes/class.OpenStreetMap.php @@ -95,7 +95,7 @@ public function add_location($location) /** * Add customer object to map * - * @param StdClass $location + * @param StdClass $customer * @return bool */ public function add_customer($customer) @@ -152,7 +152,7 @@ private function add_object($object, $type) * Add circuit object to map * * @param StdClass $location1 Location of A end - * @param StdClas $location2 Location of B end + * @param StdClass $location2 Location of B end * @param StdClass $type Circuit circuitType object (color & dotted) * @return bool */ @@ -280,7 +280,7 @@ function osm_point_to_circle(feature, latlng) { private function hash_from_address($address) { $address_min = preg_replace('#\s+#', ' ', mb_strtolower($address)); - $hash = openssl_digest(trim($address_min), 'sha256', true); + $hash = openssl_digest(trim((string) $address_min), 'sha256', true); if (!is_string($hash) || strlen($hash) != 32) { throw new \Exception(_('openssl_digest failure')); @@ -352,13 +352,13 @@ public function get_latlng_from_address($address) return $result; } + $elapsed = -microtime(true); + try { // Obtain exclusive MySQL row lock $Lock = new LockForUpdateMySQL($this->Database, 'nominatim', 1); $Lock->obtain_lock(-1); - $elapsed = -microtime(true); - // Check cached results from the last 24h $cached_result = $this->search_geo_cache($address, true); if ($cached_result) { diff --git a/functions/classes/class.PDO.php b/functions/classes/class.PDO.php index a7d4cfb80..a07cdf486 100644 --- a/functions/classes/class.PDO.php +++ b/functions/classes/class.PDO.php @@ -105,7 +105,7 @@ abstract class DB { * @var array * @access public */ - public $cache = array(); + public $cache = []; /** * Enable MySQL CTE query support @@ -172,12 +172,12 @@ public function __construct($username = null, $password = null, $charset = null, * @return void */ private function load_schema_exceptions() { - $fh = fopen(dirname(__FILE__) . '/../../db/SCHEMA.sql', 'r'); + $fh = fopen(__DIR__ . '/../../db/SCHEMA.sql', 'r'); if ($fh === false) { return; } - $lines = explode("\n", str_replace("\r\n", "\n", fread($fh, 100000))); + $lines = explode("\n", str_replace("\r\n", "\n", (string) fread($fh, 100000))); fclose($fh); $current_table = ""; @@ -311,7 +311,7 @@ private function log_query ($query, $values = false) { $myFile = "/tmp/queries.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); // query - fwrite($fh, $query->queryString); + fwrite($fh, (string) $query->queryString); // values if(is_array($values)) { fwrite($fh, " Params: ".implode(", ", $values)); @@ -331,15 +331,15 @@ private function log_query ($query, $values = false) { * @return string */ public static function unquote_outer($str) { - $len = strlen($str); + $len = strlen((string) $str); if ($len>1) { if ($str[0] == "'" && $str[$len-1] == "'") { - return substr($str, 1, -1); + return substr((string) $str, 1, -1); } elseif ($str[0] == "'") { - return substr($str, 1); + return substr((string) $str, 1); } elseif ($str[$len-1] == "'") { - return substr($str, 0, -1); + return substr((string) $str, 0, -1); } } elseif ($len>0) { if ($str[0] == "'") { @@ -410,7 +410,7 @@ public function lastInsertId() { * @param integer|null &$rowCount (default: null) * @return bool */ - public function runQuery($query, $values = array(), &$rowCount = null) { + public function runQuery($query, $values = [], &$rowCount = null) { if (!$this->isConnected()) $this->connect(); $result = null; @@ -462,6 +462,7 @@ public function emulate_cte_query($tableName, $schema, $anchor_query, $anchor_ar // Run Anchor query then the recursive query until there are no more results $level = 1; + $rowCount = 0; do { // reset args for recursive query $anchor_args = $level==1 ? $anchor_args : []; @@ -507,7 +508,7 @@ public function escape($str) { // SQL Injection - strip backquote character $str = str_replace('`', '', $str); - return $this->unquote_outer($this->pdo->quote($str)); + return static::unquote_outer($this->pdo->quote($str)); } /** @@ -550,7 +551,7 @@ public function numObjectsFilter($tableName, $method, $value, $like = false) { //debug $this->log_query ($statement, (array) $value); - $statement->execute(array($value)); + $statement->execute([$value]); return $statement->fetchColumn(); } @@ -594,7 +595,7 @@ public function updateObject($tableName, $obj, $primarykey = 'id', $primarykey2 //formulate an update statement based on the object parameters $objParams = array_keys($obj); - $preparedParamArr = array(); + $preparedParamArr = []; foreach ($objParams as $objParam) { $preparedParamArr[] = '`' . $this->escape($objParam) . '`=?'; } @@ -638,7 +639,7 @@ public function updateMultipleObjects($tableName, $ids, $values) { $idParts = array_fill(0, $num, '`id`=?'); //set values $objParams = array_keys($values); - $preparedParamArr = array(); + $preparedParamArr = []; foreach ($objParams as $objParam) { $preparedParamArr[] = '`' . $this->escape($objParam) . '`=?'; } @@ -678,7 +679,7 @@ public function insertObject($tableName, $obj, $raw = false, $replace = false, $ //formulate an update statement based on the object parameters $objValues = array_values($obj); - $preparedParamsArr = array(); + $preparedParamsArr = []; foreach ($obj as $key => $value) { $preparedParamsArr[] = '`' . $this->escape($key) . '`'; } @@ -714,7 +715,7 @@ public function insertObject($tableName, $obj, $raw = false, $replace = false, $ * @param mixed $id (default: null) * @return bool */ - public function objectExists($tableName, $query = null, $values = array(), $id = null) { + public function objectExists($tableName, $query = null, $values = [], $id = null) { return is_object($this->getObject($tableName, $id)); } @@ -723,7 +724,7 @@ public function objectExists($tableName, $query = null, $values = array(), $id = * Anti stored-XSS: Safe by default strategy * * Call htmlentities() on all string data returned from the database to ensure it is safe to pass to print(). - * Areas of code that require unsafe HTML symbols will be updated to explicitly call html_entity_decode(). + * Areas of code that require unsafe HTML symbols will be updated to explicitly call unescape_input(). * * @param string $tableName * @param mixed $data @@ -800,7 +801,7 @@ public function getObjects($tableName, $sortField = 'id', $sortAsc = true, $numR $statement = $this->pdo->query('SELECT * FROM `'.$tableName.'` ORDER BY `'.$sortField.'` '.$sortStr.' LIMIT '.$numRecords.' OFFSET '.$offset.';'); } - $results = array(); + $results = []; if (is_object($statement)) { $results = $statement->fetchAll($class == 'stdClass' ? PDO::FETCH_CLASS : PDO::FETCH_NUM); @@ -819,7 +820,7 @@ public function getObjects($tableName, $sortField = 'id', $sortAsc = true, $numR * @param string $class (default: 'stdClass') * @return array */ - public function getObjectsQuery($tableName, $query = null, $values = array(), $class = 'stdClass') { + public function getObjectsQuery($tableName, $query = null, $values = [], $class = 'stdClass') { if (!$this->isConnected()) $this->connect(); $statement = $this->pdo->prepare($query); @@ -828,7 +829,7 @@ public function getObjectsQuery($tableName, $query = null, $values = array(), $c $this->log_query ($statement, $values); $statement->execute((array)$values); - $results = array(); + $results = []; if (is_object($statement)) { $results = $statement->fetchAll($class == 'stdClass' ? PDO::FETCH_CLASS : PDO::FETCH_NUM); @@ -850,10 +851,10 @@ public function getGroupBy($tableName, $groupField = 'id') { $statement = $this->pdo->prepare("SELECT `$groupField`,COUNT(*) FROM `$tableName` GROUP BY `$groupField`"); //debug - $this->log_query ($statement, array()); + $this->log_query ($statement, []); $statement->execute(); - $results = array(); + $results = []; if (is_object($statement)) { $results = $statement->fetchAll(PDO::FETCH_KEY_PAIR); @@ -887,7 +888,7 @@ public function getObject($tableName, $id = null, $class = 'stdClass') { } //debug - $this->log_query ($statement, array($id)); + $this->log_query ($statement, [$id]); $statement->execute(); //we can then extract the single object (if we have a result) @@ -910,7 +911,7 @@ public function getObject($tableName, $id = null, $class = 'stdClass') { * @param string $class (default: 'stdClass') * @return object|null */ - public function getObjectQuery($tableName, $query = null, $values = array(), $class = 'stdClass') { + public function getObjectQuery($tableName, $query = null, $values = [], $class = 'stdClass') { if (!$this->isConnected()) $this->connect(); $statement = $this->pdo->prepare($query); @@ -973,9 +974,9 @@ public function findObjects($table, $field, $value, $sortField = 'id', $sortAsc // subnets if ($table=='subnets' && $sortField=='subnet') { - return $this->getObjectsQuery($table, 'SELECT '.$result_fields.' FROM `' . $table . '` WHERE `'. $field .'`'.$negate_operator. $operator .'? ORDER BY LPAD(`subnet`,39,0) ' . ($sortAsc ? '' : 'DESC') . ';', array($value)); + return $this->getObjectsQuery($table, 'SELECT '.$result_fields.' FROM `' . $table . '` WHERE `'. $field .'`'.$negate_operator. $operator .'? ORDER BY LPAD(`subnet`,39,0) ' . ($sortAsc ? '' : 'DESC') . ';', [$value]); } else { - return $this->getObjectsQuery($table, 'SELECT '.$result_fields.' FROM `' . $table . '` WHERE `'. $field .'`'.$negate_operator. $operator .'? ORDER BY `'.$sortField.'` ' . ($sortAsc ? '' : 'DESC') . ';', array($value)); + return $this->getObjectsQuery($table, 'SELECT '.$result_fields.' FROM `' . $table . '` WHERE `'. $field .'`'.$negate_operator. $operator .'? ORDER BY `'.$sortField.'` ' . ($sortAsc ? '' : 'DESC') . ';', [$value]); } } @@ -992,7 +993,7 @@ public function findObject($table, $field, $value) { $table = $this->escape($table); $field = $this->escape($field); - return $this->getObjectQuery($table, 'SELECT * FROM `' . $table . '` WHERE `' . $field . '` = ? LIMIT 1;', array($value)); + return $this->getObjectQuery($table, 'SELECT * FROM `' . $table . '` WHERE `' . $field . '` = ? LIMIT 1;', [$value]); } /** @@ -1005,7 +1006,7 @@ public function findObject($table, $field, $value) { public function deleteObject($tableName, $id) { $tableName = $this->escape($tableName); - return $this->runQuery('DELETE FROM `'.$tableName.'` WHERE `id`=?;', array($id)); + return $this->runQuery('DELETE FROM `'.$tableName.'` WHERE `id`=?;', [$id]); } /** @@ -1057,9 +1058,9 @@ public function deleteRow($tableName, $field, $value, $field2=null, $value2 = nu //multiple if(!empty($field2)) - return $this->runQuery('DELETE FROM `'.$tableName.'` WHERE `'.$field.'`=? and `'.$field2.'`=?;', array($value, $value2)); + return $this->runQuery('DELETE FROM `'.$tableName.'` WHERE `'.$field.'`=? and `'.$field2.'`=?;', [$value, $value2]); else - return $this->runQuery('DELETE FROM `'.$tableName.'` WHERE `'.$field.'`=?;', array($value)); + return $this->runQuery('DELETE FROM `'.$tableName.'` WHERE `'.$field.'`=?;', [$value]); } /** @@ -1129,7 +1130,7 @@ class Database_PDO extends DB { * @var array * @access protected */ - protected $pdo_ssl_opts = array (); + protected $pdo_ssl_opts = []; /** * flag if installation is happening! @@ -1190,15 +1191,15 @@ private function set_db_params () { $this->ssl = false; if (@$db['ssl']===true) { - $this->pdo_ssl_opts = array ( + $this->pdo_ssl_opts = [ 'ssl_key' => PDO::MYSQL_ATTR_SSL_KEY, 'ssl_cert' => PDO::MYSQL_ATTR_SSL_CERT, 'ssl_ca' => PDO::MYSQL_ATTR_SSL_CA, 'ssl_cipher' => PDO::MYSQL_ATTR_SSL_CIPHER, 'ssl_capath' => PDO::MYSQL_ATTR_SSL_CAPATH - ); + ]; - $this->ssl = array(); + $this->ssl = []; if ($db['ssl_verify']===false) { $this->ssl[1014] = false; // PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT=1014 exists as of PHP 7.0.18 and PHP 7.1.4. @@ -1220,7 +1221,8 @@ private function set_db_params () { * @access public * @return void */ - public function connect() { + #[\Override] + public function connect() { parent::connect(); //@$this->pdo->query('SET NAMES \'' . $this->charset . '\';'); } @@ -1231,7 +1233,8 @@ public function connect() { * @access protected * @return string */ - protected function makeDsn() { + #[\Override] + protected function makeDsn() { # for installation if($this->install) { return 'mysql:host=' . $this->host . ';port=' . $this->port . ';charset=' . $this->charset; } else { return 'mysql:host=' . $this->host . ';port=' . $this->port . ';dbname=' . $this->dbname . ';charset=' . $this->charset; } @@ -1250,14 +1253,14 @@ public function getColumnInfo() { WHERE `table_schema`='" . $this->dbname . "'; "); - $columnsByTable = array(); + $columnsByTable = []; if (!is_array($columns)) return $columnsByTable; foreach ($columns as $column) { if (!isset($columnsByTable[$column->table_name])) { - $columnsByTable[$column->table_name] = array(); + $columnsByTable[$column->table_name] = []; } $columnsByTable[$column->table_name][$column->column_name] = $column; @@ -1279,7 +1282,7 @@ public function getFieldInfo ($tableName = false, $field = false) { $tableName = $this->escape($tableName); $field = $this->escape($field); // fetch and return - return $this->getObjectQuery("no_html_escape", "SHOW FIELDS FROM `$tableName` where Field = ?", array($field)); + return $this->getObjectQuery("no_html_escape", "SHOW FIELDS FROM `$tableName` where Field = ?", [$field]); } /** @@ -1296,25 +1299,25 @@ public function getForeignKeyInfo() { WHERE i.`constraint_type` = 'FOREIGN KEY' AND i.`table_schema`='" . $this->dbname . "'; "); - $foreignLinksByTable = array(); - $foreignLinksByRefTable = array(); + $foreignLinksByTable = []; + $foreignLinksByRefTable = []; if (!is_array($foreignLinks)) - return array($foreignLinksByTable, $foreignLinksByRefTable); + return [$foreignLinksByTable, $foreignLinksByRefTable]; foreach ($foreignLinks as $foreignLink) { if (!isset($foreignLinksByTable[$foreignLink->table_name])) { - $foreignLinksByTable[$foreignLink->table_name] = array(); + $foreignLinksByTable[$foreignLink->table_name] = []; } if (!isset($foreignLinksByRefTable[$foreignLink->referenced_table_name])) { - $foreignLinksByRefTable[$foreignLink->referenced_table_name] = array(); + $foreignLinksByRefTable[$foreignLink->referenced_table_name] = []; } $foreignLinksByTable[$foreignLink->table_name][$foreignLink->column_name] = $foreignLink; $foreignLinksByRefTable[$foreignLink->referenced_table_name][$foreignLink->table_name] = $foreignLink; } - return array($foreignLinksByTable, $foreignLinksByRefTable); + return [$foreignLinksByTable, $foreignLinksByRefTable]; } } diff --git a/functions/classes/class.Params.php b/functions/classes/class.Params.php index 97e1af382..4886047b9 100644 --- a/functions/classes/class.Params.php +++ b/functions/classes/class.Params.php @@ -43,6 +43,7 @@ public function __construct($args = [], $default = null, $strip_tags = false, $h * * @return int */ + #[\Override] public function count() : int { return count($this->as_array()); } @@ -65,10 +66,7 @@ public function as_array() { * @return mixed */ public function __get($name) { - if (isset($this->{$name})) - return $this->{$name}; - - return $this->____default; + return $this->{$name} ?? $this->____default; } /** diff --git a/functions/classes/class.Password_check.php b/functions/classes/class.Password_check.php index 9028553ba..fad435f21 100644 --- a/functions/classes/class.Password_check.php +++ b/functions/classes/class.Password_check.php @@ -254,10 +254,9 @@ private function validate_symbols () { /** * Count all symbols * - * @method count_symbols - * @return void + */ - private function count_symbols () { + private function count_symbols (): int { $cnt = 0; foreach (preg_split('//u',$this->password, -1, PREG_SPLIT_NO_EMPTY) as $l) { if (in_array($l, $this->allowedSymbols)) { @@ -275,6 +274,6 @@ private function count_symbols () { * @return string[]|false */ private function get_special_chars () { - return preg_split('//u',preg_replace("/[a-zA-Z,0-9]/u", "", $this->password), -1, PREG_SPLIT_NO_EMPTY); + return preg_split('//u',(string) preg_replace("/[a-zA-Z,0-9]/u", "", $this->password), -1, PREG_SPLIT_NO_EMPTY); } } diff --git a/functions/classes/class.PowerDNS.php b/functions/classes/class.PowerDNS.php index 05bdc75a3..ee7cac98d 100644 --- a/functions/classes/class.PowerDNS.php +++ b/functions/classes/class.PowerDNS.php @@ -112,7 +112,7 @@ class PowerDNS extends Common_functions { * @var array * @access private */ - private $domains_cache = array(); + private $domains_cache = []; /** * Database class - phpipam @@ -181,12 +181,12 @@ public function __construct (Database_PDO $Database) { */ private function db_set () { // decode values form powerDNS - $this->db_settings = strlen($this->settings->powerDNS)>10 ? db_json_decode($this->settings->powerDNS) : db_json_decode($this->db_set_db_settings ()); + $this->db_settings = strlen((string) $this->settings->powerDNS)>10 ? db_json_decode($this->settings->powerDNS) : db_json_decode($this->db_set_db_settings ()); // if comma delimited host - if (strpos($this->db_settings->host, ";")!==false) { + if (strpos((string) $this->db_settings->host, ";")!==false) { // get all databases - $this->db_settings->host = explode(";", $this->db_settings->host); + $this->db_settings->host = explode(";", (string) $this->db_settings->host); // set active index $this->active_db = false; // check each, use first we are able to connect to @@ -275,12 +275,12 @@ public function get_last_db_id () { * @access private */ private function set_domain_types () { - $types = array( + $types = [ "NATIVE", "MASTER", "SLAVE", "SUPERSLAVE" - ); + ]; # save $this->domain_types = (object) $types; } @@ -313,7 +313,7 @@ private function set_domain_types () { */ private function set_record_types () { // init - $record_types = array(); + $record_types = []; // set array $record_types[] = "A"; $record_types[] = "AAAA"; @@ -339,7 +339,7 @@ private function set_record_types () { */ private function set_ttl_values () { // init - $ttl = array(); + $ttl = []; // set array $ttl[60] = "1 minute"; $ttl[180] = "3 minutes"; @@ -630,7 +630,7 @@ public function count_domain_records ($domain_id) { // query $query = 'SELECT COUNT(*) AS `cnt` FROM `records` WHERE `domain_id` = ? AND `type` IS NOT NULL;'; // fetch - try { $records = $this->Database_pdns->getObjectsQuery("records", $query, array($domain_id)); } + try { $records = $this->Database_pdns->getObjectsQuery("records", $query, [$domain_id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -651,7 +651,7 @@ public function count_domain_records_by_type ($domain_id, $type="PTR") { // query $query = "select count(*) as `cnt` from `records` where `domain_id` = ? and `type` = ?;"; // fetch - try { $records = $this->Database_pdns->getObjectsQuery("records", $query, array($domain_id, $type)); } + try { $records = $this->Database_pdns->getObjectsQuery("records", $query, [$domain_id, $type]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -680,7 +680,7 @@ public function count_domain_records_by_type ($domain_id, $type="PTR") { public function fetch_all_domain_records ($domain_id) { $query = "SELECT * FROM `records` WHERE `domain_id` = ? AND `type` IS NOT NULL ORDER BY $this->orderby $this->orderdir LIMIT $this->limit;"; // fetch - try { $records = $this->Database_pdns->getObjectsQuery("records", $query, array($domain_id)); } + try { $records = $this->Database_pdns->getObjectsQuery("records", $query, [$domain_id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -695,13 +695,13 @@ public function fetch_all_domain_records ($domain_id) { * @access public * @param mixed $domain_id * @param mixed $type - * @return void + * @return array|false */ public function fetch_domain_records_by_type ($domain_id, $type) { // query $query = "select * from `records` where `domain_id` = ? and `type` = ? order by $this->orderby $this->orderdir limit $this->limit;"; // fetch - try { $records = $this->Database_pdns->getObjectsQuery("records", $query, array($domain_id, $type)); } + try { $records = $this->Database_pdns->getObjectsQuery("records", $query, [$domain_id, $type]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -742,7 +742,7 @@ public function search_domains_by_hostname_or_ip ($hostname, $ip) { // query $query = "select DISTINCT(`domain_id`) from `records` where `name` = ? or `content` = ? and `type` != 'NS' and `type` != 'SOA';"; // fetch - try { $records = $this->Database_pdns->getObjectsQuery("records", $query, array($hostname, $ip)); } + try { $records = $this->Database_pdns->getObjectsQuery("records", $query, [$hostname, $ip]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -764,7 +764,7 @@ public function search_record_domain_type_name ($domain_id, $type, $name) { // query $query = "select * from `records` where `domain_id` = ? and `type` = ? and `name` = ? limit 1;"; // fetch - try { $records = $this->Database_pdns->getObjectQuery("records", $query, array($domain_id, $type, $name)); } + try { $records = $this->Database_pdns->getObjectQuery("records", $query, [$domain_id, $type, $name]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -1005,7 +1005,7 @@ public function pdns_remove_ip_and_hostname_records ($hostname, $ip) { $query = "delete from `records` where (`name` = ? or `content` = ?) and `type` != 'NS' and `type` != 'SOA';"; // run - try { $this->Database_pdns->runQuery($query, array($hostname, $ip)); } + try { $this->Database_pdns->runQuery($query, [$hostname, $ip]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -1060,17 +1060,17 @@ private function update_soa_serial ($domain_id, $serial = false) { else { $soa = $soa[0]; } // update serial it not autoserial - $soa_serial = pf_explode(" ", $soa->content); + $soa_serial = explode(" ", (string) $soa->content); $soa_serial[2] = $this->db_settings->autoserial=="Yes" ? 0 : (int) $soa_serial[2]+1; // if serail set override it if($serial!==false) { $soa_serial[2] = $serial; } // set update content - $content = array( + $content = [ "id"=>$soa->id, "content"=>implode(" ", $soa_serial) - ); + ]; // update $this->update_domain_record_content ($content); } @@ -1113,9 +1113,9 @@ public function create_default_records ($values, $checkOnly = false) { $this->db_set_db_settings (); // content - $soa = array(); - $soa[] = array_shift(pf_explode(";", $values['ns'])); - $soa[] = str_replace ("@", ".", $values['hostmaster']); + $soa = []; + $soa[] = array_shift(explode(";", (string) $values['ns'])); + $soa[] = str_replace ("@", ".", (string) $values['hostmaster']); $soa[] = date("Ymd")."00"; $soa[] = $this->validate_refresh ($values['refresh']); $soa[] = $this->validate_integer ($values['retry']); @@ -1126,7 +1126,7 @@ public function create_default_records ($values, $checkOnly = false) { $records[] = $this->formulate_new_record ($this->lastId, $values['name'], "SOA", implode(" ", $soa), $values['ttl'], null, 0, $checkOnly); // formulate NS records - $ns = pf_explode(";", $values['ns']); + $ns = explode(";", (string) $values['ns']); if (sizeof($ns)>0) { foreach($ns as $s) { // validate @@ -1260,18 +1260,18 @@ private function validate_record_name ($name, $type = NULL) { // certain record types allow forbidden characters in record name // when using reserved words if ($type == "TXT") { - if (preg_match("/^_dmarc.*$/", $name) - && preg_match("/^.{1,253}$/", $name) //overall length check - && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $name)) //length of each label) + if (preg_match("/^_dmarc.*$/", (string) $name) + && preg_match("/^.{1,253}$/", (string) $name) //overall length check + && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", (string) $name)) //length of each label) { return $name; } - if (preg_match("/^.*_domainkey.*$/", $name) - && preg_match("/^.{1,253}$/", $name) //overall length check - && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $name)) //length of each label) + if (preg_match("/^.*_domainkey.*$/", (string) $name) + && preg_match("/^.{1,253}$/", (string) $name) //overall length check + && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", (string) $name)) //length of each label) { return $name; } } // DNS wildcard records are OK (https://tools.ietf.org/html/rfc4592#section-2.1.1) - if (preg_match("/^\*\..*$/", $name) && $this->validate_hostname(substr($name, 2))) { + if (preg_match("/^\*\..*$/", (string) $name) && $this->validate_hostname(substr((string) $name, 2))) { return $name; } @@ -1396,7 +1396,7 @@ private function validate_integer ($int) { */ public function update_all_records ($domain_id, $old_name, $name) { // execute - try { $this->Database_pdns->runQuery("update `records` set `name` = replace(`name`, ?, ?) where where `domain_id` = ?;", array($old_name, $name, $domain_id)); } + try { $this->Database_pdns->runQuery("update `records` set `name` = replace(`name`, ?, ?) where where `domain_id` = ?;", [$old_name, $name, $domain_id]); } catch (Exception $e) { // write log $this->Result->show("danger", _("Error: ").$e->getMessage()); @@ -1414,7 +1414,7 @@ public function update_all_records ($domain_id, $old_name, $name) { */ public function remove_all_records ($domain_id) { // execute - try { $this->Database_pdns->runQuery("delete from `records` where `domain_id` = ?;", array($domain_id)); } + try { $this->Database_pdns->runQuery("delete from `records` where `domain_id` = ?;", [$domain_id]); } catch (Exception $e) { // write log $this->Log->write( _("PowerDNS domain truncate"), _("Failed to remove all PowerDNS domain records").": ".$e->getMessage()."
".$this->array_to_log((array) $domain_id), 2); @@ -1464,7 +1464,7 @@ public function get_ptr_zone_name_v4 ($ip, $mask) { $bits = $mask<24 ? 2 : 1; // to array - $zone = pf_explode(".", $ip); + $zone = explode(".", (string) $ip); // create name if ($bits==1) { return $zone[2].".".$zone[1].".".$zone[0].".in-addr.arpa"; } @@ -1489,7 +1489,7 @@ public function get_ptr_zone_name_v6 ($ip, $mask) { $networkp = $ipp & $maskp; $ipt = ''; - foreach(str_split($networkp) as $char) $ipt .= str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT); + foreach(str_split($networkp) as $char) $ipt .= str_pad(dechex(ord($char[0])), 2, '0', STR_PAD_LEFT); $prefixnibbles = floor($mask / 4); $network = substr($ipt, 0, $prefixnibbles); $zone = array_reverse(str_split($network)); @@ -1508,7 +1508,7 @@ public function get_ip_ptr_name ($ip) { // set zone prefix and reverse content if ($this->identify_address ($ip)=="IPv4") { $prefix = ".in-addr.arpa"; - $zone = array_reverse(pf_explode(".", $ip)); + $zone = array_reverse(explode(".", (string) $ip)); } else { // PEAR for IPv6 @@ -1518,7 +1518,7 @@ public function get_ip_ptr_name ($ip) { $ip = $this->Net_IPv6->removeNetmaskSpec($ip); // to array - $ip = pf_explode(":", $ip); + $ip = explode(":", $ip); // if 0 than add 4 nulls foreach ($ip as $k=>$i) { @@ -1545,7 +1545,7 @@ public function get_ip_ptr_name ($ip) { */ public function record_exists ($domain_id, $name, $type, $content) { // execute - try { $res = $this->Database_pdns->getObjectQuery("records", "select count(*) as `cnt` from `records` where `domain_id` = ? and `name`=? and `type`=? and `content`=?;", array($domain_id, $name, $type, $content)); } + try { $res = $this->Database_pdns->getObjectQuery("records", "select count(*) as `cnt` from `records` where `domain_id` = ? and `name`=? and `type`=? and `content`=?;", [$domain_id, $name, $type, $content]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -1583,18 +1583,18 @@ public function record_id_exists ($ptr_id = 0) { * @param mixed $indexes (array of PTR indexes) * @return bool */ - public function remove_all_ptr_records ($domain_id, $indexes = array()) { + public function remove_all_ptr_records ($domain_id, $indexes = []) { // if false return ok and don't execute if (sizeof($indexes)==0 || !is_array($indexes)) { return true; } // set parameters - default - $params = array($domain_id); + $params = [$domain_id]; // set query - start $query = "delete from `records` where `domain_id` = ? and `type` = 'PTR'"; // loop if (sizeof($indexes)>0) { - $q_tmp = array(); + $q_tmp = []; $query .= " and ("; foreach ($indexes as $i) { $q_tmp[] = " `id` = ? "; diff --git a/functions/classes/class.Rackspace.php b/functions/classes/class.Rackspace.php index 88236e84d..bfe7ef30b 100755 --- a/functions/classes/class.Rackspace.php +++ b/functions/classes/class.Rackspace.php @@ -15,7 +15,7 @@ class phpipam_rack extends Tools { * @var array * @access public */ - public $rack_sizes = array(); + public $rack_sizes = []; /** * List of all racks @@ -112,6 +112,7 @@ public function fetch_all_racks ($locations = false) { $this->all_racks = false; } else { + $out = []; // reindex foreach ($all_racks as $r) { $out[$r->id] = $r; @@ -251,10 +252,10 @@ public function free_u($rack, $rack_devices, $rack_contents, $current_device = n unset($available_back[$rack->size+$m]); } - /* if the current device rackStart is not valid because of a prior bug, then it will not be included - * in the result. this is bad because the GUI will not have that option included in the dropdown menu, - * which will mean the user could accidentally submit the form and move the device to a different - * position without realizing. therefore, let us ensure the current position is included even if it's + /* if the current device rackStart is not valid because of a prior bug, then it will not be included + * in the result. this is bad because the GUI will not have that option included in the dropdown menu, + * which will mean the user could accidentally submit the form and move the device to a different + * position without realizing. therefore, let us ensure the current position is included even if it's * invalid. we will then try to catch the invalid position upon form submission. */ if (property_exists($current_device, 'rack_start')) { @@ -307,9 +308,8 @@ public function draw_rack ($id, $deviceId = false, $is_back = false, $draw_names * @param bool $recursion // a kill switch to make sure we don't loop infinitely * * @access private - * @return void */ - private function compile_rack_contents ($id, $deviceId = false, $is_back = false, $draw_names = true, $recursion = true) { + private function compile_rack_contents ($id, $deviceId = false, $is_back = false, $draw_names = true, $recursion = true): Rack { // fetch rack details $rack = $this->fetch_rack_details ($id); // fetch rack devices @@ -320,7 +320,7 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false if ($is_back) { $rack_name = "["._('R')."] ".$rack->name; } elseif ($rack->hasBack) { $rack_name = "["._('F')."] ".$rack->name; } else { $rack_name = $rack->name; } - $rack_content = array(); + $rack_content = []; // set freeform content if ($contents!==false) { @@ -329,12 +329,12 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false if ($is_back) { if ($c->rack_start > $rack->size) { // add initial location - $rd = array("id"=>"none", + $rd = ["id"=>"none", "name"=>$c->name, "startLocation"=>$c->rack_start-$rack->size, "size"=>$c->rack_size, "rackName"=>$rack->name, - ); + ]; // if startlocation is not set $rd['startLocation'] -= 1; // prepend name if full depth @@ -343,7 +343,7 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false if(!$draw_names) { unset ($rd['name']); } // populate the subrack data if ($c->subrackId) { - $rd['url'] = htmlentities(create_link("tools", "racks", $c->subrackId)); + $rd['url'] = escape_input(create_link("tools", "racks", $c->subrackId)); if ($recursion) $rd['subrack'] = $this->compile_rack_contents ($c->subrackId, $deviceId, !$is_back, $draw_names, false); if (sizeof($rd['subrack']->getContent())==0) unset($rd['subrack']); } @@ -352,19 +352,19 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false } else { if ($c->rack_deep) { // add initial location - $rd = array("id"=>"none", + $rd = ["id"=>"none", "name"=>"["._('R')."] ".$c->name, "startLocation"=>$c->rack_start, "size"=>$c->rack_size, "rackName"=>$rack->name, - ); + ]; // if startlocation is not set $rd['startLocation'] -= 1; // remove name if not permitted if(!$draw_names) { unset ($rd['name']); } // populate the subrack data if ($c->subrackId) { - $rd['url'] = htmlentities(create_link("tools", "racks", $c->subrackId)); + $rd['url'] = escape_input(create_link("tools", "racks", $c->subrackId)); if ($recursion) $rd['subrack'] = $this->compile_rack_contents ($c->subrackId, $deviceId, $is_back, $draw_names, false); if (sizeof($rd['subrack']->getContent())==0) unset($rd['subrack']); } @@ -377,12 +377,12 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false else { if($c->rack_start <= $rack->size) { // add initial location - $rd = array("id"=>"none", + $rd = ["id"=>"none", "name"=>$c->name, "startLocation"=>$c->rack_start, "size"=>$c->rack_size, "rackName"=>$rack->name, - ); + ]; // if startlocation is not set $rd['startLocation'] -= 1; // prepend name if full depth @@ -390,7 +390,7 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false // remove name if not permitted if(!$draw_names) { unset ($rd['name']); } if ($c->subrackId) { - $rd['url'] = htmlentities(create_link("tools", "racks", $c->subrackId)); + $rd['url'] = escape_input(create_link("tools", "racks", $c->subrackId)); if ($recursion) $rd['subrack'] = $this->compile_rack_contents ($c->subrackId, $deviceId, $is_back, $draw_names, false); if (sizeof($rd['subrack']->getContent())==0) unset($rd['subrack']); } @@ -399,18 +399,18 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false } else { if ($c->rack_deep) { // add initial location - $rd = array("id"=>"none", + $rd = ["id"=>"none", "name"=>"["._('R')."] ".$c->name, "startLocation"=>$c->rack_start-$rack->size, "size"=>$c->rack_size, "rackName"=>$rack->name, - ); + ]; // if startlocation is not set $rd['startLocation'] -= 1; // remove name if not permitted if(!$draw_names) { unset ($rd['name']); } if ($c->subrackId) { - $rd['url'] = htmlentities(create_link("tools", "racks", $c->subrackId)); + $rd['url'] = escape_input(create_link("tools", "racks", $c->subrackId)); if ($recursion) $rd['subrack'] = $this->compile_rack_contents ($c->subrackId, $deviceId, !$is_back, $draw_names, false); if (sizeof($rd['subrack']->getContent())==0) unset($rd['subrack']); } @@ -433,15 +433,15 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false if($is_back) { if($d->rack_start > $rack->size) { // add initial location - $rd = array("id"=>$d->id, + $rd = ["id"=>$d->id, "name"=>$d->hostname, "startLocation"=>$d->rack_start-$rack->size, "size"=>$d->rack_size, "rackName"=>$rack->name, - "url"=>htmlentities(create_link("tools", "devices", $d->id)), + "url"=>escape_input(create_link("tools", "devices", $d->id)), "bgcolor"=>$bg, "fgcolor"=>$fg, - ); + ]; // if startlocation is not set $rd['startLocation'] -= 1; // prepend name if full depth @@ -453,15 +453,15 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false } else { if ($d->rack_deep) { // add initial location - $rd = array("id"=>$d->id, + $rd = ["id"=>$d->id, "name"=>"["._('R')."] ".$d->hostname, "startLocation"=>$d->rack_start, "size"=>$d->rack_size, "rackName"=>$rack->name, - "url"=>htmlentities(create_link("tools", "devices", $d->id)), + "url"=>escape_input(create_link("tools", "devices", $d->id)), "bgcolor"=>$bg, "fgcolor"=>$fg, - ); + ]; // if startlocation is not set $rd['startLocation'] -= 1; // remove name if not permitted @@ -475,15 +475,15 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false else { if($d->rack_start <= $rack->size) { // add initial location - $rd = array("id"=>$d->id, + $rd = ["id"=>$d->id, "name"=>$d->hostname, "startLocation"=>$d->rack_start, "size"=>$d->rack_size, "rackName"=>$rack->name, - "url"=>htmlentities(create_link("tools", "devices", $d->id)), + "url"=>escape_input(create_link("tools", "devices", $d->id)), "bgcolor"=>$bg, "fgcolor"=>$fg, - ); + ]; // if startlocation is not set $rd['startLocation'] -= 1; // prepend name if full depth @@ -495,15 +495,15 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false } else { if ($d->rack_deep) { // add initial location - $rd = array("id"=>$d->id, + $rd = ["id"=>$d->id, "name"=>"["._('R')."] " . $d->hostname, "startLocation"=>$d->rack_start-$rack->size, "size"=>$d->rack_size, "rackName"=>$rack->name, - "url"=>htmlentities(create_link("tools", "devices", $d->id)), + "url"=>escape_input(create_link("tools", "devices", $d->id)), "bgcolor"=>$bg, "fgcolor"=>$fg, - ); + ]; // if startlocation is not set $rd['startLocation'] -= 1; // remove name if not permitted @@ -517,8 +517,8 @@ private function compile_rack_contents ($id, $deviceId = false, $is_back = false } // create rack - $result = new Rack (array("id"=>$id, "name"=>$rack_name, "content"=>$rack_content, - "space"=>$rack->size, "orientation"=>$rack->topDown)); + $result = new Rack (["id"=>$id, "name"=>$rack_name, "content"=>$rack_content, + "space"=>$rack->size, "orientation"=>$rack->topDown]); // set active device if ($deviceId!==false) { @@ -550,7 +550,7 @@ public function find_subrack_parent ($id) { * @return array|false */ public function fetch_orphan_subracks () { - $out = array(); + $out = []; $racks = $this->fetch_all_objects("racks", "id"); if ($racks!==false) { $all_content = $this->fetch_all_objects("rackContents"); @@ -747,9 +747,9 @@ class RackDrawer extends Common_functions { public function draw(Rack $rack) { $this->rack = $rack; - $top = imagecreatefromstring(file_get_contents(dirname(__FILE__).'/../../css/images/blankracks/rack-top.png', false)); - $unit = imagecreatefromstring(file_get_contents(dirname(__FILE__).'/../../css/images/blankracks/rack-unit.png', false)); - $bottom = imagecreatefromstring(file_get_contents(dirname(__FILE__).'/../../css/images/blankracks/rack-bottom.png', false)); + $top = imagecreatefromstring(file_get_contents(__DIR__ . '/../../public/css/images/blankracks/rack-top.png', false)); + $unit = imagecreatefromstring(file_get_contents(__DIR__ . '/../../public/css/images/blankracks/rack-unit.png', false)); + $bottom = imagecreatefromstring(file_get_contents(__DIR__ . '/../../public/css/images/blankracks/rack-bottom.png', false)); $this->rackXSize = imagesx($top); $this->topYSize = imagesy($top); $this->unitYSize = imagesy($unit); @@ -767,14 +767,14 @@ public function draw(Rack $rack) { for ($i = 0; $i < $this->rack->getSpace(); $i++) { imagecopy($this->template, $unit, 0, $y, 0, 0, $this->rackXSize, $this->unitYSize); $text = ($this->rack->getOrientation()) ? $i + 1 : $this->rack->getSpace() - $i; - $textBox = imagettfbbox(12, 0, dirname(__FILE__)."/../../css/fonts/MesloLGS-Regular.ttf", $text); + $textBox = imagettfbbox(12, 0, __DIR__ . '/../../public/css/fonts/MesloLGS-Regular.ttf', $text); // disable transparency for U labels imagealphablending($this->template, true); imagettftext($this->template, 12, 0, $this->rackInsideXOffset - 4 - abs($textBox[2] - $textBox[0]), $y + abs($textBox[1] - $textBox[7]) + round(($this->unitYSize - ($textBox[1] - $textBox[7])) / 2), - $textColor, dirname(__FILE__)."/../../css/fonts/MesloLGS-Regular.ttf", $text); + $textColor, __DIR__ . '/../../public/css/fonts/MesloLGS-Regular.ttf', $text); imagealphablending($this->template, false); $y += $this->unitYSize; @@ -786,7 +786,11 @@ public function draw(Rack $rack) { header("Content-type: image/png"); imagepng($this->template); - imagedestroy($this->template); + if (version_compare(PHP_VERSION, '8.5.0', '<')) { + // phpcs:ignore + imagedestroy($this->template); + // phpcs:enable + } } /** @@ -816,7 +820,7 @@ private function imageCenterString($img, $text, $color) { $x = imagesx($img) - $width - 8; $y = Imagesy($img) +9; // imagestring($img, $font, $x/2, $y/2, $text, $color); - imagettftext($img, 8, 0, (int) $x/2, (int) $y/2, $color, dirname(__FILE__)."/../../css/fonts/MesloLGS-Regular.ttf", $text ); + imagettftext($img, 8, 0, (int) $x/2, (int) $y/2, $color, __DIR__ . '/../../public/css/fonts/MesloLGS-Regular.ttf', $text ); } /** @@ -838,7 +842,11 @@ private function drawContents() { $this->topYSize + $this->unitYSize * ($this->rack->getSpace() - ($content->getStartLocation() + $content->getSize())); imagecopy($this->template, $img, $this->rackInsideXOffset + 1, $yPos, 0, 0, $this->rackInsideXSize - 2, $pixelSize); - imagedestroy($img); + if (version_compare(PHP_VERSION, '8.5.0', '<')) { + // phpcs:ignore + imagedestroy($img); + // phpcs:enable + } } } @@ -886,7 +894,7 @@ public function __construct(array $fields) { foreach ($fields as $field => $value) { - $setter = 'set' . ucfirst($field); + $setter = 'set' . ucfirst((string) $field); if (method_exists($this, $setter)) { $this->{$setter}($value); } @@ -968,7 +976,7 @@ class RackDrawer_SVG extends Common_functions { * @var mixed * @access private */ - private $svgData = array(); + private $svgData = []; /** @@ -1054,7 +1062,7 @@ private function drawStyles() { } /** - * Draws rack frame + * Draws rack frame * * @access public * @return void @@ -1132,7 +1140,7 @@ private function drawNameplate() { $w = $this->imgXSize - ($this->marginSides * 2) - 14; $h = $this->unitYSize - 2; $this->svgData[] = ""; - $this->svgData[] = ""; + $this->svgData[] = ""; $this->svgData[] = ""; $this->svgData[] = "{$this->rack->getName()}"; $this->svgData[] = ""; @@ -1145,13 +1153,13 @@ private function drawNameplate() { * @return void */ private function drawContents() { - $output = array(); - $keepOnTop = array(); + $output = []; + $keepOnTop = []; $output[] = ""; $w = $this->imgXSize - ($this->marginSides * 2); $x_center = $this->imgXSize / 2; foreach ($this->rack->getContent() as $content) { - $queue = array(); + $queue = []; $size = max($content->getSize(), 1); $h = $this->unitYSize * $size; $yPos = ($this->rack->getOrientation()) ? @@ -1178,7 +1186,7 @@ private function drawContents() { } $cornerstone_x = $this->marginSides + $subrack_margin; $cornerstone_y = $yPos + $h + $this->unitYSize; - if (strlen($content->getName())>0) $queue[] = "{$content->getName()}"; + if (strlen((string) $content->getName())>0) $queue[] = "{$content->getName()}"; foreach ($content->getSubrack()->getContent() as $blade) { $this_y = $cornerstone_y + (($blade->getStartLocation() - 0) * ($blade_h + $subrack_margin)); $this_h = ($blade_h * $blade->getSize()) + ($subrack_margin * ($blade->getSize() - 1)); @@ -1186,13 +1194,13 @@ private function drawContents() { // Chrome won't render nested // if ($blade->getUrl()) $queue[] = ""; $queue[] = ""; - if (strlen($content->getName())>0) $queue[] = "{$blade->getName()}"; + if (strlen((string) $content->getName())>0) $queue[] = "{$blade->getName()}"; // Chrome won't render nested // if ($blade->getUrl()) $queue[] = ""; } } else { $y = $y + (($size - 1) * $this->unitYSize / 2); // increase the height by .5RU for each device whose size exceeds 1 RU - if (strlen($content->getName())>0) $queue[] = "{$content->getName()}"; + if (strlen((string) $content->getName())>0) $queue[] = "{$content->getName()}"; } if ($content->getUrl()) $queue[] = ""; // place the queue onto the stack @@ -1203,6 +1211,17 @@ private function drawContents() { $this->svgData = array_merge($this->svgData,$output); } + /** + * Return SVG HTML entities + * + * @access public + * @return string + */ + private function svg_html_entities() { + // https://github.com/phpipam/phpipam/issues/4595 + return ' '; + } + /** * Draws the rack * @@ -1213,6 +1232,7 @@ private function drawContents() { public function draw(Rack $rack) { $this->rack = $rack; $this->imgYSize = $this->marginTop + $this->marginBottom + $this->marginFeet + ($this->unitYSize * $this->rack->getSpace()); + $this->svgData[] = 'svg_html_entities() .' ]>'; $this->svgData[] = ""; $this->drawDefs(); $this->drawStyles(); diff --git a/functions/classes/class.Radius.php b/functions/classes/class.Radius.php deleted file mode 100644 index 49cf4d183..000000000 --- a/functions/classes/class.Radius.php +++ /dev/null @@ -1,832 +0,0 @@ -. - * - * - * @author: SysCo/al - * @updated: https://github.com/flaviojunior1995 - * @since CreationDate: 2008-01-04 - * @copyright (c) 2008 by SysCo systemes de communication sa - * @version $LastChangedRevision: 1.2.3 $ - * @version $LastChangedDate: 2023-20-12 $ - * @version $LastChangedBy: https://github.com/flaviojunior1995 $ - * @link $HeadURL: radius.class.php $ - * @link http://developer.sysco.ch/php/ - * @link developer@sysco.ch - * Language: PHP 7.2 or higher - * - * - * Usage - * - * require_once('radius.class.php'); - * $radius = new Radius($ip_radius_server = 'radius_server_ip_address', $shared_secret = 'radius_shared_secret'[, $radius_suffix = 'optional_radius_suffix'[, $udp_timeout = udp_timeout_in_seconds[, $authentication_port = 1812]]]); - * $result = $radius->Access_Request($username = 'username', $password = 'password'[, $udp_timeout = udp_timeout_in_seconds]); - * - * - * Examples - * - * Example 1 - * SetNasIpAddress('1.2.3.4'); // Needed for some devices, and not auto_detected if PHP not ran through a web server - * if ($radius->AccessRequest('user', 'pass')) - * { - * echo "Authentication accepted."; - * } - * else - * { - * echo "Authentication rejected."; - * } - * ?> - * - * Example 2 - * SetNasPort(0); - * $radius->SetNasIpAddress('1.2.3.4'); // Needed for some devices, and not auto_detected if PHP not ran through a web server - * if ($radius->AccessRequest('user', 'pass')) - * { - * echo "Authentication accepted."; - * echo "
"; - * } - * else - * { - * echo "Authentication rejected."; - * echo "
"; - * } - * echo $radius->GetReadableReceivedAttributes(); - * ?> - * - * - * External file needed - * - * none. - * - * - * External file created - * - * none. - * - * - * Special issues - * - * - Sockets support must be enabled. - * * In Linux and *nix environments, the extension is enabled at - * compile time using the --enable-sockets configure option - * * In Windows, PHP Sockets can be activated by un-commenting - * extension=php_sockets.dll in php.ini - * - * - * Other related resources - * - * FreeRADIUS, a free Radius server implementation for Linux and *nix environments: - * http://www.freeradius.org/ - * - * WinRadius, Windows Radius server (free for 5 users): - * http://www.itconsult2000.com/en/product/WinRadius.zip - * - * Radl, a free Radius server for Windows: - * http://www.loriotpro.com/Products/RadiusServer/FreeRadiusServer_EN.php - * - * DOS command line Radius client: - * http://www.itconsult2000.com/en/product/WinRadiusClient.zip - * - * - * Users feedbacks and comments - * - * 2008-07-02 Pim Koeman/Parantion - * - * When using a radius connection behind a linux iptables firewall - * allow port 1812 and 1813 with udp protocol - * - * IPTABLES EXAMPLE (command line): - * iptables -A AlwaysACCEPT -p udp --dport 1812 -j ACCEPT - * iptables -A AlwaysACCEPT -p udp --dport 1813 -j ACCEPT - * - * or put the lines in /etc/sysconfig/iptables (red-hat type systems (fedora, centos, rhel etc.) - * -A AlwaysACCEPT -p udp --dport 1812 -j ACCEPT - * -A AlwaysACCEPT -p udp --dport 1813 -j ACCEPT - * - * - * Change Log - * - * 2023-12-20 1.2.3 https://github.com/flaviojunior1995 Updated to work with php8 and fix deprecated errors - * 2009-01-05 1.2.2 SysCo/al Added Robert Svensson feedback, Mideye RADIUS server is supported - * 2008-11-11 1.2.1 SysCo/al Added Carlo Ferrari resolution in examples (add NAS IP Address for a VASCO Middleware server) - * 2008-07-07 1.2 SysCo/al Added Pim Koeman (Parantion) contribution - * - comments concerning using radius behind a linux iptables firewall - * Added Jon Bright (tick Trading Software AG) contribution - * - false octal encoding with 0xx indexes (indexes are now rewritten in xx only) - * - challenge/response support for the RSA SecurID New-PIN mode - * Added GetRadiusPacketInfo() method - * Added GetAttributesInfo() method - * Added DecodeVendorSpecificContent() (to answer Raul Carvalho's question) - * Added Decoded Vendor Specific Content in debug messages - * 2008-02-04 1.1 SysCo/al Typo error for the udp_timeout parameter (line 256 in the version 1.0) - * 2008-01-07 1.0 SysCo/al Initial release - * - *********************************************************************/ - - -/********************************************************************* - * - * Radius - * Pure PHP radius class - * - * Creation 2008-01-04 - * Update 2023-12-20 - * @package radius - * @version v.1.2.3 - * @author SysCo/al - * @updated https://github.com/flaviojunior1995 - * - *********************************************************************/ -class Radius -{ - var $_ip_radius_server; // Radius server IP address - var $_shared_secret; // Shared secret with the radius server - var $_radius_suffix; // Radius suffix (default is ''); - var $_udp_timeout; // Timeout of the UDP connection in seconds (default value is 5) - var $_authentication_port; // Authentication port (default value is 1812) - var $_accounting_port; // Accounting port (default value is 1813) - var $_nas_ip_address; // NAS IP address - var $_nas_port; // NAS port - var $_encrypted_password; // Encrypted password, as described in the RFC 2865 - var $_user_ip_address; // Remote IP address of the user - var $_request_authenticator; // Request-Authenticator, 16 octets random number - var $_response_authenticator; // Request-Authenticator, 16 octets random number - var $_username; // Username to sent to the Radius server - var $_password; // Password to sent to the Radius server (clear password, must be encrypted) - var $_identifier_to_send; // Identifier field for the packet to be sent - var $_identifier_received; // Identifier field for the received packet - var $_radius_packet_to_send; // Radius packet code (1=Access-Request, 2=Access-Accept, 3=Access-Reject, 4=Accounting-Request, 5=Accounting-Response, 11=Access-Challenge, 12=Status-Server (experimental), 13=Status-Client (experimental), 255=Reserved - var $_radius_packet_received; // Radius packet code (1=Access-Request, 2=Access-Accept, 3=Access-Reject, 4=Accounting-Request, 5=Accounting-Response, 11=Access-Challenge, 12=Status-Server (experimental), 13=Status-Client (experimental), 255=Reserved - var $_attributes_to_send; // Radius attributes to send - var $_attributes_received; // Radius attributes received - var $_socket_to_server; // Socket connection - var $_debug_mode; // Debug mode flag - var $debug_text = []; // Debug messages - var $_attributes_info; // Attributes info array - var $_radius_packet_info; // Radius packet codes info array - var $_last_error_code; // Last error code - var $_last_error_message; // Last error message - - - /********************************************************************* - * - * Name: Radius - * short description: Radius class constructor - * - * Creation 2008-01-04 - * Update 2023-12-20 - * @version v.1.2.3 - * @author SysCo/al - * @updated https://github.com/flaviojunior1995 - * @param string ip address of the radius server - * @param string shared secret with the radius server - * @param string radius domain name suffix (default is empty) - * @param integer UDP timeout (default is 5) - * @param integer authentication port - * @param integer accounting port - * @return NULL - *********************************************************************/ - public function __construct($ip_radius_server = '127.0.0.1', $shared_secret = '', $radius_suffix = '', $udp_timeout = 5, $authentication_port = 1812, $accounting_port = 1813) - { - $this->_radius_packet_info[1] = 'Access-Request'; - $this->_radius_packet_info[2] = 'Access-Accept'; - $this->_radius_packet_info[3] = 'Access-Reject'; - $this->_radius_packet_info[4] = 'Accounting-Request'; - $this->_radius_packet_info[5] = 'Accounting-Response'; - $this->_radius_packet_info[11] = 'Access-Challenge'; - $this->_radius_packet_info[12] = 'Status-Server (experimental)'; - $this->_radius_packet_info[13] = 'Status-Client (experimental)'; - $this->_radius_packet_info[255] = 'Reserved'; - - $this->_attributes_info[1] = array('User-Name', 'S'); - $this->_attributes_info[2] = array('User-Password', 'S'); - $this->_attributes_info[3] = array('CHAP-Password', 'S'); // Type (1) / Length (1) / CHAP Ident (1) / String - $this->_attributes_info[4] = array('NAS-IP-Address', 'A'); - $this->_attributes_info[5] = array('NAS-Port', 'I'); - $this->_attributes_info[6] = array('Service-Type', 'I'); - $this->_attributes_info[7] = array('Framed-Protocol', 'I'); - $this->_attributes_info[8] = array('Framed-IP-Address', 'A'); - $this->_attributes_info[9] = array('Framed-IP-Netmask', 'A'); - $this->_attributes_info[10] = array('Framed-Routing', 'I'); - $this->_attributes_info[11] = array('Filter-Id', 'T'); - $this->_attributes_info[12] = array('Framed-MTU', 'I'); - $this->_attributes_info[13] = array('Framed-Compression', 'I'); - $this->_attributes_info[14] = array('Login-IP-Host', 'A'); - $this->_attributes_info[15] = array('Login-service', 'I'); - $this->_attributes_info[16] = array('Login-TCP-Port', 'I'); - $this->_attributes_info[17] = array('(unassigned)', ''); - $this->_attributes_info[18] = array('Reply-Message', 'T'); - $this->_attributes_info[19] = array('Callback-Number', 'S'); - $this->_attributes_info[20] = array('Callback-Id', 'S'); - $this->_attributes_info[21] = array('(unassigned)', ''); - $this->_attributes_info[22] = array('Framed-Route', 'T'); - $this->_attributes_info[23] = array('Framed-IPX-Network', 'I'); - $this->_attributes_info[24] = array('State', 'S'); - $this->_attributes_info[25] = array('Class', 'S'); - $this->_attributes_info[26] = array('Vendor-Specific', 'S'); // Type (1) / Length (1) / Vendor-Id (4) / Vendor type (1) / Vendor length (1) / Attribute-Specific... - $this->_attributes_info[27] = array('Session-Timeout', 'I'); - $this->_attributes_info[28] = array('Idle-Timeout', 'I'); - $this->_attributes_info[29] = array('Termination-Action', 'I'); - $this->_attributes_info[30] = array('Called-Station-Id', 'S'); - $this->_attributes_info[31] = array('Calling-Station-Id', 'S'); - $this->_attributes_info[32] = array('NAS-Identifier', 'S'); - $this->_attributes_info[33] = array('Proxy-State', 'S'); - $this->_attributes_info[34] = array('Login-LAT-Service', 'S'); - $this->_attributes_info[35] = array('Login-LAT-Node', 'S'); - $this->_attributes_info[36] = array('Login-LAT-Group', 'S'); - $this->_attributes_info[37] = array('Framed-AppleTalk-Link', 'I'); - $this->_attributes_info[38] = array('Framed-AppleTalk-Network', 'I'); - $this->_attributes_info[39] = array('Framed-AppleTalk-Zone', 'S'); - $this->_attributes_info[60] = array('CHAP-Challenge', 'S'); - $this->_attributes_info[61] = array('NAS-Port-Type', 'I'); - $this->_attributes_info[62] = array('Port-Limit', 'I'); - $this->_attributes_info[63] = array('Login-LAT-Port', 'S'); - $this->_attributes_info[76] = array('Prompt', 'I'); - - $this->_identifier_to_send = 0; - $this->_user_ip_address = (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0'); - - $this->GenerateRequestAuthenticator(); - $this->SetIpRadiusServer($ip_radius_server); - $this->SetSharedSecret($shared_secret); - $this->SetAuthenticationPort($authentication_port); - $this->SetAccountingPort($accounting_port); - $this->SetRadiusSuffix($radius_suffix); - $this->SetUdpTimeout($udp_timeout); - $this->SetUsername(); - $this->SetPassword(); - $this->SetNasIpAddress(); - $this->SetNasPort(); - - $this->ClearLastError(); - $this->ClearDataToSend(); - $this->ClearDataReceived(); - } - - - function GetNextIdentifier() - { - $this->_identifier_to_send = (($this->_identifier_to_send + 1) % 256); - return $this->_identifier_to_send; - } - - - function GenerateRequestAuthenticator() - { - $this->_request_authenticator = ''; - for ($ra_loop = 0; $ra_loop <= 15; $ra_loop++) - { - $this->_request_authenticator .= chr(rand(1, 255)); - } - } - - - function GetRequestAuthenticator() - { - return $this->_request_authenticator; - } - - - function GetLastError() - { - if (0 < $this->_last_error_code) - { - return $this->_last_error_message.' ('.$this->_last_error_code.')'; - } else - { - return ''; - } - } - - - function ClearDataToSend() - { - $this->_radius_packet_to_send = 0; - $this->_attributes_to_send = NULL; - } - - - function ClearDataReceived() - { - $this->_radius_packet_received = 0; - $this->_attributes_received = NULL; - } - - - function SetPacketCodeToSend($packet_code) - { - $this->_radius_packet_to_send = $packet_code; - } - - - function SetDebugMode($debug_mode) - { - $this->_debug_mode = (TRUE === $debug_mode); - } - - - function SetIpRadiusServer($ip_radius_server) - { - $this->_ip_radius_server = gethostbyname($ip_radius_server); - } - - - function SetSharedSecret($shared_secret) - { - $this->_shared_secret = $shared_secret; - } - - - function SetRadiusSuffix($radius_suffix) - { - $this->_radius_suffix = $radius_suffix; - } - - - function SetUsername($username = '') - { - $temp_username = $username; - if (false === strpos($temp_username, '@')) - { - $temp_username .= $this->_radius_suffix; - } - - $this->_username = $temp_username; - $this->SetAttribute(1, $this->_username); - } - - - function SetPassword($password = '') - { - $this->_password = $password; - $encrypted_password = ''; - $padded_password = $password; - - if (0 != (strlen($password) % 16)) - { - $padded_password .= str_repeat(chr(0), (16 - strlen($password) % 16)); - } - - $previous_result = $this->_request_authenticator; - - for ($full_loop = 0; $full_loop < (strlen($padded_password) / 16); $full_loop++) - { - $xor_value = md5($this->_shared_secret.$previous_result); - - $previous_result = ''; - for ($xor_loop = 0; $xor_loop <= 15; $xor_loop++) - { - $value1 = ord(substr($padded_password, ($full_loop * 16) + $xor_loop, 1)); - $value2 = hexdec(substr($xor_value, 2 * $xor_loop, 2)); - $xor_result = $value1^$value2; - $previous_result .= chr($xor_result); - } - $encrypted_password .= $previous_result; - } - - $this->_encrypted_password = $encrypted_password; - $this->SetAttribute(2, $this->_encrypted_password); - } - - - function SetNasIPAddress($nas_ip_address = '') - { - if (0 < strlen($nas_ip_address)) - { - $this->_nas_ip_address = gethostbyname($nas_ip_address); - } else - { - $this->_nas_ip_address = gethostbyname(isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '0.0.0.0'); - } - $this->SetAttribute(4, $this->_nas_ip_address); - } - - - function SetNasPort($nas_port = 0) - { - $this->_nas_port = intval($nas_port); - $this->SetAttribute(5, $this->_nas_port); - } - - - function SetUdpTimeout($udp_timeout = 5) - { - if (intval($udp_timeout) > 0) - { - $this->_udp_timeout = intval($udp_timeout); - } - } - - - function ClearLastError() - { - $this->_last_error_code = 0; - $this->_last_error_message = ''; - } - - - function SetAuthenticationPort($authentication_port) - { - if ((intval($authentication_port) > 0) && (intval($authentication_port) < 65536)) - { - $this->_authentication_port = intval($authentication_port); - } - } - - - function SetAccountingPort($accounting_port) - { - if ((intval($accounting_port) > 0) && (intval($accounting_port) < 65536)) - { - $this->_accounting_port = intval($accounting_port); - } - } - - - function GetReceivedPacket() - { - return $this->_radius_packet_received; - } - - - function GetReceivedAttributes() - { - return $this->_attributes_received; - } - - - function GetReadableReceivedAttributes() - { - $readable_attributes = ''; - if (isset($this->_attributes_received)) - { - foreach ($this->_attributes_received as $one_received_attribute) - { - $attributes_info = $this->GetAttributesInfo($one_received_attribute[0]); - $readable_attributes .= $attributes_info[0].": "; - if (26 == $one_received_attribute[0]) - { - $vendor_array = $this->DecodeVendorSpecificContent($one_received_attribute[1]); - foreach ($vendor_array as $vendor_one) - { - $readable_attributes .= 'Vendor-Id: '.$vendor_one[0].", Vendor-type: ".$vendor_one[1].", Attribute-specific: ".$vendor_one[2]; - } - } else - { - $readable_attributes .= $one_received_attribute[1]; - } - $readable_attributes .= "
\n"; - } - } - return $readable_attributes; - } - - - function GetAttribute($attribute_type) - { - $attribute_value = NULL; - foreach ($this->_attributes_received as $one_received_attribute) - { - if (intval($attribute_type) == $one_received_attribute[0]) - { - $attribute_value = $one_received_attribute[1]; - break; - } - } - return $attribute_value; - } - - - function GetRadiusPacketInfo($info_index) - { - if (isset($this->_radius_packet_info[intval($info_index)])) - { - return $this->_radius_packet_info[intval($info_index)]; - } else - { - return ''; - } - } - - - function GetAttributesInfo($info_index) - { - if (isset($this->_attributes_info[intval($info_index)])) - { - return $this->_attributes_info[intval($info_index)]; - } else - { - return array('', ''); - } - } - - - function DebugInfo($debug_info) - { - if ($this->_debug_mode) - { - //save debugging - $this->debug_text[] = date('Y-m-d H:i:s').' DEBUG: '.$debug_info; - } - } - - - function SetAttribute($type, $value) - { - $attribute_index = -1; - $attribute_count = count((array)$this->_attributes_to_send); - for ($attributes_loop = 0; $attributes_loop < $attribute_count; $attributes_loop++) - { - if ($type == ord(substr($this->_attributes_to_send[$attributes_loop], 0, 1))) - { - $attribute_index = $attributes_loop; - break; - } - } - - $temp_attribute = NULL; - - if (isset($this->_attributes_info[$type])) - { - switch ($this->_attributes_info[$type][1]) - { - case 'T': // Text, 1-253 octets containing UTF-8 encoded ISO 10646 characters (RFC 2279). - $temp_attribute = chr($type).chr(2 + strlen($value)).$value; - break; - case 'S': // String, 1-253 octets containing binary data (values 0 through 255 decimal, inclusive). - $temp_attribute = chr($type).chr(2 + strlen($value)).$value; - break; - case 'A': // Address, 32 bit value, most significant octet first. - $ip_array = pf_explode(".", $value); - $temp_attribute = chr($type).chr(6).chr($ip_array[0]).chr($ip_array[1]).chr($ip_array[2]).chr($ip_array[3]); - break; - case 'I': // Integer, 32 bit unsigned value, most significant octet first. - $temp_attribute = chr($type).chr(6).chr($value / 256 * 256 * 256 % 256).chr($value / 256 * 256 % 256). chr($value * 256 / 256 % 256 ) .chr($value % 256); - break; - case 'D': // Time, 32 bit unsigned value, most significant octet first -- seconds since 00:00:00 UTC, January 1, 1970. (not used in this RFC) - $temp_attribute = NULL; - break; - default: - $temp_attribute = NULL; - } - } - - if ($attribute_index > -1) - { - $this->_attributes_to_send[$attribute_index] = $temp_attribute; - $additional_debug = 'Modified'; - } else - { - $this->_attributes_to_send[] = $temp_attribute; - $additional_debug = 'Added'; - } - $attribute_info = $this->GetAttributesInfo($type); - $this->DebugInfo($additional_debug.' Attribute '.$type.' ('.$attribute_info[0].'), format '.$attribute_info[1].', value '.$value.''); - } - - - function DecodeAttribute($attribute_raw_value, $attribute_format) - { - $attribute_value = NULL; - - if (isset($this->_attributes_info[$attribute_format])) - { - switch ($this->_attributes_info[$attribute_format][1]) - { - case 'T': // Text, 1-253 octets containing UTF-8 encoded ISO 10646 characters (RFC 2279). - $attribute_value = $attribute_raw_value; - break; - case 'S': // String, 1-253 octets containing binary data (values 0 through 255 decimal, inclusive). - $attribute_value = $attribute_raw_value; - break; - case 'A': // Address, 32 bit value, most significant octet first. - $attribute_value = ord(substr($attribute_raw_value, 0, 1)).'.'.ord(substr($attribute_raw_value, 1, 1)).'.'.ord(substr($attribute_raw_value, 2, 1)).'.'.ord(substr($attribute_raw_value, 3, 1)); - break; - case 'I': // Integer, 32 bit unsigned value, most significant octet first. - $attribute_value = (ord(substr($attribute_raw_value, 0, 1)) * 256 * 256 * 256) + (ord(substr($attribute_raw_value, 1, 1)) * 256 * 256) + (ord(substr($attribute_raw_value, 2, 1)) * 256) + ord(substr($attribute_raw_value, 3, 1)); - break; - case 'D': // Time, 32 bit unsigned value, most significant octet first -- seconds since 00:00:00 UTC, January 1, 1970. (not used in this RFC) - $attribute_value = NULL; - break; - default: - $attribute_value = NULL; - } - } - return $attribute_value; - } - - - /********************************************************************* - * Array returned: array(array(Vendor-Id1, Vendor type1, Attribute-Specific1), ..., array(Vendor-IdN, Vendor typeN, Attribute-SpecificN) - *********************************************************************/ - function DecodeVendorSpecificContent($vendor_specific_raw_value) - { - $result = array(); - $offset_in_raw = 0; - $vendor_id = (ord(substr($vendor_specific_raw_value, 0, 1)) * 256 * 256 * 256) + (ord(substr($vendor_specific_raw_value, 1, 1)) * 256 * 256) + (ord(substr($vendor_specific_raw_value, 2, 1)) * 256) + ord(substr($vendor_specific_raw_value, 3, 1)); - $offset_in_raw += 4; - while ($offset_in_raw < strlen($vendor_specific_raw_value)) - { - $vendor_type = (ord(substr($vendor_specific_raw_value, 0 + $offset_in_raw, 1))); - $vendor_length = (ord(substr($vendor_specific_raw_value, 1 + $offset_in_raw, 1))); - $attribute_specific = substr($vendor_specific_raw_value, 2 + $offset_in_raw, $vendor_length); - $result[] = array($vendor_id, $vendor_type, $attribute_specific); - $offset_in_raw += ($vendor_length); - } - - return $result; - } - - - /* - * Function : AccessRequest - * - * Return TRUE if Access-Request is accepted, FALSE otherwise - */ - function AccessRequest($username = '', $password = '', $udp_timeout = 0, $state = NULL) - { - $this->ClearDataReceived(); - $this->ClearLastError(); - - $this->SetPacketCodeToSend(1); // Access-Request - - if (0 < strlen($username)) - { - $this->SetUsername($username); - } - - if (0 < strlen($password)) - { - $this->SetPassword($password); - } - - if ($state !== NULL) - { - $this->SetAttribute(24, $state); - } else - { - $this->SetAttribute(6, 1); // 1=Login - } - - if (intval($udp_timeout) > 0) - { - $this->SetUdpTimeout($udp_timeout); - } - - $attributes_content = ''; - $attribute_count1 = count((array)$this->_attributes_to_send); - for ($attributes_loop = 0; $attributes_loop < $attribute_count1; $attributes_loop++) - { - $attributes_content .= $this->_attributes_to_send[$attributes_loop]; - } - - $packet_length = 4; // Radius packet code + Identifier + Length high + Length low - $packet_length += strlen($this->_request_authenticator); // Request-Authenticator - $packet_length += strlen($attributes_content); // Attributes - - $packet_data = chr($this->_radius_packet_to_send); - $packet_data .= chr($this->GetNextIdentifier()); - $packet_data .= chr(intval($packet_length / 256)); - $packet_data .= chr(intval($packet_length % 256)); - $packet_data .= $this->_request_authenticator; - $packet_data .= $attributes_content; - - $_socket_to_server = socket_create(AF_INET, SOCK_DGRAM, 17); // UDP packet = 17 - - if ($_socket_to_server === FALSE) - { - $this->_last_error_code = socket_last_error(); - $this->_last_error_message = socket_strerror($this->_last_error_code); - } elseif (FALSE === socket_connect($_socket_to_server, $this->_ip_radius_server, $this->_authentication_port)) - { - $this->_last_error_code = socket_last_error(); - $this->_last_error_message = socket_strerror($this->_last_error_code); - } elseif (FALSE === socket_write($_socket_to_server, $packet_data, $packet_length)) - { - $this->_last_error_code = socket_last_error(); - $this->_last_error_message = socket_strerror($this->_last_error_code); - } else - { - $this->DebugInfo('Packet type '.$this->_radius_packet_to_send.' ('.$this->GetRadiusPacketInfo($this->_radius_packet_to_send).')'.' sent'); - if ($this->_debug_mode) - { - $readable_attributes = ''; - foreach ($this->_attributes_to_send as $one_attribute_to_send) - { - $attribute_info = $this->GetAttributesInfo(ord(substr($one_attribute_to_send, 0, 1))); - $this->DebugInfo('Attribute '.ord(substr($one_attribute_to_send, 0, 1)).' ('.$attribute_info[0].'), length '.(ord(substr($one_attribute_to_send, 1, 1)) - 2).', format '.$attribute_info[1].', value '.$this->DecodeAttribute(substr($one_attribute_to_send, 2), ord(substr($one_attribute_to_send, 0, 1))).''); - } - } - $read_socket_array = array($_socket_to_server); - $write_socket_array = NULL; - $except_socket_array = NULL; - - $received_packet = chr(0); - - if (!(FALSE === socket_select($read_socket_array, $write_socket_array, $except_socket_array, $this->_udp_timeout))) - { - if (in_array($_socket_to_server, $read_socket_array)) - { - if (FALSE === ($received_packet = @socket_read($_socket_to_server, 1024))) { - // @ used, than no error is displayed if the connection is closed by the remote host - { - $received_packet = chr(0); - } - $this->_last_error_code = socket_last_error(); - $this->_last_error_message = socket_strerror($this->_last_error_code); - } else - { - socket_close($_socket_to_server); - } - } - } else - { - socket_close($_socket_to_server); - } - } - - $this->_radius_packet_received = intval(ord(substr($received_packet, 0, 1))); - - $this->DebugInfo('Packet type '.$this->_radius_packet_received.' ('.$this->GetRadiusPacketInfo($this->_radius_packet_received).')'.' received'); - - if ($this->_radius_packet_received > 0) - { - $this->_identifier_received = intval(ord(substr($received_packet, 1, 1))); - $packet_length = (intval(ord(substr($received_packet, 2, 1))) * 256) + (intval(ord(substr($received_packet, 3, 1)))); - $this->_response_authenticator = substr($received_packet, 4, 16); - $attributes_content = substr($received_packet, 20, ($packet_length - 4 - 16)); - while (strlen($attributes_content) > 2) - { - $attribute_type = intval(ord(substr($attributes_content, 0, 1))); - $attribute_length = intval(ord(substr($attributes_content, 1, 1))); - $attribute_raw_value = substr($attributes_content, 2, $attribute_length - 2); - $attributes_content = substr($attributes_content, $attribute_length); - - $attribute_value = $this->DecodeAttribute($attribute_raw_value, $attribute_type); - - $attribute_info = $this->GetAttributesInfo($attribute_type); - if (26 == $attribute_type) - { - $vendor_array = $this->DecodeVendorSpecificContent($attribute_value); - foreach ($vendor_array as $vendor_one) - { - $this->DebugInfo('Attribute '.$attribute_type.' ('.$attribute_info[0].'), length '.($attribute_length - 2).', format '.$attribute_info[1].', Vendor-Id: '.$vendor_one[0].", Vendor-type: ".$vendor_one[1].", Attribute-specific: ".$vendor_one[2]); - } - } else - { - $this->DebugInfo('Attribute '.$attribute_type.' ('.$attribute_info[0].'), length '.($attribute_length - 2).', format '.$attribute_info[1].', value '.$attribute_value.''); - } - - $this->_attributes_received[] = array($attribute_type, $attribute_value); - } - } - - return (2 == ($this->_radius_packet_received)); - } -} diff --git a/functions/classes/class.Result.php b/functions/classes/class.Result.php index b31c13d0d..d9f9adc5a 100644 --- a/functions/classes/class.Result.php +++ b/functions/classes/class.Result.php @@ -282,7 +282,7 @@ public function throw_exception ($code, $exception) { */ protected function set_location_header ($location) { # validate location header - if(!preg_match('/^[a-zA-Z0-9\-\_\/.]+$/i',$location)) { + if(!preg_match('/^[a-zA-Z0-9\-\_\/.]+$/i',(string) $location)) { $this->throw_exception (500, "Invalid location header"); } # set diff --git a/functions/classes/class.Rewrite.php b/functions/classes/class.Rewrite.php index b3896b90b..8ab67dfad 100644 --- a/functions/classes/class.Rewrite.php +++ b/functions/classes/class.Rewrite.php @@ -50,7 +50,7 @@ class Rewrite { * * @var array */ - private $uri_passthroughs = array('app', '?switch=back'); + private $uri_passthroughs = ['app', '?switch=back']; /** * URI parts from $_SERVER['REQUEST_URI'] @@ -59,14 +59,14 @@ class Rewrite { * * @var array */ - private $uri_parts = array(); + private $uri_parts = []; /** * Final GET params to be returned * * @var array */ - private $get_params = array(); + private $get_params = []; @@ -131,12 +131,12 @@ public function is_api () { */ private function process_request_uri () { // ignore for direct access - if(strpos($_SERVER['REQUEST_URI'], "index.php")===false) { + if(strpos((string) $_SERVER['REQUEST_URI'], "index.php")===false) { if(BASE!="/") { - $this->uri_parts = array_values(array_filter(pf_explode("/", str_replace(BASE, "", $_SERVER['REQUEST_URI'])))); + $this->uri_parts = array_values(array_filter(explode("/", str_replace((string) BASE, "", (string) $_SERVER['REQUEST_URI'])))); } else { - $this->uri_parts = array_values(array_filter(pf_explode("/", $_SERVER['REQUEST_URI']))); + $this->uri_parts = array_values(array_filter(explode("/", (string) $_SERVER['REQUEST_URI']))); } // urldecode uri_parts @@ -178,7 +178,7 @@ private function create_get_params_ui () { $this->get_params = $_GET; } else { foreach ($this->uri_parts as $k=>$l) { - if (strncmp($l, '?', 1) == 0) continue; //skip qsa + if (strncmp((string) $l, '?', 1) == 0) continue; //skip qsa switch ($k) { case 0 : $this->get_params['page'] = $l; break; case 1 : $this->get_params['section'] = $l; break; @@ -207,8 +207,8 @@ private function create_get_params_ui () { * @return void */ private function append_qsa () { - if(strpos($_SERVER['REQUEST_URI'], "?")!==false) { - $parts = pf_explode("?", $_SERVER['REQUEST_URI']); + if(strpos((string) $_SERVER['REQUEST_URI'], "?")!==false) { + $parts = explode("?", (string) $_SERVER['REQUEST_URI']); $parts = $parts[1]; // parse parse_str ($parts, $out); @@ -260,7 +260,7 @@ private function create_get_params_api () { // create if(sizeof($this->uri_parts)>0) { foreach ($this->uri_parts as $k=>$l) { - if (strncmp($l, '?', 1) == 0) continue; //skip qsa + if (strncmp((string) $l, '?', 1) == 0) continue; //skip qsa switch ($k) { case 0 : $this->get_params['app_id'] = $l; break; case 1 : $this->get_params['controller'] = $l; break; diff --git a/functions/classes/class.SNMP.php b/functions/classes/class.SNMP.php index 9fc4f8ccc..c5b96dd9c 100644 --- a/functions/classes/class.SNMP.php +++ b/functions/classes/class.SNMP.php @@ -591,7 +591,7 @@ private function get_arp_table () { $n++; }; - $interface_indexes = array(); // to avoid fetching if multiple times + $interface_indexes = []; // to avoid fetching if multiple times // fetch interface name $n=0; foreach ($res3 as $r) { @@ -766,10 +766,10 @@ private function get_vlan_table () { // parse result foreach ($res1 as $k=>$r) { // set number - $k = str_replace($this->snmp_oids['CISCO-VTP-MIB::vtpVlanName'].'.1.', "", $k); - $k = array_pop(pf_explode(".", $k)); + $k = str_replace($this->snmp_oids['CISCO-VTP-MIB::vtpVlanName'].'.1.', "", (string) $k); + $k = array_pop(explode(".", $k)); // set value - $r = trim(str_replace("\"","",substr($r, strpos($r, ":")+2))); + $r = trim(str_replace("\"","",substr((string) $r, strpos((string) $r, ":")+2))); $res[$k] = $r; } @@ -790,7 +790,7 @@ private function decode_mplsVpnVrfName($oid) { // the first octet is the string length, and subsequent octets are // the ASCII codes of each character. // For example, “vpn1” is represented as 4.118.112.110.49. - $a = array_values(array_filter(pf_explode('.', $oid))); + $a = array_values(array_filter(explode('.', $oid))); if (($a[0]+1) != sizeof($a)) return $oid; @@ -821,8 +821,8 @@ private function get_vrf_table () { // parse results foreach ($res1 as $k=>$r) { // set name - $k = str_replace($this->snmp_oids['MPLS-VPN-MIB::mplsVpnVrfRouteDistinguisher'].'.', "", $k); - $k = str_replace("\"", "", $k); + $k = str_replace($this->snmp_oids['MPLS-VPN-MIB::mplsVpnVrfRouteDistinguisher'].'.', "", (string) $k); + $k = str_replace("\"", "", (string) $k); $k = $this->decode_mplsVpnVrfName($k); // set rd $r = $this->parse_snmp_result_value ($r); @@ -830,8 +830,8 @@ private function get_vrf_table () { } foreach ($res2 as $k=>$r) { // set name - $k = str_replace($this->snmp_oids['MPLS-VPN-MIB::mplsVpnVrfDescription'].'.', "", $k); - $k = str_replace("\"", "", $k); + $k = str_replace($this->snmp_oids['MPLS-VPN-MIB::mplsVpnVrfDescription'].'.', "", (string) $k); + $k = str_replace("\"", "", (string) $k); $k = $this->decode_mplsVpnVrfName($k); // set descr $r = $this->parse_snmp_result_value ($r); @@ -882,16 +882,16 @@ private function format_snmp_mac_value ($input) { $mac_parts = []; list($type, $mac) = $this->extract_type_and_value($input); - if (strlen($mac)==6) { + if (strlen((string) $mac)==6) { // 6 byte binary string (Cisco bug?), try unpacking to hex string. - $mac = unpack('H*mac', $mac)['mac']; + $mac = unpack('H*mac', (string) $mac)['mac']; } - if (preg_match('/^[0-9a-fA-F]{12}$/',$mac)) { + if (preg_match('/^[0-9a-fA-F]{12}$/',(string) $mac)) { // hex string "0011223344AA" - $mac_parts = str_split($mac, 2); + $mac_parts = str_split((string) $mac, 2); - } elseif (preg_match('/^([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})$/', $mac, $matches)) { + } elseif (preg_match('/^([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})[ :-]([0-9a-fA-F]{1,2})$/', (string) $mac, $matches)) { // separated MAC address, 0:1b:c:55:7 unset($matches[0]); foreach($matches as $i => $v) diff --git a/functions/classes/class.Scan.php b/functions/classes/class.Scan.php index cd5118eb0..86a75ec3b 100644 --- a/functions/classes/class.Scan.php +++ b/functions/classes/class.Scan.php @@ -193,7 +193,7 @@ public function reset_scan_method ($method) { //check if(!in_array($method, $possible)) { //die or print? - if($this->icmp_exit) { die(json_encode(array("status"=>1, "error"=>_("Invalid scan method.")))); } + if($this->icmp_exit) { die(json_encode(["status"=>1, "error"=>_("Invalid scan method.")])); } else { $this->Result->show("danger", _("Invalid scan method."), true); } } //ok @@ -290,10 +290,18 @@ public function ping_address ($address, $count=1, $timeout = 1) { # make sure it is in right format $address = $this->transform_address ($address, "dotted"); - # set method name variable - $ping_method = "ping_address_method_".$this->icmp_type; + # ping with selected method - return $this->{$ping_method} ($address); + switch ($this->icmp_type) { + case "ping": + return $this->ping_address_method_ping($address); + case "pear": + return $this->ping_address_method_pear($address); + case "fping": + return $this->ping_address_method_fping($address); + default: + return $this->ping_address_method_none($address); + } } /** @@ -339,7 +347,7 @@ protected function ping_address_method_ping($address) { # for IPv6 remove wait if ($this->identify_address($address) == "IPv6") { - $cmd = pf_explode(" ", $cmd); + $cmd = explode(" ", $cmd); unset($cmd[3], $cmd[4]); $cmd = implode(" ", $cmd); } @@ -364,7 +372,7 @@ protected function ping_address_method_ping($address) { */ protected function ping_address_method_pear ($address) { # we need pear ping package - require_once(dirname(__FILE__) . '/../../functions/PEAR/Net/Ping.php'); + require_once __DIR__ . '/../PEAR/Net/Ping.php'; $ping = Net_Ping::factory(); # ipv6 not supported @@ -388,7 +396,7 @@ protected function ping_address_method_pear ($address) { } else { //set count and timeout - $ping->setArgs(array('count' => $this->icmp_timeout, 'timeout' => $this->icmp_timeout)); + $ping->setArgs(['count' => $this->icmp_timeout, 'timeout' => $this->icmp_timeout]); //execute $ping_response = $ping->ping($address); //check response for error @@ -399,7 +407,7 @@ protected function ping_address_method_pear ($address) { //all good if($ping_response->_transmitted == $ping_response->_received) { $result['code'] = 0; - $this->rtt = "RTT: ". strstr($ping_response->_round_trip['avg'], ".", true); + $this->rtt = "RTT: ". strstr((string) $ping_response->_round_trip['avg'], ".", true); } //ping loss elseif($ping_response->_received == 0) { @@ -467,7 +475,7 @@ public function ping_address_method_fping($address) { */ private function save_fping_rtt ($line) { // 173.192.112.30 : xmt/rcv/%loss = 1/1/0%, min/avg/max = 160/160/160 - $tmp = pf_explode(" ",$line); + $tmp = explode(" ",(string) $line); # save rtt if (is_array($tmp) && isset($tmp[7])) @@ -492,9 +500,9 @@ private function save_fping_rtt ($line) { */ public function ping_address_method_fping_subnet ($subnet_cidr, $return_result = false) { $this->ping_verify_path ($this->fping_path); - $out = array(); + $out = []; # set command - $cmd = sprintf("%s -c %s -t %s -Agq %s 2>&1", escapeshellcmd($this->fping_path), escapeshellarg($this->icmp_count), escapeshellarg($this->icmp_timeout * 1000), escapeshellarg($subnet_cidr)); + $cmd = sprintf("%s -c %s -t %s -Agq %s 2>&1", escapeshellcmd($this->fping_path), escapeshellarg($this->icmp_count), escapeshellarg($this->icmp_timeout * 1000), escapeshellarg((string) $subnet_cidr)); # execute command, return $retval exec($cmd, $output, $retval); @@ -507,7 +515,7 @@ public function ping_address_method_fping_subnet ($subnet_cidr, $return_result = if (!$match || $matches[1] == 100) continue; - $tmp = pf_explode(" ", $line); + $tmp = explode(" ", $line); $out[] = $tmp[0]; } } @@ -551,14 +559,14 @@ private function ping_verify_path ($path) { * * @access public * @param mixed $code - * @return void + * @return string */ public function ping_exit_explain ($code) { # fetch explain codes $explain_codes = $this->ping_set_exit_code_explains (); # return code - return isset($explain_codes[$code]) ? $explain_codes[$code] : false; + return isset($explain_codes[$code]) ? $explain_codes[$code] : ""; } /** @@ -569,7 +577,7 @@ public function ping_exit_explain ($code) { * extend if needed for future scripts * * @access public - * @return void + * @return array */ public function ping_set_exit_code_explains () { $explain_codes[0] = "SUCCESS"; @@ -605,7 +613,7 @@ public function ping_update_lastseen ($id, $datetime = null, $mac = null) { # set datetime $datetime = is_null($datetime) ? date("Y-m-d H:i:s") : $datetime; # execute - $update_ipaddress = array("id"=>$id, "lastSeen"=>$datetime); + $update_ipaddress = ["id"=>$id, "lastSeen"=>$datetime]; if (!is_null($mac)) { $update_ipaddress["mac"] = $mac; } @@ -629,7 +637,7 @@ public function ping_update_scanagent_checktime ($id, $datetime = false) { // set date $datetime = $datetime===false ? date("Y-m-d H:i:s") : $datetime; # execute - try { $this->Database->updateObject("scanAgents", array("id"=>$id, "last_access"=>$datetime), "id"); } + try { $this->Database->updateObject("scanAgents", ["id"=>$id, "last_access"=>$datetime], "id"); } catch (Exception $e) { } } @@ -646,7 +654,7 @@ public function update_subnet_scantime ($subnet_id, $datetime = false) { // set date $datetime = $datetime===false ? date("Y-m-d H:i:s") : $datetime; // update - try { $this->Database->updateObject("subnets", array("id"=>$subnet_id, "lastScan"=>$datetime), "id"); } + try { $this->Database->updateObject("subnets", ["id"=>$subnet_id, "lastScan"=>$datetime], "id"); } catch (Exception $e) {} } @@ -662,7 +670,7 @@ public function update_subnet_discoverytime ($subnet_id, $datetime = false) { // set date $datetime = $datetime===false ? date("Y-m-d H:i:s") : $datetime; // update - try { $this->Database->updateObject("subnets", array("id"=>$subnet_id, "lastDiscovery"=>$datetime), "id"); } + try { $this->Database->updateObject("subnets", ["id"=>$subnet_id, "lastDiscovery"=>$datetime], "id"); } catch (Exception $e) {} } @@ -682,7 +690,7 @@ public function update_address_tag ($address_id, $tag_id = 2, $old_tag_id = null if ($last_seen_date!==false && !is_null($last_seen_date) && strlen($last_seen_date)>2 && $last_seen_date!="0000-00-00 00:00:00" && $last_seen_date!="1970-01-01 00:00:01" && $last_seen_date!="1970-01-01 01:00:00") { // don't update reserved to offline if (!($tag_id==1 && $old_tag_id==3)) { - try { $this->Database->updateObject("ipaddresses", array("id"=>$address_id, "state"=>$tag_id), "id"); } + try { $this->Database->updateObject("ipaddresses", ["id"=>$address_id, "state"=>$tag_id], "id"); } catch (Exception $e) { return false; } @@ -712,7 +720,7 @@ public function update_address_tag ($address_id, $tag_id = 2, $old_tag_id = null */ public function telnet_address ($address, $port) { # set all ports - $ports = pf_explode(",", str_replace(";",",",$port)); + $ports = explode(",", str_replace(";",",",(string) $port)); # default response is dead $retval = 1; //try each port until one is alive @@ -757,7 +765,7 @@ public function prepare_addresses_to_scan ($type, $subnet, $die = true) { # update addresses statuses elseif($type=="update") { return $this->prepare_addresses_to_update ($subnet); } # fail - else { die(json_encode(array("status"=>1, "error"=>_("Invalid scan type provided.")))); } + else { die(json_encode(["status"=>1, "error"=>_("Invalid scan type provided.")])); } } /** @@ -774,14 +782,14 @@ public function prepare_addresses_to_discover_subnetId ($subnetId, $die) { //subnet ID is provided, fetch subnet $subnet = $Subnets->fetch_subnet(null, $subnetId); if($subnet===false) { - if ($die) { die(json_encode(array("status"=>1, "error"=>_("Invalid subnet ID provided.")))); } - else { return array(); } + if ($die) { die(json_encode(["status"=>1, "error"=>_("Invalid subnet ID provided.")])); } + else { return []; } } // we should support only up to 4094 hosts! if($Subnets->max_hosts ($subnet)>4096 && php_sapi_name()!="cli") - if ($die) { die(json_encode(array("status"=>1, "error"=>_("Scanning from GUI is only available for subnets up to /20 or 4096 hosts!")))); } - else { return array(); } + if ($die) { die(json_encode(["status"=>1, "error"=>_("Scanning from GUI is only available for subnets up to /20 or 4096 hosts!")])); } + else { return []; } # set array of addresses to scan, exclude existing! $ip = $Subnets->get_all_possible_subnet_addresses ($subnet); @@ -791,8 +799,8 @@ public function prepare_addresses_to_discover_subnetId ($subnetId, $die) { //none to scan? if(sizeof($ip)==0) { - if ($die) { die(json_encode(array("status"=>1, "error"=>"Didn't find any address to scan!"))); } - else { return array(); } + if ($die) { die(json_encode(["status"=>1, "error"=>"Didn't find any address to scan!"])); } + else { return []; } } //return @@ -824,7 +832,7 @@ private function remove_existing_subnet_addresses ($ip, $subnetId) { $ip = array_values(@$ip); } //return - return is_array(@$ip) ? $ip : array(); + return is_array(@$ip) ? $ip : []; } /** @@ -841,7 +849,7 @@ public function prepare_addresses_to_discover_subnet ($subnet) { # result $ip = $Subnets->get_all_possible_subnet_addresses ($subnet); //none to scan? - if(sizeof($ip)==0) { die(json_encode(array("status"=>1, "error"=>_("Didn't find any address to scan!")))); } + if(sizeof($ip)==0) { die(json_encode(["status"=>1, "error"=>_("Didn't find any address to scan!")])); } //result return $ip; } @@ -869,7 +877,7 @@ public function prepare_addresses_to_update ($subnetId) { return $scan_addresses; } else { - return array(); + return []; } } } diff --git a/functions/classes/class.Sections.php b/functions/classes/class.Sections.php index c5a25c3d6..0a5d2ab05 100644 --- a/functions/classes/class.Sections.php +++ b/functions/classes/class.Sections.php @@ -116,7 +116,7 @@ private function section_add ($values) { $values['id'] = $this->lastInsertId; $this->Log->write( _("Sections create"), _("New section created").".
".$this->array_to_log($this->reformat_empty_array_fields ($values, "NULL")), 0); # write changelog - $this->Log->write_changelog('section', "add", 'success', array(), $values); + $this->Log->write_changelog('section', "add", 'success', [], $values); return true; } @@ -172,7 +172,7 @@ private function section_delete ($values) { if(is_array($section_subnets) && sizeof($section_subnets)>0) { foreach($section_subnets as $ss) { //delete subnet - $Subnets->modify_subnet("delete", array("id"=>$ss->id)); + $Subnets->modify_subnet("delete", ["id"=>$ss->id]); } } # delete all sections @@ -185,7 +185,7 @@ private function section_delete ($values) { } # write changelog - $this->Log->write_changelog('section', "delete", 'success', $old_section, array()); + $this->Log->write_changelog('section', "delete", 'success', $old_section, []); # log $this->Log->write( _("Section")." ".$old_section->name." "._("delete"), _("Section")." ".$old_section->name." "._("deleted").".
".$this->array_to_log($this->reformat_empty_array_fields((array) $old_section)), 0); return true; @@ -202,7 +202,7 @@ private function section_reorder ($order) { # update each section foreach($order as $key=>$o) { # execute - try { $this->Database->updateObject("sections", array("order"=>$o, "id"=>$key), "id"); } + try { $this->Database->updateObject("sections", ["order"=>$o, "id"=>$key], "id"); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); return false; @@ -269,13 +269,13 @@ public function fetch_section ($method, $value) { * @return array */ public function fetch_subsections ($sectionId) { - try { $subsections = $this->Database->getObjectsQuery('sections', "SELECT * FROM `sections` where `masterSection` = ?;", array($sectionId)); } + try { $subsections = $this->Database->getObjectsQuery('sections', "SELECT * FROM `sections` where `masterSection` = ?;", [$sectionId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; } # result - return sizeof($subsections)>0 ? $subsections : array(); + return sizeof($subsections)>0 ? $subsections : []; } /** @@ -294,10 +294,10 @@ private function get_all_section_and_subsection_ids ($id) { } } else { - $subsections_ids = array(); + $subsections_ids = []; } //array of section + all subsections - return array_filter(array_merge($subsections_ids, array($id))); + return array_filter(array_merge($subsections_ids, [$id])); } /** @@ -311,7 +311,7 @@ public function fetch_section_vlans ($sectionId) { # set query $query = "select distinct(`v`.`vlanId`),`v`.`name`,`v`.`number`,`v`.`domainId`, `v`.`description` from `subnets` as `s`,`vlans` as `v` where `s`.`sectionId` = ? and `s`.`vlanId`=`v`.`vlanId` order by `v`.`number` asc;"; # fetch - try { $vlans = $this->Database->getObjectsQuery('subnets', $query, array($sectionId)); } + try { $vlans = $this->Database->getObjectsQuery('subnets', $query, [$sectionId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -331,7 +331,7 @@ public function fetch_section_vrfs ($sectionId) { # set query $query = "select distinct(`v`.`vrfId`),`v`.`name`,`v`.`description` from `subnets` as `s`,`vrf` as `v` where `s`.`sectionId` = ? and `s`.`vrfId`=`v`.`vrfId` order by `v`.`name` asc;"; # fetch - try { $vrfs = $this->Database->getObjectsQuery('subnets', $query, array($sectionId)); } + try { $vrfs = $this->Database->getObjectsQuery('subnets', $query, [$sectionId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -353,7 +353,7 @@ public function fetch_section_domains ($sectionId) { $Admin = new Admin ($this->Database, false); $domains = $Admin->fetch_all_objects ("vlanDomains", "name"); # loop and check - $permitted = array(); + $permitted = []; foreach($domains as $d) { //default if($d->id==1) { @@ -361,7 +361,7 @@ public function fetch_section_domains ($sectionId) { } else { //array - if(in_array($sectionId, pf_explode(";", $d->permissions))) { + if(in_array($sectionId, explode(";", (string) $d->permissions))) { $permitted[] = $d->id; } } @@ -383,7 +383,7 @@ public function fetch_section_nameserver_sets ($sectionId) { $nameservers = $Admin->fetch_all_objects ("nameservers","name"); # loop and check if ($nameservers!==false) { - $permitted = array(); + $permitted = []; foreach($nameservers as $n) { //default if($n->id==1) { @@ -391,7 +391,7 @@ public function fetch_section_nameserver_sets ($sectionId) { } else { //array - if(in_array($sectionId, pf_explode(";", $n->permissions))) { + if(in_array($sectionId, explode(";", (string) $n->permissions))) { $permitted[] = $n->id; } } @@ -432,7 +432,7 @@ public function parse_section_permissions($permissions) { } } # return array of groups - return isset($out) ? $out : array(); + return isset($out) ? $out : []; } /** @@ -493,7 +493,7 @@ public function get_group_section_permissions ($gid, $name = true) { $sections = $this->fetch_all_sections(); # init result - $out = array(); + $out = []; # loop through sections and check if group_id in permissions if ($sections !== false) { @@ -536,7 +536,7 @@ public function get_group_section_permissions ($gid, $name = true) { * @return string */ public function print_section_subnets_table($User, $sectionId, $showSupernetOnly = false) { - $html = array(); + $html = []; # create csrf token $csrf_ffss = $User->Crypto->csrf_cookie ("create-if-not-exists", "find_free_section_subnets"); @@ -547,7 +547,7 @@ public function print_section_subnets_table($User, $sectionId, $showSupernetOnly # set hidden fields $hidden_fields = db_json_decode($User->settings->hiddenCustomFields, true) ? : ['subnets'=>null]; - $hidden_fields = is_array($hidden_fields['subnets']) ? $hidden_fields['subnets'] : array(); + $hidden_fields = is_array($hidden_fields['subnets']) ? $hidden_fields['subnets'] : []; # check permission $permission = $this->check_permission($User->user, $sectionId); @@ -583,7 +583,7 @@ public function print_section_subnets_table($User, $sectionId, $showSupernetOnly if(is_array($custom)) { foreach($custom as $field) { if(!in_array($field['name'], $hidden_fields)) { - $html[] = '
'; + $html[] = ''; } } } diff --git a/functions/classes/class.Session_DB.php b/functions/classes/class.Session_DB.php index a01bdccbb..986babd37 100644 --- a/functions/classes/class.Session_DB.php +++ b/functions/classes/class.Session_DB.php @@ -1,170 +1,148 @@ Database = $database; - // result - $this->Result = new Result (); - // set handler - $this->set_handler (); - } - - /** - * Register this class as session handler - * @method set_handler - */ - private function set_handler () { - // Set database as handler if requested - session_set_save_handler( - array($this, "_open"), - array($this, "_close"), - array($this, "_read"), - array($this, "_write"), - array($this, "_destroy"), - array($this, "_gc") - ); - // start - session_start (); - } - - /** - * Open connection - * @method _open - * @return bool - */ - public function _open () { - try { - $this->Database->connect(); - return true; - } - catch (Exception $e) { - $this->Result->show("danger", $e->getMessage(), false); - return false; - } - } - - /** - * Close connection - not needed - * @method _close - * @return void - */ - public function _close () { - return true; - } - - /** - * Check database for session data - * @method _read - * @param string $id - * @return string - */ - public function _read ($id) { - // check database for cookie - try { - // Note: Database->getObject() does not support non-numeric id's. Use findObject(). - $session = $this->Database->findObject ('php_sessions', 'id', $id); - // check - if (!is_object($session) || empty($session->data)) - return ""; - - return $session->data; - } - catch (Exception $e) { - $this->Result->show("danger", $e->getMessage(), false); - return ""; - } - } - - /** - * Save session data - * - * @method _write - * @param string $id - * @param string $data - * @return bool - */ - public function _write ($id, $data) { - // we need some data, otherwise don't save session - if(is_blank($data)) { - //return true; - } - // set insert / update values - $values = [ - "id" => $id, - "access" => time(), - "data" => $data, - "remote_ip" => $_SERVER['REMOTE_ADDR'] - ]; - // insert - try { - $this->Database->insertObject ("php_sessions", $values, false, true, false); - return true; - } - catch (Exception $e) { - $this->Result->show("danger", $e->getMessage(), false); - return false; - } - } - - /** - * Destroy session - * - * @method _destroy - * @param string $id - * @return bool - */ - public function _destroy ($id) { - try { - $this->Database->deleteObject ("php_sessions", $id); - return true; - } - catch (Exception $e) { - $this->Result->show("danger", $e->getMessage(), false); - return false; - } - } - - /** - * Garbage collection functions - * @method _gc - * @param int $max - * @return bool - */ - public function _gc ($max) { - try { - $this->Database->runQuery ("DELETE FROM php_sessions WHERE `access` < ?", [time() - $max]); - return true; - } - catch (Exception $e) { - return false; - } - } +final class Session_DB implements SessionHandlerInterface +{ + /** + * @var Database_PDO + */ + private $Database; + + /** + * @var Result + */ + private $Result; + + /** + * @return void + */ + public function __construct(Database_PDO $database) + { + $this->Database = $database; + + $this->Result = new Result; + + session_set_save_handler($this, true); + + session_start(); + } + + /** + * Open connection + * + * @param string $path + * @param string $name + */ + public function open($path, $name): bool + { + try { + $this->Database->connect(); + } catch (PDOException $e) { + $this->Result->show('danger', $e->getMessage(), false); + + return false; + } + + return true; + } + + /** + * Close connection - not needed + */ + public function close(): bool + { + return true; + } + + /** + * Check database for session data + * + * @param string $id + * @return string|false + */ + #[\ReturnTypeWillChange] + public function read($id) + { + // check database for cookie + try { + // Note: Database->getObject() does not support non-numeric id's. Use findObject(). + $session = $this->Database->findObject('php_sessions', 'id', $id); + + if (is_object($session) && strlen($session->data) > 0) { + return (string) $session->data; + } + } catch (PDOException $e) { + $this->Result->show('danger', $e->getMessage(), false); + + return false; + } + + return ''; + } + + /** + * Save session data + * + * @param string $id + * @param string $data + */ + public function write($id, $data): bool + { + // set insert / update values + $values = [ + 'id' => $id, + 'access' => time(), + 'data' => $data, + 'remote_ip' => $_SERVER['REMOTE_ADDR'], + ]; + + try { + $this->Database->insertObject('php_sessions', $values, false, true, false); + } catch (PDOException $e) { + $this->Result->show('danger', $e->getMessage(), false); + + return false; + } + + return true; + } + + /** + * Destroy session + * + * @param string $id + */ + public function destroy($id): bool + { + try { + $this->Database->deleteObject('php_sessions', $id); + } catch (PDOException $e) { + $this->Result->show('danger', $e->getMessage(), false); + + return false; + } + + return true; + } + + /** + * Garbage collection functions + * + * @param int $max + * @return int|false + */ + #[\ReturnTypeWillChange] + public function gc($max) + { + $rowCount = 0; + try { + $this->Database->runQuery('DELETE FROM php_sessions WHERE `access` < ?', [time() - $max], $rowCount); + } catch (PDOException $e) { + return false; + } + + return (int) $rowCount; + } } diff --git a/functions/classes/class.Subnets.php b/functions/classes/class.Subnets.php index f5ea407cc..f3c8ba7d9 100644 --- a/functions/classes/class.Subnets.php +++ b/functions/classes/class.Subnets.php @@ -40,7 +40,7 @@ class Subnets extends Common_functions { * @var array * @access protected */ - protected $ripe = array(); + protected $ripe = []; /** * array of /8 arin subnets @@ -50,7 +50,7 @@ class Subnets extends Common_functions { * @var array * @access protected */ - protected $arin = array(); + protected $arin = []; /** * Addresses class @@ -112,7 +112,7 @@ public function __construct (Database_PDO $database) { * * @param object|false $section * @access private - * @return void + * @return array|false */ private function get_subnet_order($section) { $this->get_settings(); @@ -125,7 +125,7 @@ private function get_subnet_order($section) { if (!in_array($order, array_keys($this->get_valid_subnet_orderings(false)))) { $order = "subnet,asc"; } - return explode(",", $order); + return explode(",", (string) $order); } /** @@ -246,7 +246,7 @@ private function subnet_add ($values) { # ok $this->Log->write( _("Subnet creation"), _("New subnet created").".
".$this->array_to_log($this->reformat_empty_array_fields ($values, "NULL")), 0); # write changelog - $this->Log->write_changelog('subnet', "add", 'success', array(), $values); + $this->Log->write_changelog('subnet', "add", 'success', [], $values); return true; } @@ -327,7 +327,7 @@ private function subnet_delete ($id) { $this->remove_subnet_nat_items ($id, true); # write changelog - $this->Log->write_changelog('subnet', "delete", 'success', $old_subnet, array()); + $this->Log->write_changelog('subnet', "delete", 'success', $old_subnet, []); # ok $this->Log->write( _("Subnet")." ".$old_subnet->description." "._("delete"), _("Subnet")." ".$old_subnet->description." "._("deleted").".
".$this->array_to_log($this->reformat_empty_array_fields ((array) $old_subnet)), 0); return true; @@ -366,14 +366,14 @@ private function subnet_resize ($subnetId, $subnet, $mask) { # save old values $old_subnet = $this->fetch_subnet (null, $subnetId); # execute - try { $this->Database->updateObject("subnets", array("id"=>$subnetId, "subnet"=>$subnet, "mask"=>$mask), "id"); } + try { $this->Database->updateObject("subnets", ["id"=>$subnetId, "subnet"=>$subnet, "mask"=>$mask], "id"); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); $this->Log->write( _("Subnet edit"), _("Failed to resize subnet")." ".$old_subnet->description." "._("id")." ".$old_subnet->id.".
".$e->getMessage(), 2); return false; } # ok - $this->Log->write( _("Subnet resize"), _("Subnet")." ".$old_subnet->description." "._("id")." ".$old_subnet->id." "._("resized").".
".$this->array_to_log(array("id"=>$subnetId, "mask"=>$mask)), 0); + $this->Log->write( _("Subnet resize"), _("Subnet")." ".$old_subnet->description." "._("id")." ".$old_subnet->id." "._("resized").".
".$this->array_to_log(["id"=>$subnetId, "mask"=>$mask]), 0); return true; } @@ -399,7 +399,7 @@ public function subnet_split ($subnet_old, $number, $prefix, $group="yes", $copy # admin object and tools object $Admin = new Admin ($this->Database, false); - $custom_fields = array (); + $custom_fields = []; if($copy_custom=="yes") { $Tools = new Tools ($this->Database); $custom_fields = $Tools->fetch_custom_fields ("subnets"); @@ -408,7 +408,7 @@ public function subnet_split ($subnet_old, $number, $prefix, $group="yes", $copy # create new subnets and change subnetId for recalculated hosts foreach($newsubnets as $m => $subnet) { //set new subnet insert values - $values = array( + $values = [ "description" => !is_blank($prefix) ? $prefix.($m+1) : "split_subnet_".($m+1), "subnet" => $subnet['subnet'], "mask" => $subnet['mask'], @@ -422,7 +422,7 @@ public function subnet_split ($subnet_old, $number, $prefix, $group="yes", $copy "nameserverId" => $subnet_old->nameserverId, "device" => $subnet_old->device, "isPool" => $subnet_old->isPool, - ); + ]; // custom fields if($copy_custom=="yes" && is_array($custom_fields)) { foreach ($custom_fields as $myField) { @@ -442,13 +442,13 @@ public function subnet_split ($subnet_old, $number, $prefix, $group="yes", $copy //replace all subnetIds in IP addresses to new subnet if(sizeof($ids)>0) { - if(!$Admin->object_modify("ipaddresses", "edit-multiple", $ids, array("subnetId"=>$this->lastInsertId))) { $this->Result->show("danger", _("Failed to move IP address"), true); } + if(!$Admin->object_modify("ipaddresses", "edit-multiple", $ids, ["subnetId"=>$this->lastInsertId])) { $this->Result->show("danger", _("Failed to move IP address"), true); } } } # do we need to remove old subnet? if($group!="yes") { - if(!$Admin->object_modify("subnets", "delete", "id", array("id"=>$subnet_old->id))) { $this->Result->show("danger", _("Failed to remove old subnet"), true); } + if(!$Admin->object_modify("subnets", "delete", "id", ["id"=>$subnet_old->id])) { $this->Result->show("danger", _("Failed to remove old subnet"), true); } } # result @@ -469,7 +469,7 @@ public function remove_subnet_nat_items ($obj_id = 0, $print = true) { # set found flag for returns $found = 0; # fetch all nats - try { $all_nats = $this->Database->getObjectsQuery ("nat", "select * from `nat` where `src` like :id or `dst` like :id", array ("id"=>'%"'.$obj_id.'"%')); } + try { $all_nats = $this->Database->getObjectsQuery ("nat", "select * from `nat` where `src` like :id or `dst` like :id", ["id"=>'%"'.$obj_id.'"%']); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -485,9 +485,9 @@ public function remove_subnet_nat_items ($obj_id = 0, $print = true) { $d = db_json_decode($nat->dst, true); if(is_array($s['subnets'])) - $s['subnets'] = array_diff($s['subnets'], array($obj_id)); + $s['subnets'] = array_diff($s['subnets'], [$obj_id]); if(is_array($d['subnets'])) - $d['subnets'] = array_diff($d['subnets'], array($obj_id)); + $d['subnets'] = array_diff($d['subnets'], [$obj_id]); # save back and update $src_new = json_encode(array_filter($s)); @@ -497,7 +497,7 @@ public function remove_subnet_nat_items ($obj_id = 0, $print = true) { if($s!=$src_new || $d!=$dst_new) { $found++; - if($Admin->object_modify ("nat", "edit", "id", array("id"=>$nat->id, "src"=>$src_new, "dst"=>$dst_new))!==false) { + if($Admin->object_modify ("nat", "edit", "id", ["id"=>$nat->id, "src"=>$src_new, "dst"=>$dst_new])!==false) { if($print) { $this->Result->show("success", _("Subnet removed from NAT"), false); } @@ -574,7 +574,7 @@ public function fetch_section_subnets ($sectionId, $field = false, $value = fals else { $query = "SELECT $safe_result_fields FROM `subnets` where `sectionId` in (SELECT id from sections where name = ?) $field_query order by `isFolder` desc, case `isFolder` when 1 then description else $order[0] end $order[1]"; } - try { $subnets = $this->Database->getObjectsQuery('subnets', $query, array($sectionId)); } + try { $subnets = $this->Database->getObjectsQuery('subnets', $query, [$sectionId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -746,7 +746,7 @@ public function fetch_overlapping_subnets ($cidr, $method=null, $value=null, $re $cidr_network = $this->decimal_network_address($cidr_decimal, $cidr_mask); $cidr_broadcast = $this->decimal_broadcast_address($cidr_decimal, $cidr_mask); - $possible_parents = array(); + $possible_parents = []; for ($mask = 0; $mask <= $cidr_mask; $mask++) { $parent = $this->decimal_network_address($cidr_decimal, $mask); $possible_parents[] = "('$parent','$mask')"; @@ -834,7 +834,7 @@ private function fetch_all_subnets_for_Check($discoverytype, $agentId) { $query = "SELECT s.id, s.subnet, s.sectionId, s.mask, s.resolveDNS, s.nameserverId FROM subnets AS s LEFT JOIN subnets AS child ON child.masterSubnetId = s.id WHERE s.scanAgent = ? AND s.$discoverytype = 1 AND s.isFolder = 0 AND s.mask > 0 AND s.subnet < 4294967296 AND child.id IS NULL;"; - try { $subnets = $this->Database->getObjectsQuery('subnets', $query, array($agentId)); } + try { $subnets = $this->Database->getObjectsQuery('subnets', $query, [$agentId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -862,11 +862,11 @@ public function fetch_vlan_subnets ($vlanId, $sectionId=null) { # set query if(!is_null($sectionId)) { $query = "select * from `subnets` where `vlanId` = ? and `sectionId` = ? ORDER BY isFolder desc, $order[0] $order[1];"; - $params = array($vlanId, $sectionId); + $params = [$vlanId, $sectionId]; } else { $query = "select * from `subnets` where `vlanId` = ? ORDER BY isFolder desc, $order[0] $order[1];"; - $params = array($vlanId); + $params = [$vlanId]; } # fetch @@ -913,7 +913,7 @@ public function is_linked ($subnetId) { return false; } else { - try { $subnets = $this->Database->getObjectsQuery('subnets', "select * from subnets where `linked_subnet` = ?", array($subnetId)); } + try { $subnets = $this->Database->getObjectsQuery('subnets', "select * from subnets where `linked_subnet` = ?", [$subnetId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -949,11 +949,11 @@ public function fetch_vrf_subnets ($vrfId, $sectionId=null) { # set query if(!is_null($sectionId)) { $query = "select * from `subnets` where `vrfId` = ? and `sectionId` = ? ORDER BY isFolder desc, $order[0] $order[1];"; - $params = array($vrfId, $sectionId); + $params = [$vrfId, $sectionId]; } else { $query = "select * from `subnets` where `vrfId` = ? ORDER BY isFolder desc, $order[0] $order[1];"; - $params = array($vrfId); + $params = [$vrfId]; } # fetch @@ -1016,7 +1016,7 @@ public function fetch_scanned_subnets ($agentId=null) { // set query $query = "select * from `subnets` where `scanAgent` = ? and ( `pingSubnet`=1 or `discoverSubnet`=1 or `resolveDNS`=1 );"; # fetch - try { $subnets = $this->Database->getObjectsQuery('subnets', $query, array($agentId)); } + try { $subnets = $this->Database->getObjectsQuery('subnets', $query, [$agentId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -1035,7 +1035,7 @@ public function find_gateway ($subnetId) { // set query $query = "select `ip_addr`,`id` from `ipaddresses` where `subnetId` = ? and `is_gateway` = 1;"; # fetch - try { $gateway = $this->Database->getObjectQuery("ipaddresses", $query, array($subnetId)); } + try { $gateway = $this->Database->getObjectQuery("ipaddresses", $query, [$subnetId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -1050,7 +1050,7 @@ public function find_gateway ($subnetId) { * @return array */ public function get_ipv4_masks () { - $out = array(); + $out = []; # loop masks for($mask=32; $mask>=0; $mask--) { // initialize @@ -1070,7 +1070,7 @@ public function get_ipv4_masks () { $out[$mask]->wildcard = long2ip(~ip2long($net->netmask)); //0.0.255.255 // binary - $parts = pf_explode(".", $net->netmask); + $parts = explode(".", (string) $net->netmask); foreach($parts as $k=>$p) { $parts[$k] = str_pad(decbin($p),8, 0); } $out[$mask]->binary = implode(".", $parts); } @@ -1085,7 +1085,7 @@ public function get_ipv4_masks () { * @return array */ public function get_ipv4_masks_for_subnet ($subnet_mask = "32") { - $out = array(); + $out = []; # loop masks for($mask=32; $mask>=$subnet_mask; $mask--) { // initialize @@ -1105,7 +1105,7 @@ public function get_ipv4_masks_for_subnet ($subnet_mask = "32") { $out[$mask]->wildcard = long2ip(~ip2long($net->netmask)); //0.0.255.255 // binary - $parts = pf_explode(".", $net->netmask); + $parts = explode(".", (string) $net->netmask); foreach($parts as $k=>$p) { $parts[$k] = str_pad(decbin($p),8, 0); } $out[$mask]->binary = implode(".", $parts); } @@ -1247,7 +1247,7 @@ public function remove_subnet_slaves_master ($subnetId) { * @return array */ public function fetch_parents_recursive ($subnetId) { - $parents = array(); + $parents = []; $root = false; while($root === false) { @@ -1291,7 +1291,7 @@ public function find_subnet ($sectionId = false, $cidr = false) { // set subnet / mask $tmp = $this->cidr_network_and_mask($cidr); // search - try { $subnet = $this->Database->getObjectQuery('subnets', "select * from `subnets` where `subnet`=? and `mask`=? and `sectionId`=?;", array($this->transform_address($tmp[0],"decimal"), $tmp[1], $sectionId)); } + try { $subnet = $this->Database->getObjectQuery('subnets', "select * from `subnets` where `subnet`=? and `mask`=? and `sectionId`=?;", [$this->transform_address($tmp[0],"decimal"), $tmp[1], $sectionId]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -1520,11 +1520,11 @@ private function calculate_subnet_usage_stats_recursive ($subnet) { * @return mixed */ public function reformat_number ($number) { - $length = strlen($number); + $length = strlen((string) $number); $pos = $length - 3; if ($length > 8) { - $number = "~". substr($number, 0, $length - $pos) . "·10^". $pos .""; + $number = "~". substr((string) $number, 0, $length - $pos) . "·10^". $pos .""; } return $number; } @@ -1734,7 +1734,7 @@ private function generate_network_bitmasks () { // [size] = 2^(mask bits) subnet size // [broadcast] = OR bitmask to set subnet /mask bits to calculate broadcast addresses // [network] = AND bitmask to clear subnet /mask bits to calculate network addresses - $bmask = array(); + $bmask = []; for ($x=0; $x <= 128; $x++) { $pwr = gmp_pow2(128-$x); $bmask['IPv6'][$x]['size'] = $pwr; @@ -1866,16 +1866,16 @@ public function find_unused_addresses($subnet, $address1=false, $address2=false) public function get_subnet_freespacemap ($masterSubnet) { // Get Current and Previous subnets $subnets = $this->fetch_subnet_slaves($masterSubnet->id); - $subnets = is_array($subnets) ? $subnets : array(); + $subnets = is_array($subnets) ? $subnets : []; // detect type $type = $this->identify_address($masterSubnet->subnet); $max_mask = ($type == 'IPv4') ? 32 : 128; # here we use range split/exclusion algorithm to find final list of networks a whole lot of times faster - $ranges = array( array( + $ranges = [ [ 'start' => $this->decimal_network_address($masterSubnet->subnet, $masterSubnet->mask), - 'end' => $this->decimal_broadcast_address($masterSubnet->subnet, $masterSubnet->mask) )); + 'end' => $this->decimal_broadcast_address($masterSubnet->subnet, $masterSubnet->mask) ]]; foreach ($subnets as $excl) { $estart = $this->decimal_network_address($excl->subnet, $excl->mask); $eend = $this->decimal_broadcast_address($excl->subnet, $excl->mask); @@ -1884,18 +1884,18 @@ public function get_subnet_freespacemap ($masterSubnet) { # range overlaps, now we check what to do unset($ranges[$rid]); # remove existing range - if (gmp_cmp($range['start'], $estart) < 0) { $ranges[] = array('start' => $range['start'], 'end' => gmp_strval(gmp_sub($estart, 1))); }; - if (gmp_cmp($range['end'], $eend) > 0) { $ranges[] = array('start' => gmp_strval(gmp_add($eend, 1)), 'end' => $range['end']); }; + if (gmp_cmp($range['start'], $estart) < 0) { $ranges[] = ['start' => $range['start'], 'end' => gmp_strval(gmp_sub($estart, 1))]; }; + if (gmp_cmp($range['end'], $eend) > 0) { $ranges[] = ['start' => gmp_strval(gmp_add($eend, 1)), 'end' => $range['end']]; }; } } uasort($ranges, function ($a, $b) { return gmp_cmp($a['start'], $b['start']); }); - return array( + return [ 'subnet' => $masterSubnet->subnet, 'mask' => $masterSubnet->mask, 'type' => $type, 'max_search_mask' => $max_mask, - 'freeranges' => $ranges); + 'freeranges' => $ranges]; } /** @@ -1909,10 +1909,10 @@ public function get_subnet_freespacemap ($masterSubnet) { */ public function get_freespacemap_first_available ($fsm, $mask, $count) { if ($mask < 0 || $mask > $fsm['max_search_mask']) { - return array ('subnets' => array(), 'truncated' => false); + return ['subnets' => [], 'truncated' => false]; } - $subnets = array(); + $subnets = []; $ranges = $fsm['freeranges']; $size = $this->gmp_bitmasks[$fsm['type']][$mask]['size']; @@ -1932,7 +1932,7 @@ public function get_freespacemap_first_available ($fsm, $mask, $count) { while (gmp_cmp($candidate_end, $range['end']) <= 0) { if ($count > 0 && ++$discovered > $count) { - return array ('subnets' => $subnets, 'truncated' => true); + return ['subnets' => $subnets, 'truncated' => true]; } $subnets[] = $this->transform_to_dotted(gmp_strval($candidate_start)) . '/' . $mask; @@ -1941,7 +1941,7 @@ public function get_freespacemap_first_available ($fsm, $mask, $count) { } } - return array ('subnets' => $subnets, 'truncated' => false); + return ['subnets' => $subnets, 'truncated' => false]; } /** @@ -1955,10 +1955,10 @@ public function get_freespacemap_first_available ($fsm, $mask, $count) { */ public function get_freespacemap_last_available ($fsm, $mask, $count) { if ($mask < 0 || $mask > $fsm['max_search_mask']) { - return array ('subnets' => array(), 'truncated' => false); + return ['subnets' => [], 'truncated' => false]; } - $subnets = array(); + $subnets = []; $ranges = array_reverse($fsm['freeranges']); $size = $this->gmp_bitmasks[$fsm['type']][$mask]['size']; @@ -1978,7 +1978,7 @@ public function get_freespacemap_last_available ($fsm, $mask, $count) { while (gmp_cmp($candidate_start, $range['start']) >= 0) { if ($count > 0 && ++$discovered > $count) { - return array ('subnets' => $subnets, 'truncated' => true); + return ['subnets' => $subnets, 'truncated' => true]; } $subnets[] = $this->transform_to_dotted(gmp_strval($candidate_start)) . '/' . $mask; @@ -1987,7 +1987,7 @@ public function get_freespacemap_last_available ($fsm, $mask, $count) { } } - return array ('subnets' => $subnets, 'truncated' => false); + return ['subnets' => $subnets, 'truncated' => false]; } @@ -2049,7 +2049,7 @@ public function verify_cidr_address_IPv4 ($cidr, $issubnet = true) { */ public function verify_cidr_address_IPv6 ($cidr, $issubnet = true) { # to lower - $cidr = strtolower($cidr); + $cidr = strtolower((string) $cidr); # Initialize PEAR NET object $this->initialize_pear_net_IPv6 (); # validate @@ -2621,7 +2621,7 @@ private function verify_subnet_split ($subnet_old, $number, $group) { } # all good, return result array of newsubnets and addresses - return array(0=>$newsubnets, 1=>$addresses); + return [0=>$newsubnets, 1=>$addresses]; } /** @@ -2649,7 +2649,7 @@ public function find_invalid_subnets () { // validate foreach ($ids as $id) { if ($this->verify_subnet_id ($id->masterSubnetId)===0) { - if(!isset($false)) $false = array(); + if(!isset($false)) $false = []; $false[] = $this->fetch_subnet_slaves ($id->masterSubnetId); } } @@ -2719,7 +2719,7 @@ public function find_inactive_hosts ($timelimit = 86400, $limit = 100) { // fetch settings $this->get_settings (); // search - try { $res = $this->Database->getObjectsQuery('ipaddresses', "select ipaddresses.* from `ipaddresses` join subnets on ipaddresses.subnetId = subnets.id where subnets.pingSubnet = 1 and `lastSeen` between ? and ? order by lastSeen desc limit $limit;", array(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s"))-$timelimit), date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s"))-(int) str_replace(";","",strstr($this->settings->pingStatus, ";")))) ); } + try { $res = $this->Database->getObjectsQuery('ipaddresses', "select ipaddresses.* from `ipaddresses` join subnets on ipaddresses.subnetId = subnets.id where subnets.pingSubnet = 1 and `lastSeen` between ? and ? order by lastSeen desc limit $limit;", [date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s"))-$timelimit), date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s"))-(int) str_replace(";","",(string) strstr((string) $this->settings->pingStatus, ";")))] ); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -2762,8 +2762,8 @@ public function fetch_multicast_subnets () { $res2 = $this->fetch_distinct_multicast_folders (); # array check - if($res===false) $res = array(); - if($res2===false) $res2 = array(); + if($res===false) $res = []; + if($res2===false) $res2 = []; # create if (sizeof($res)>0 && sizeof($res2)>0) { return $res2 + $res; } @@ -2789,7 +2789,7 @@ public function fetch_distinct_multicast_folders () { } # return if(sizeof($res)>0) { - $out = array(); + $out = []; foreach ($res as $r) { $out[] = "(`isfolder` = '1' and `id` = $r->id)"; } @@ -2853,7 +2853,7 @@ public function create_multicast_mac ($address) { // ipv4 if ($this->identify_address ($address)=="IPv4") { // to array - $mac_tmp = pf_explode(".", $address); + $mac_tmp = explode(".", (string) $address); // check 3rd octet if ($mac_tmp[1]>=128) { $mac_tmp[1]=$mac_tmp[1]-128; } // create mac @@ -2865,7 +2865,7 @@ public function create_multicast_mac ($address) { //expand $expanded = $this->Net_IPv6->uncompress($address); // to array - $mac_tmp = pf_explode(":", $expanded); + $mac_tmp = explode(":", $expanded); $mac = strtolower("33:33:".str_pad(dechex($mac_tmp[4]),2,"0",STR_PAD_LEFT).":".str_pad(dechex($mac_tmp[5]),2,"0",STR_PAD_LEFT).":".str_pad(dechex($mac_tmp[6]),2,"0",STR_PAD_LEFT).":".str_pad(dechex($mac_tmp[7]),2,"0",STR_PAD_LEFT)); } else { @@ -2887,7 +2887,7 @@ public function find_duplicate_multicast_mac ($address_id, $mac) { // query $query = "select i.ip_addr,i.hostname,i.mac,i.subnetId,i.description as i_description,s.sectionId,s.description,s.isFolder,se.name from `ipaddresses` as `i`, `subnets` as `s`, `sections` as `se` where `i`.`mac` = ? and `i`.`id` != ? and `se`.`id`=`s`.`sectionId` and `i`.`subnetId`=`s`.`id`"; // fetch - try { $res = $this->Database->getObjectsQuery('ipaddresses', $query, array($mac, $address_id)); } + try { $res = $this->Database->getObjectsQuery('ipaddresses', $query, [$mac, $address_id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -2934,7 +2934,7 @@ private function multicast_address_exists ($mac, $sectionId, $vlanId, $unique_re } // fetch - try { $res = $this->Database->getObjectsQuery('ipaddresses', $query, array($mac, $address_id)); } + try { $res = $this->Database->getObjectsQuery('ipaddresses', $query, [$mac, $address_id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -2970,7 +2970,7 @@ private function multicast_address_exists ($mac, $sectionId, $vlanId, $unique_re public function validate_multicast_mac ($mac, $sectionId, $vlanId, $unique_required="vlan", $address_id = 0) { // first put it to common format (1) $mac = $this->reformat_mac_address ($mac); - $mac_delimited = pf_explode(":", $mac); + $mac_delimited = explode(":", $mac); // we permit empty if (is_blank($mac)) { return true; @@ -3112,7 +3112,7 @@ public function set_permissions ($subnets, $removed_permissions, $changed_permis } // set values - $values = array("id" => $s->id, "permissions" => json_encode($s_old_perm)); + $values = ["id" => $s->id, "permissions" => json_encode($s_old_perm)]; // update if($this->modify_subnet ("edit", $values, false)===false) { @@ -3197,7 +3197,7 @@ public function print_subnets_menu($user, $section_subnets) { */ public function print_vlan_menu( $user, $vlans, $section_subnets, $sectionId ) { # initialize html array - $html = array(); + $html = []; # must be numeric if(isset($_GET['section'])) if(!is_numeric($_GET['section'])) { $this->Result->show("danger",_("Invalid ID"), true); } if(isset($_GET['subnetId'])) if(!is_numeric($_GET['subnetId'])) { $this->Result->show("danger",_("Invalid ID"), true); } @@ -3238,7 +3238,7 @@ public function print_vlan_menu( $user, $vlans, $section_subnets, $sectionId ) { $html[] = ''.$item['number'].' ('.$item['name'].') '.$item['l2domain'].''; # set all subnets in this vlan - $subnets = array(); + $subnets = []; foreach ($section_subnets as $s) { if ($s->vlanId==$item['vlanId']) { $subnets[] = $s; @@ -3296,7 +3296,7 @@ public function print_vlan_menu( $user, $vlans, $section_subnets, $sectionId ) { */ public function print_vrf_menu( $user, $vrfs, $section_subnets, $sectionId ) { # initialize html array - $html = array(); + $html = []; # Menu start $html[] = '
    '; @@ -3331,7 +3331,7 @@ public function print_vrf_menu( $user, $vrfs, $section_subnets, $sectionId ) { $html[] = ''.$item['name'].''; # set all subnets in this vrf - $subnets = array(); + $subnets = []; foreach ($section_subnets as $s) { if ($s->vrfId==$item['vrfId']) { $subnets[] = $s; @@ -3390,9 +3390,9 @@ public function print_mastersubnet_dropdown_menu($sectionId, $current_master = 0 # must be integer if(!is_numeric($sectionId)) { $this->Result->show("danger", _("Invalid ID"), true); } - $folders = array(); + $folders = []; $section_subnets = $this->fetch_section_subnets ($sectionId, false, false); - if (!is_array($section_subnets)) $section_subnets = array(); + if (!is_array($section_subnets)) $section_subnets = []; foreach($section_subnets as $subnet) { if ($subnet->isFolder) { @@ -3470,7 +3470,7 @@ public function subnet_dropdown_print_available($sectionId, $subnetMasterId) { # Find the first|last $count available free subnets of size $mask inside the freespacemap array. # return values = array (subnets => $available_subnets, truncated => false); - $nets = array(); + $nets = []; $levels_full = 8; # Display all available subnets for n sections, $level_trunc = 8; # then display the first y available subnets in the remaining sections @@ -3481,7 +3481,7 @@ public function subnet_dropdown_print_available($sectionId, $subnetMasterId) { } # finally, output menu - $html = array(); + $html = []; foreach ($nets as $prefix => $net) { $subnets = $net['subnets']; $truncated = $net['truncated']; @@ -3558,18 +3558,18 @@ public function search_available_subnets ($subnetMasterId, $mask, $count = Subne * Fetch subnet information form RIPE / ARIN * * @access public - * @param mixed $subnet + * @param string $subnet * @return array */ public function resolve_ripe_arin ($subnet) { // set subnet allocations $this->define_ripe_arin_subnets (); // take only first bit of ip address to match /8 delegations - $subnet_check = reset(pf_explode(".", $subnet)); + $subnet_check = reset(explode(".", $subnet)); // ripe or arin? if (in_array($subnet_check, $this->ripe)) { return $this->query_ripe ($subnet); } elseif (in_array($subnet_check, $this->arin)) { return $this->query_arin ($subnet); } - else { return array("result"=>"error", "error"=>"$subnet "._("Not RIPE or ARIN subnet")); } + else { return ["result"=>"error", "error"=>"$subnet "._("Not RIPE or ARIN subnet")]; } } @@ -3589,15 +3589,15 @@ private function query_ripe ($subnet) { // not existings if ($ripe_result['result_code']==404) { // return array - return array("result"=>"error", "error"=>$ripe_result['error_msg']); + return ["result"=>"error", "error"=>$ripe_result['error_msg']]; } // fail if ($ripe_result['result_code']!==200) { // return array - return array("result"=>"error", "error"=>_("Error connecting to RIPE REST API")." : ".$ripe_result['error_msg']); + return ["result"=>"error", "error"=>_("Error connecting to RIPE REST API")." : ".$ripe_result['error_msg']]; } else { - $out = array(); + $out = []; // loop if (isset($ripe_result['result']->objects->object[0]->attributes->attribute)) { foreach($ripe_result['result']->objects->object[0]->attributes->attribute as $k=>$v) { @@ -3605,7 +3605,7 @@ private function query_ripe ($subnet) { } } // return array - return array("result"=>"success", "data"=>array_filter($out)); + return ["result"=>"success", "data"=>array_filter($out)]; } } @@ -3626,15 +3626,15 @@ private function query_arin ($subnet) { // not existings if ($arin_result['result_code']==404) { // return array - return array("result"=>"error", "error"=>_("Subnet not found")); + return ["result"=>"error", "error"=>_("Subnet not found")]; } // fail if ($arin_result['result_code']!==200) { // return array - return array("result"=>"error", "error"=>_("Error connecting to ARIN REST API")." : ".$arin_result['error_msg']); + return ["result"=>"error", "error"=>_("Error connecting to ARIN REST API")." : ".$arin_result['error_msg']]; } else { - $out = array(); + $out = []; // loop if (isset($arin_result['result']->nets->net )) { foreach($arin_result['result']->nets->net as $k=>$v) { @@ -3651,14 +3651,14 @@ private function query_arin ($subnet) { } // do some formats if (array_key_exists("cidrLength", $out) && array_key_exists("startAddress", $out)) { - $out = array_merge(array("CIDR"=>$out['startAddress']."/".$out['cidrLength']), $out); - $out = array_merge(array('NetRange'=>$out['startAddress']." - ".$out['endAddress']), $out); + $out = array_merge(["CIDR"=>$out['startAddress']."/".$out['cidrLength']], $out); + $out = array_merge(['NetRange'=>$out['startAddress']." - ".$out['endAddress']], $out); unset($out['startAddress'], $out['endAddress'], $out['cidrLength']); } unset($out['orgRef'], $out['parentNetRef'], $out['version'], $out['registrationDate']); // return array - return array("result"=>"success", "data"=>array_filter($out)); + return ["result"=>"success", "data"=>array_filter($out)]; } } @@ -3673,7 +3673,7 @@ private function query_arin ($subnet) { */ private function ripe_arin_fetch ($network, $type, $subnet) { // Validate $subnet - $cidr = array_pad(explode("/", $subnet), 2, null); + $cidr = array_pad(explode("/", (string) $subnet), 2, null); if ( (sizeof($cidr) > 2) || (filter_var($cidr[0], FILTER_VALIDATE_IP) === false) || @@ -3719,16 +3719,16 @@ public function ripe_fetch_subnets ($as) { while (!feof($ripe_connection)) { $out .= fgets($ripe_connection); } //parse it - $out = pf_explode("\n", $out); + $out = explode("\n", $out); //we only want lines starting with route or route6 - $subnet = array(); + $subnet = []; foreach($out as $line) { if (substr($line,0,6)=="route:" || substr($line,0,7)=="route6:") { //replace route6 with route $line = str_replace("route6:", "route:", $line); //only take IP address - $line = pf_explode("route:", $line); + $line = explode("route:", $line); $line = trim($line[1]); //set result $subnet[] = $line; @@ -3749,21 +3749,21 @@ public function ripe_fetch_subnets ($as) { private function define_ripe_arin_subnets () { // ripe if (sizeof($this->ripe)==0) { - $this->ripe = array ( + $this->ripe = [ "2", "5", "31", "37", "46", "51", "62", "77", "78", "79", "8", "81", "82", "83", "84", "85", "86", "87", "88", "89", "9", "91", "92", "93", "94", "95", "19", "141", "145", "151", "176", "178", "185", "188", "193", "194", "195", "212", "213", "217" - ); + ]; } // arin if (sizeof($this->arin)==0) { - $this->arin = array ( + $this->arin = [ "7", "13", "23", "24", "32", "35", "4", "45", "47", "5", "52", "54", "63", "64", "65", "66", "67", "68", "69", "7", "71", "72", "73", "74", "75", "76", "96", "97", "98", "99", "1", "14", "17", "18", "128", "129", "13", "131", "132", "134", "135", "136", "137", "138", "139", "14", "142", "143", "144", "146", "147", "148", "149", "152", "155", "156", "157", "158", "159", "16", "161", "162", "164", "165", "166", "167", "168", "169", "17", "172", "173", "174", "184", "192", "198", "199", "24", "25", "26", "27", "28", "29", "216" - ); + ]; } } diff --git a/functions/classes/class.SubnetsMasterDropDown.php b/functions/classes/class.SubnetsMasterDropDown.php index 21c649131..e440b801b 100644 --- a/functions/classes/class.SubnetsMasterDropDown.php +++ b/functions/classes/class.SubnetsMasterDropDown.php @@ -14,7 +14,7 @@ class SubnetsMasterDropDown { * Store generated html * @var array */ - private $html = array(); + private $html = []; /** * Name of current @@ -73,7 +73,7 @@ public function optgroup_close() { * @return string */ private function get_subnet_options($subnet) { - $options = array(); + $options = []; // selected="selected" if ($subnet->id == $this->previously_selected) { diff --git a/functions/classes/class.SubnetsMenu.php b/functions/classes/class.SubnetsMenu.php index fe4508028..6164b8570 100644 --- a/functions/classes/class.SubnetsMenu.php +++ b/functions/classes/class.SubnetsMenu.php @@ -14,14 +14,14 @@ class SubnetsMenu { * Store generated HTML * @var array */ - private $html = array(); + private $html = []; /** * Array of expanded subnet/folder ids * Lookus by index, $expanded[$id] = 1 vs full array search for every item [in_array()] * @var array */ - private $expanded = array(); + private $expanded = []; /** * Expand All Folders/Subnets @@ -52,7 +52,7 @@ public function __construct($Subnets, $expanded, $expandall, $selected) { $this->Subnets = $Subnets; $this->Subnets->get_Settings(); if (isset($expanded)) { - $expanded = array_filter(pf_explode("|", $expanded)); + $expanded = array_filter(explode("|", $expanded)); // Store expanded subnets/folders to allow fast index lookups. foreach($expanded as $e) $this->expanded[$e] = 1; } @@ -134,7 +134,7 @@ private function get_subnet_styles($subnet) { $style_openf = "-open"; } - return array($style_open, $style_openf, $style_active, $style_leafClass); + return [$style_open, $style_openf, $style_active, $style_leafClass]; } /** diff --git a/functions/classes/class.SubnetsTable.php b/functions/classes/class.SubnetsTable.php index fdc091216..c2a2bb99f 100644 --- a/functions/classes/class.SubnetsTable.php +++ b/functions/classes/class.SubnetsTable.php @@ -32,7 +32,7 @@ class SubnetsTable { * Index of all VLANs. * @var array */ - private $all_vlans = array(); + private $all_vlans = []; /** * Class Constructor @@ -48,7 +48,7 @@ public function __construct($Tools, $custom_fields, $showSupernetOnly) { $this->Tools->get_Settings(); $hiddenCustomFields = db_json_decode($this->Tools->settings->hiddenCustomFields, true) ? : ['subnets'=>null]; - $this->hidden_fields = is_array($hiddenCustomFields['subnets']) ? $hiddenCustomFields['subnets'] : array(); + $this->hidden_fields = is_array($hiddenCustomFields['subnets']) ? $hiddenCustomFields['subnets'] : []; # fetch all vlans and domains and reindex $vlans_and_domains = $this->Tools->fetch_all_domains_and_vlans (); @@ -81,7 +81,7 @@ private function table_row($subnet) { $padding = '10px'; } - $tr = array(); + $tr = []; # description $description = is_blank($subnet->description) ? "/" : $subnet->description; @@ -150,14 +150,14 @@ private function table_row($subnet) { // customer if ($this->Tools->settings->enableCustomers == 1) { $customer = $this->Tools->fetch_object ("customers", "id", $subnet->customer_id); - $tr['customer'] = $customer===false ? "/" : $customer->title." "; + $tr['customer'] = $customer===false ? "/" : $customer->title." "; } //custom if(is_array($this->custom_fields)) { foreach($this->custom_fields as $field) { if(!in_array($field['name'], $this->hidden_fields)) { - $field_name = urlencode($field['name']); + $field_name = urlencode((string) $field['name']); // create html links $subnet->{$field['name']} = $this->Tools->create_links($subnet->{$field['name']}, $field['type']); @@ -181,7 +181,7 @@ private function table_row($subnet) { } # set permission - $html = array(); + $html = []; $html[] = "
    "; if($subnet->permissions_check>1) { @@ -216,7 +216,7 @@ private function table_row($subnet) { public function json_paginate($SubnetsTree, $offset, $limit) { // If showSupernetOnly is enabled extract the first level of subnets if ($this->showSupernetOnly) { - $subnets = array(); + $subnets = []; foreach($SubnetsTree->subnets as $s) { if ($s->level == 0) $subnets[] = $s; } @@ -226,7 +226,7 @@ public function json_paginate($SubnetsTree, $offset, $limit) { // Generate JSON response $total = sizeof($subnets); - $rows = array(); + $rows = []; // Extract and generate json data for $limit rows at $offset for ($i=$offset; $i<$total && $i<($offset+$limit); $i++) { @@ -234,7 +234,7 @@ public function json_paginate($SubnetsTree, $offset, $limit) { } // bootstrap-tables paginated server-side response format. - $data = array('total' => $total, 'rows' => $rows); + $data = ['total' => $total, 'rows' => $rows]; return json_encode($data); } } diff --git a/functions/classes/class.SubnetsTree.php b/functions/classes/class.SubnetsTree.php index 1877dabc0..e5565a636 100644 --- a/functions/classes/class.SubnetsTree.php +++ b/functions/classes/class.SubnetsTree.php @@ -78,7 +78,7 @@ public function add($subnet) { * Reset subnets internal tree structures */ public function reset() { - $this->subnets = array(); + $this->subnets = []; $root = new stdClass (); $root->id = 0; @@ -86,8 +86,8 @@ public function reset() { $root->description = _("Root folder"); $root->masterSubnetId = 0; - $this->subnets_by_id = array(0 => $root); - $this->children_by_parent_id = array(); + $this->subnets_by_id = [0 => $root]; + $this->children_by_parent_id = []; } /** @@ -95,7 +95,7 @@ public function reset() { * @param boolean $show_root */ public function walk($show_root = true) { - $this->subnets = array(); + $this->subnets = []; $this->walk_recursive(0, 0, $show_root); } diff --git a/functions/classes/class.Table.php b/functions/classes/class.Table.php index 97b57f85b..66ecc89c6 100644 --- a/functions/classes/class.Table.php +++ b/functions/classes/class.Table.php @@ -8,7 +8,7 @@ class Table extends Common_functions { - private $limits = array(25, 50, 100, 250, 500, "all"); + private $limits = [25, 50, 100, 250, 500, "all"]; public $limit = 50; @@ -16,7 +16,7 @@ class Table extends Common_functions { public $subpage = 1; - public $filters = array(); + public $filters = []; @@ -54,11 +54,11 @@ public function paginate_table ($subnets) { // set pagination $pagination = $this->get_table_pagination ($subnets); // result - return array( + return [ "dropdown" => $dropdown, "filters" => $this->filters, "pagination" => $pagination - ); + ]; } private function set_table_filter_data ($subnets) { @@ -86,19 +86,19 @@ private function set_table_filter_data ($subnets) { $pagenum = (int) ceil(sizeof($subnets)/$this->limit); // save - $this->filters = array( + $this->filters = [ "subpage" => $this->subpage, "limit" => $this->limit, "pagenum" => $pagenum, "start" => $start, "stop" => $stop - ); + ]; } private function get_table_dropdown () { // print if($this->filters['pagenum']>1) { - $html = array(); + $html = []; $html[] = "
    "; $html[] = "
"; } else { @@ -1120,12 +1112,12 @@ public function ip_request_send_mail ($action, $values) { $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName); if ($recipients!==false) { foreach($recipients as $r) { - $phpipam_mail->Php_mailer->addAddress(addslashes(trim($r->email))); + $phpipam_mail->Php_mailer->addAddress(addslashes(trim((string) $r->email))); } - $phpipam_mail->Php_mailer->AddCC(addslashes(trim($recipients_requester))); + $phpipam_mail->Php_mailer->AddCC(addslashes(trim((string) $recipients_requester))); } else { - $phpipam_mail->Php_mailer->addAddress(addslashes(trim($recipients_requester))); + $phpipam_mail->Php_mailer->addAddress(addslashes(trim((string) $recipients_requester))); } $phpipam_mail->Php_mailer->Subject = $subject; $phpipam_mail->Php_mailer->msgHTML($content); @@ -1154,7 +1146,7 @@ private function ip_request_get_mail_recipients ($subnetId = false) { // fetch all users with mailNotify $notification_users = $this->fetch_multiple_objects ("users", "mailNotify", "Yes", "id", true); // recipients array - $recipients = array(); + $recipients = []; // any ? if ($notification_users!==false) { // if subnetId is set check who has permissions @@ -1198,7 +1190,7 @@ private function ip_request_reformat_mail_values ($values) { // addresses $this->Addresses = new Addresses ($this->Database); - $mail = array(); + $mail = []; // change fields for mailings foreach ($values as $k=>$v) { @@ -1334,7 +1326,7 @@ public function verify_database () { # update check field $this->update_db_verify_field (); # return empty array - return array(); + return []; } } @@ -1352,7 +1344,7 @@ public function verify_database () { public function table_exists ($tablename, $quit = false) { # query $query = 'SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = "'.$this->Database->dbname.'" AND table_name = ?;'; - try { $count = $this->Database->getObjectQuery("no_html_escape", $query, array($tablename)); } + try { $count = $this->Database->getObjectQuery("no_html_escape", $query, [$tablename]); } catch (Exception $e) { !$quit ? : $this->Result->show("danger", $e->getMessage(), true); return false; } # return return $count->count ==1 ? true : false; @@ -1426,7 +1418,7 @@ public function get_field_fix ($table, $field) { $file = trim(strstr($file, "# Dump of table", true)); //get proper line - $file = pf_explode("\n", $file); + $file = explode("\n", $file); foreach($file as $k=>$l) { if(strpos(trim($l), "$field`")==1) { $res = trim($l, ","); @@ -1522,16 +1514,16 @@ private function get_schema_indexes () { $schema = $this->read_db_schema(); # get definitions to array, explode with CREATE TABLE ` - $creates = pf_explode("CREATE TABLE `", $schema); + $creates = explode("CREATE TABLE `", $schema); - $indexes = array (); + $indexes = []; foreach($creates as $k=>$c) { if($k == 0) continue; $c = trim(strstr($c, ";" . "\n", true)); $table = strstr($c, "`", true); - $definitions = pf_explode("\n", $c); + $definitions = explode("\n", $c); foreach($definitions as $definition) { if (preg_match('/(KEY|UNIQUE KEY) +`(.*)` +\(/', $definition, $matches)) { $indexes[$table][] = $matches[2]; @@ -1604,7 +1596,7 @@ private function fix_missing_index ($table, $index_name) { $file = trim(strstr($file, "# Dump of table", true)); //get proper line - $file = pf_explode("\n", $file); + $file = explode("\n", $file); $line = false; foreach($file as $k=>$l) { @@ -1732,7 +1724,7 @@ public function check_latest_phpipam_version ($print_error = false) { return false; } # set releases href - $xml = simplexml_load_string($curl['result']); + $xml = simplexml_load_string((string) $curl['result']); // if ok if ($xml!==false) { @@ -1743,11 +1735,11 @@ public function check_latest_phpipam_version ($print_error = false) { // check for latest release foreach ($json->entry as $e) { // releases will be named with numberic values - if (is_numeric(str_replace(array("Version", "."), "", $e->title))) { + if (is_numeric(str_replace(["Version", "."], "", (string) $e->title))) { // save $this->phpipam_latest_release = $e; // return - return str_replace("Version", "", $e->title); + return str_replace("Version", "", (string) $e->title); } } // none @@ -1812,7 +1804,7 @@ private function calculate_IPv4_calc_results ($cidr) { $net = $this->Net_IPv4->parseAddress( $cidr ); # set ip address type - $out = array(); + $out = []; $out['Type'] = 'IPv4'; # calculate network details @@ -1877,7 +1869,7 @@ private function get_ipv4_address_type ($network, $broadcast) { */ private function define_ipv4_address_types () { # define classes - $classes = array(); + $classes = []; $classes['private A'] = '10.0.0.0/8'; $classes['private B'] = '172.16.0.0/12'; $classes['private C'] = '192.168.0.0/16'; @@ -1909,7 +1901,7 @@ private function calculate_IPv6_calc_results ($cidr) { $this->initialize_pear_net_IPv6 (); # set ip address type - $out = array(); + $out = []; $out['Type'] = 'IPv6'; # calculate network details @@ -1964,7 +1956,7 @@ public function reverse_IPv6 ($addresses, $pflen=128) { //uncompress $uncompressed = $this->Net_IPv6->removeNetmaskSpec($this->Net_IPv6->uncompress($addresses)); $len = $pflen / 4; - $parts = pf_explode(':', $uncompressed); + $parts = explode(':', $uncompressed); $res = ''; foreach($parts as $part) { $res .= str_pad($part, 4, '0', STR_PAD_LEFT); @@ -2052,10 +2044,10 @@ public function translate_nat_objects_for_display ($json_objects, $nat_id = fals // to array "subnets"=>array(1,2,3) $objects = db_json_decode($json_objects, true); // init out array - $out = array(); + $out = []; // set ping statuses for warning and offline $this->get_settings(); - $statuses = pf_explode(";", $this->settings->pingStatus); + $statuses = explode(";", (string) $this->settings->pingStatus); // check if(is_array($objects)) { if(sizeof($objects)>0) { @@ -2126,12 +2118,12 @@ public function translate_nat_objects_for_display ($json_objects, $nat_id = fals * @param array $all_nats (default: array()) * @return array */ - public function reindex_nat_objects ($all_nats = array()) { + public function reindex_nat_objects ($all_nats = []) { // out array - $out = array( - "ipaddresses"=>array(), - "subnets"=>array() - ); + $out = [ + "ipaddresses"=>[], + "subnets"=>[] + ]; // loop if(is_array($all_nats)) { if (sizeof($all_nats)>0) { @@ -2195,16 +2187,16 @@ public function print_nat_table ($n, $is_admin = false, $nat_id = false, $admin // no src/dst if ($sources===false) - $sources = array(""._("None").""); + $sources = [""._("None").""]; if ($destinations===false) - $destinations = array(""._("None").""); + $destinations = [""._("None").""]; // description - $n->description = str_replace("\n", "
", $n->description); + $n->description = str_replace("\n", "
", (string) $n->description); $n->description = !is_blank($n->description) ? "
$n->description" : ""; // device - if (strlen($n->device)) { + if (strlen((string) $n->device)) { if($n->device !== 0) { $device = $this->fetch_object ("devices", "id", $n->device); $description = !is_blank($device->description) ? " ($device->description)" : ""; @@ -2219,10 +2211,10 @@ public function print_nat_table ($n, $is_admin = false, $nat_id = false, $admin $icon = $n->type=="static" ? "fa-arrows-h" : "fa-long-arrow-right"; // to html - $html = array(); + $html = []; $html[] = ""; $html[] = ""; + $out .= "\n\t\t"; } $out .= "\n"; } @@ -634,7 +634,7 @@ function dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel $val = $this->val($row,$col,$sheet); if ($val=='') { $val=" "; } else { - $val = htmlentities($val); + $val = htmlentities((string) $val); $link = $this->hyperlink($row,$col,$sheet); if ($link!='') { $val = "$val"; @@ -654,28 +654,28 @@ function dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel // END PUBLIC API - var $boundsheets = array(); - var $formatRecords = array(); - var $fontRecords = array(); - var $xfRecords = array(); - var $colInfo = array(); - var $rowInfo = array(); + public $boundsheets = []; + public $formatRecords = []; + public $fontRecords = []; + public $xfRecords = []; + public $colInfo = []; + public $rowInfo = []; - var $sst = array(); - var $sheets = array(); + public $sst = []; + public $sheets = []; - var $data; - var $_ole; - var $_defaultEncoding = "UTF-8"; - var $_defaultFormat = SPREADSHEET_EXCEL_READER_DEF_NUM_FORMAT; - var $_columnsFormat = array(); - var $_rowoffset = 1; - var $_coloffset = 1; + public $data; + public $_ole; + public $_defaultEncoding = "UTF-8"; + public $_defaultFormat = SPREADSHEET_EXCEL_READER_DEF_NUM_FORMAT; + public $_columnsFormat = []; + public $_rowoffset = 1; + public $_coloffset = 1; /** * List of default date formats used by Excel */ - var $dateFormats = array ( + public $dateFormats = [ 0xe => "m/d/Y", 0xf => "M-d-Y", 0x10 => "d-M", @@ -688,12 +688,12 @@ function dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel 0x2d => "i:s", 0x2e => "H:i:s", 0x2f => "i:s.S" - ); + ]; /** * Default number formats used by Excel */ - var $numberFormats = array( + public $numberFormats = [ 0x1 => "0", 0x2 => "0.00", 0x3 => "#,##0", @@ -714,9 +714,9 @@ function dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel 0x2b => "#,##0.00;(#,##0.00)", // Not exactly 0x2c => "\$#,##0.00;(\$#,##0.00)", // Not exactly 0x30 => "##0.0E+0" - ); + ]; - var $colors = Array( + public $colors = [ 0x00 => "#000000", 0x01 => "#FFFFFF", 0x02 => "#FF0000", @@ -792,9 +792,9 @@ function dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel 0x51 => "#000000", 0x7FFF => "#000000" - ); + ]; - var $lineStyles = array( + public $lineStyles = [ 0x00 => "", 0x01 => "Thin", 0x02 => "Medium", @@ -809,9 +809,9 @@ function dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel 0x0B => "Thin dash-dot-dotted", 0x0C => "Medium dash-dot-dotted", 0x0D => "Slanted medium dash-dotted" - ); + ]; - var $lineStylesCss = array( + public $lineStylesCss = [ "Thin" => "1px solid", "Medium" => "2px solid", "Dashed" => "1px dashed", @@ -825,12 +825,12 @@ function dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel "Thin dash-dot-dotted" => "1px dashed", "Medium dash-dot-dotted" => "2px dashed", "Slanted medium dash-dotte" => "2px dashed" - ); + ]; function read16bitstring($data, $start) { $len = 0; while (ord($data[$start + $len]) + ord($data[$start + $len + 1]) > 0) $len++; - return substr($data, $start, $len); + return substr((string) $data, $start, $len); } // ADDED by Matt Kruse for better formatting @@ -838,12 +838,12 @@ function _format_value($format,$num,$f) { // 49==TEXT format // http://code.google.com/p/php-excel-reader/issues/detail?id=7 if ( (!$f && $format=="%s") || ($f==49) || ($format=="GENERAL") ) { - return array('string'=>$num, 'formatColor'=>null); + return ['string'=>$num, 'formatColor'=>null]; } // Custom pattern can be POSITIVE;NEGATIVE;ZERO // The "text" option as 4th parameter is not handled - $parts = preg_split('/;/',$format); + $parts = preg_split('/;/',(string) $format); $pattern = $parts[0]; // Negative pattern if (count($parts)>2 && $num==0) { @@ -856,7 +856,7 @@ function _format_value($format,$num,$f) { } $color = ""; - $matches = array(); + $matches = []; $color_regex = "/^\[(BLACK|BLUE|CYAN|GREEN|MAGENTA|RED|WHITE|YELLOW)\]/i"; if (preg_match($color_regex,$pattern,$matches)) { $color = strtolower($matches[1]); @@ -864,32 +864,32 @@ function _format_value($format,$num,$f) { } // In Excel formats, "_" is used to add spacing, which we can't do in HTML - $pattern = preg_replace("/_./","",$pattern); + $pattern = preg_replace("/_./","",(string) $pattern); // Some non-number characters are escaped with \, which we don't need - $pattern = preg_replace("/\\\/","",$pattern); + $pattern = preg_replace("/\\\/","",(string) $pattern); // Some non-number strings are quoted, so we'll get rid of the quotes - $pattern = preg_replace("/\"/","",$pattern); + $pattern = preg_replace("/\"/","",(string) $pattern); // TEMPORARY - Convert # to 0 - $pattern = preg_replace("/\#/","0",$pattern); + $pattern = preg_replace("/\#/","0",(string) $pattern); // Find out if we need comma formatting - $has_commas = preg_match("/,/",$pattern); + $has_commas = preg_match("/,/",(string) $pattern); if ($has_commas) { - $pattern = preg_replace("/,/","",$pattern); + $pattern = preg_replace("/,/","",(string) $pattern); } // Handle Percentages - if (preg_match("/\d(\%)([^\%]|$)/",$pattern,$matches)) { + if (preg_match("/\d(\%)([^\%]|$)/",(string) $pattern,$matches)) { $num = $num * 100; - $pattern = preg_replace("/(\d)(\%)([^\%]|$)/","$1%$3",$pattern); + $pattern = preg_replace("/(\d)(\%)([^\%]|$)/","$1%$3",(string) $pattern); } // Handle the number itself $number_regex = "/(\d+)(\.?)(\d*)/"; - if (preg_match($number_regex,$pattern,$matches)) { + if (preg_match($number_regex,(string) $pattern,$matches)) { $left = $matches[1]; $dec = $matches[2]; $right = $matches[3]; @@ -900,13 +900,13 @@ function _format_value($format,$num,$f) { $sprintf_pattern = "%1.".strlen($right)."f"; $formatted = sprintf($sprintf_pattern, $num); } - $pattern = preg_replace($number_regex, $formatted, $pattern); + $pattern = preg_replace($number_regex, $formatted, (string) $pattern); } - return array( + return [ 'string'=>$pattern, 'formatColor'=>$color - ); + ]; } /** @@ -1063,12 +1063,12 @@ function _parse() { $len = ($asciiEncoding)? $numChars : $numChars*2; if ($spos + $len < $limitpos) { - $retstr = substr($data, $spos, $len); + $retstr = substr((string) $data, $spos, $len); $spos += $len; } else{ // found countinue - $retstr = substr($data, $spos, $limitpos - $spos); + $retstr = substr((string) $data, $spos, $limitpos - $spos); $bytesRead = $limitpos - $spos; $charsLeft = $numChars - (($asciiEncoding) ? $bytesRead : ($bytesRead / 2)); $spos = $limitpos; @@ -1085,13 +1085,13 @@ function _parse() { $spos += 1; if ($asciiEncoding && ($option == 0)) { $len = min($charsLeft, $limitpos - $spos); // min($charsLeft, $conlength); - $retstr .= substr($data, $spos, $len); + $retstr .= substr((string) $data, $spos, $len); $charsLeft -= $len; $asciiEncoding = true; } elseif (!$asciiEncoding && ($option != 0)) { $len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength); - $retstr .= substr($data, $spos, $len); + $retstr .= substr((string) $data, $spos, $len); $charsLeft -= $len/2; $asciiEncoding = false; } @@ -1112,7 +1112,7 @@ function _parse() { } $retstr = $newstr; $len = min($charsLeft * 2, $limitpos - $spos); // min($charsLeft, $conlength); - $retstr .= substr($data, $spos, $len); + $retstr .= substr((string) $data, $spos, $len); $charsLeft -= $len/2; $asciiEncoding = false; } @@ -1142,13 +1142,13 @@ function _parse() { if ($version == SPREADSHEET_EXCEL_READER_BIFF8) { $numchars = v($data,$pos+6); if (ord($data[$pos+8]) == 0){ - $formatString = substr($data, $pos+9, $numchars); + $formatString = substr((string) $data, $pos+9, $numchars); } else { - $formatString = substr($data, $pos+9, $numchars*2); + $formatString = substr((string) $data, $pos+9, $numchars*2); } } else { $numchars = ord($data[$pos+6]); - $formatString = substr($data, $pos+7, $numchars*2); + $formatString = substr((string) $data, $pos+7, $numchars*2); } $this->formatRecords[$indexCode] = $formatString; break; @@ -1162,12 +1162,12 @@ function _parse() { // Font name $numchars = ord($data[$pos+18]); if ((ord($data[$pos+19]) & 1) == 0){ - $font = substr($data, $pos+20, $numchars); + $font = substr((string) $data, $pos+20, $numchars); } else { - $font = substr($data, $pos+20, $numchars*2); + $font = substr((string) $data, $pos+20, $numchars*2); $font = $this->_encodeUTF16($font); } - $this->fontRecords[] = array( + $this->fontRecords[] = [ 'height' => $height / 20, 'italic' => !!($option & 2), 'color' => $color, @@ -1175,7 +1175,7 @@ function _parse() { 'bold' => ($weight==700), 'font' => $font, 'raw' => $this->dumpHexData($data, $pos+3, $length) - ); + ]; break; case SPREADSHEET_EXCEL_READER_TYPE_PALETTE: @@ -1206,7 +1206,7 @@ function _parse() { $bgcolor = ""; } - $xf = array(); + $xf = []; $xf['formatIndex'] = $indexCode; $xf['align'] = $align; $xf['fontIndex'] = $fontIndexCode; @@ -1241,25 +1241,25 @@ function _parse() { if (isset($this->formatRecords[$indexCode])) $formatstr = $this->formatRecords[$indexCode]; if ($formatstr!="") { - $tmp = preg_replace("/\;.*/","",$formatstr); - $tmp = preg_replace("/^\[[^\]]*\]/","",$tmp); - if (preg_match("/[^hmsday\/\-:\s\\\,AMP]/i", $tmp) == 0) { // found day and time format + $tmp = preg_replace("/\;.*/","",(string) $formatstr); + $tmp = preg_replace("/^\[[^\]]*\]/","",(string) $tmp); + if (preg_match("/[^hmsday\/\-:\s\\\,AMP]/i", (string) $tmp) == 0) { // found day and time format $isdate = TRUE; $formatstr = $tmp; - $formatstr = str_replace(array('AM/PM','mmmm','mmm'), array('a','F','M'), $formatstr); + $formatstr = str_replace(['AM/PM','mmmm','mmm'], ['a','F','M'], $formatstr); // m/mm are used for both minutes and months - oh SNAP! // This mess tries to fix for that. // 'm' == minutes only if following h/hh or preceding s/ss $formatstr = preg_replace("/(h:?)mm?/","$1i", $formatstr); - $formatstr = preg_replace("/mm?(:?s)/","i$1", $formatstr); + $formatstr = preg_replace("/mm?(:?s)/","i$1", (string) $formatstr); // A single 'm' = n in PHP - $formatstr = preg_replace("/(^|[^m])m([^m]|$)/", '$1n$2', $formatstr); - $formatstr = preg_replace("/(^|[^m])m([^m]|$)/", '$1n$2', $formatstr); + $formatstr = preg_replace("/(^|[^m])m([^m]|$)/", '$1n$2', (string) $formatstr); + $formatstr = preg_replace("/(^|[^m])m([^m]|$)/", '$1n$2', (string) $formatstr); // else it's months $formatstr = str_replace('mm', 'm', $formatstr); // Convert single 'd' to 'j' $formatstr = preg_replace("/(^|[^d])d([^d]|$)/", '$1j$2', $formatstr); - $formatstr = str_replace(array('dddd','ddd','dd','yyyy','yy','hh','h'), array('l','D','d','Y','y','H','g'), $formatstr); + $formatstr = str_replace(['dddd','ddd','dd','yyyy','yy','hh','h'], ['l','D','d','Y','y','H','g'], $formatstr); $formatstr = preg_replace("/ss?/", 's', $formatstr); } } @@ -1270,7 +1270,7 @@ function _parse() { if ($align=='') { $xf['align'] = 'right'; } }else{ // If the format string has a 0 or # in it, we'll assume it's a number - if (preg_match("/[0#]/", $formatstr)) { + if (preg_match("/[0#]/", (string) $formatstr)) { $xf['type'] = 'number'; if ($align=='') { $xf['align']='right'; } } @@ -1295,14 +1295,14 @@ function _parse() { if ($version == SPREADSHEET_EXCEL_READER_BIFF8){ $chartype = ord($data[$pos+11]); if ($chartype == 0){ - $rec_name = substr($data, $pos+12, $rec_length); + $rec_name = substr((string) $data, $pos+12, $rec_length); } else { - $rec_name = $this->_encodeUTF16(substr($data, $pos+12, $rec_length*2)); + $rec_name = $this->_encodeUTF16(substr((string) $data, $pos+12, $rec_length*2)); } }elseif ($version == SPREADSHEET_EXCEL_READER_BIFF7){ - $rec_name = substr($data, $pos+11, $rec_length); + $rec_name = substr((string) $data, $pos+11, $rec_length); } - $this->boundsheets[] = array('name'=>$rec_name,'offset'=>$rec_offset); + $this->boundsheets[] = ['name'=>$rec_name,'offset'=>$rec_offset]; break; } @@ -1392,7 +1392,7 @@ function _parsesheet($spos) { $column = ord($data[$spos+2]) | ord($data[$spos+3])<<8; $xfindex = ord($data[$spos+4]) | ord($data[$spos+5])<<8; $index = $this->_GetInt4d($data, $spos + 6); - $this->addcell($row, $column, $this->sst[$index], array('xfIndex'=>$xfindex) ); + $this->addcell($row, $column, $this->sst[$index], ['xfIndex'=>$xfindex] ); break; case SPREADSHEET_EXCEL_READER_TYPE_MULRK: $row = ord($data[$spos]) | ord($data[$spos+1])<<8; @@ -1410,7 +1410,7 @@ function _parsesheet($spos) { case SPREADSHEET_EXCEL_READER_TYPE_NUMBER: $row = ord($data[$spos]) | ord($data[$spos+1])<<8; $column = ord($data[$spos+2]) | ord($data[$spos+3])<<8; - $tmp = unpack("ddouble", substr($data, $spos + 6, 8)); // It machine machine dependent + $tmp = unpack("ddouble", substr((string) $data, $spos + 6, 8)); // It machine machine dependent if ($this->isDate($spos)) { $numValue = $tmp['double']; } @@ -1446,7 +1446,7 @@ function _parsesheet($spos) { $this->addcell($row, $column, ''); } else { // result is a number, so first 14 bytes are just like a _NUMBER record - $tmp = unpack("ddouble", substr($data, $spos + 6, 8)); // It machine machine dependent + $tmp = unpack("ddouble", substr((string) $data, $spos + 6, 8)); // It machine machine dependent if ($this->isDate($spos)) { $numValue = $tmp['double']; } @@ -1487,7 +1487,7 @@ function _parsesheet($spos) { $xpos += 4; } $len = ($asciiEncoding)?$numChars : $numChars*2; - $retstr =substr($data, $xpos, $len); + $retstr =substr((string) $data, $xpos, $len); $xpos += $len; $retstr = ($asciiEncoding)? $retstr : $this->_encodeUTF16($retstr); } @@ -1496,7 +1496,7 @@ function _parsesheet($spos) { $xpos = $spos; $numChars =ord($data[$xpos]) | (ord($data[$xpos+1]) << 8); $xpos += 2; - $retstr =substr($data, $xpos, $numChars); + $retstr =substr((string) $data, $xpos, $numChars); } $this->addcell($previousRow, $previousCol, $retstr); break; @@ -1509,7 +1509,7 @@ function _parsesheet($spos) { $rowHeight = $rowInfo & 0x7FFF; } $rowHidden = (ord($data[$spos + 12]) & 0x20) >> 5; - $this->rowInfo[$this->sn][$row+1] = Array('height' => $rowHeight / 20, 'hidden'=>$rowHidden ); + $this->rowInfo[$this->sn][$row+1] = ['height' => $rowHeight / 20, 'hidden'=>$rowHidden ]; break; case SPREADSHEET_EXCEL_READER_TYPE_DBCELL: break; @@ -1519,13 +1519,13 @@ function _parsesheet($spos) { $cols = ($length / 2) - 3; for ($c = 0; $c < $cols; $c++) { $xfindex = ord($data[$spos + 4 + ($c * 2)]) | ord($data[$spos + 5 + ($c * 2)])<<8; - $this->addcell($row, $column + $c, "", array('xfIndex'=>$xfindex)); + $this->addcell($row, $column + $c, "", ['xfIndex'=>$xfindex]); } break; case SPREADSHEET_EXCEL_READER_TYPE_LABEL: $row = ord($data[$spos]) | ord($data[$spos+1])<<8; $column = ord($data[$spos+2]) | ord($data[$spos+3])<<8; - $this->addcell($row, $column, substr($data, $spos + 8, ord($data[$spos + 6]) | ord($data[$spos + 7])<<8)); + $this->addcell($row, $column, substr((string) $data, $spos + 8, ord($data[$spos + 6]) | ord($data[$spos + 7])<<8)); break; case SPREADSHEET_EXCEL_READER_TYPE_EOF: $cont = false; @@ -1536,7 +1536,7 @@ function _parsesheet($spos) { $row2 = ord($this->data[$spos+2]) | ord($this->data[$spos+3])<<8; $column = ord($this->data[$spos+4]) | ord($this->data[$spos+5])<<8; $column2 = ord($this->data[$spos+6]) | ord($this->data[$spos+7])<<8; - $linkdata = Array(); + $linkdata = []; $flags = ord($this->data[$spos + 28]); $udesc = ""; $ulink = ""; @@ -1547,7 +1547,7 @@ function _parsesheet($spos) { if (($flags & 0x14) == 0x14 ) { // has a description $uloc += 4; $descLen = ord($this->data[$spos + 32]) | ord($this->data[$spos + 33]) << 8; - $udesc = substr($this->data, $spos + $uloc, $descLen * 2); + $udesc = substr((string) $this->data, $spos + $uloc, $descLen * 2); $uloc += 2 * $descLen; } $ulink = $this->read16bitstring($this->data, $spos + $uloc + 20); @@ -1576,7 +1576,7 @@ function _parsesheet($spos) { $cxf = ord($data[$spos+6]) | ord($data[$spos+7]) << 8; $co = ord($data[$spos+8]); for ($coli = $colfrom; $coli <= $colto; $coli++) { - $this->colInfo[$this->sn][$coli+1] = Array('width' => $cw, 'xf' => $cxf, 'hidden' => ($co & 0x01), 'collapsed' => ($co & 0x1000) >> 12); + $this->colInfo[$this->sn][$coli+1] = ['width' => $cw, 'xf' => $cxf, 'hidden' => ($co & 0x01), 'collapsed' => ($co & 0x1000) >> 12]; } break; @@ -1649,7 +1649,7 @@ function _getCellDetails($spos,$numValue,$column) { $raw = $numValue; } - return array( + return [ 'string'=>$string, 'raw'=>$raw, 'rectype'=>$rectype, @@ -1658,7 +1658,7 @@ function _getCellDetails($spos,$numValue,$column) { 'fontIndex'=>$fontIndex, 'formatColor'=>$formatColor, 'xfIndex'=>$xfindex - ); + ]; } @@ -1719,7 +1719,7 @@ function _encodeUTF16($string) { $result = $string; if ($this->_defaultEncoding){ switch ($this->_encoderFunction){ - case 'iconv' : $result = iconv('UTF-16LE', $this->_defaultEncoding, $string); + case 'iconv' : $result = iconv('UTF-16LE', (string) $this->_defaultEncoding, (string) $string); break; case 'mb_convert_encoding' : $result = mb_convert_encoding($string, $this->_defaultEncoding, 'UTF-16LE' ); break; diff --git a/functions/php-saml b/functions/php-saml deleted file mode 160000 index 5fbf34867..000000000 --- a/functions/php-saml +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5fbf3486704ac9835b68184023ab54862c95f213 diff --git a/functions/php_poly_fill.php b/functions/php_poly_fill.php deleted file mode 100644 index c04a3ce37..000000000 --- a/functions/php_poly_fill.php +++ /dev/null @@ -1,24 +0,0 @@ -1, "error"=>"This script can only be run from cli!"))); } +if(php_sapi_name()!="cli") { die(json_encode(["status"=>1, "error"=>"This script can only be run from cli!"])); } //check input parameters -if(!isset($argv[1]) || !isset($argv[2])) { die(json_encode(array("status"=>1, "error"=>"Missing required input parameters"))); } +if(!isset($argv[1]) || !isset($argv[2])) { die(json_encode(["status"=>1, "error"=>"Missing required input parameters"])); } // test to see if threading is available if($Scan->settings->scanPingType!="fping") -if( !PingThread::available($errmsg) ) { die(json_encode(array("status"=>1, "error"=>"Threading is required for scanning subnets - Error: $errmsg\n"))); } +if( !PingThread::available($errmsg) ) { die(json_encode(["status"=>1, "error"=>"Threading is required for scanning subnets - Error: $errmsg\n"])); } //check script -if($argv[1]!="update"&&$argv[1]!="discovery") { die(json_encode(array("status"=>1, "error"=>"Invalid scan type!"))); } +if($argv[1]!="update"&&$argv[1]!="discovery") { die(json_encode(["status"=>1, "error"=>"Invalid scan type!"])); } //verify cidr if(!is_numeric($argv[2])) { - if($Subnets->verify_cidr_address($argv[2])!==true) { die(json_encode(array("status"=>1, "error"=>"Invalid subnet CIDR address provided"))); } + if($Subnets->verify_cidr_address($argv[2])!==true) { die(json_encode(["status"=>1, "error"=>"Invalid subnet CIDR address provided"])); } } /** @@ -74,7 +73,7 @@ if($Scan->settings->scanPingType=="fping") { # fetch subnet $subnet = $Subnets->fetch_subnet(null, $argv[2]); - $subnet!==false ? : die(json_encode(array("status"=>1, "error"=>"Invalid subnet ID provided"))); + $subnet!==false ? : die(json_encode(["status"=>1, "error"=>"Invalid subnet ID provided"])); //set exit flag to true $Scan->ping_set_exit(false); @@ -85,16 +84,16 @@ $retval = $Scan->ping_address_method_fping_subnet ($subnet_cidr); # errors - if($retval==3) { die(json_encode(array("status"=>1, "error"=>"invalid command line arguments"))); } - if($retval==4) { die(json_encode(array("status"=>1, "error"=>"system call failure"))); } + if($retval==3) { die(json_encode(["status"=>1, "error"=>"invalid command line arguments"])); } + if($retval==4) { die(json_encode(["status"=>1, "error"=>"system call failure"])); } # parse result - if(empty($Scan->fping_result)) { die(json_encode(array("status"=>0, "values"=>array("alive"=>null)))); } + if(empty($Scan->fping_result)) { die(json_encode(["status"=>0, "values"=>["alive"=>null]])); } else { //check each line foreach($Scan->fping_result as $l) { //split - $field = array_filter(pf_explode(" ", $l)); + $field = array_filter(explode(" ", (string) $l)); //create result $out['alive'][] = $Subnets->transform_to_decimal($field[0]); } @@ -128,7 +127,7 @@ } if (empty($threads)) { - die(json_encode(array("status" => 1, "error" => "Unable to spawn scanning pool"))); + die(json_encode(["status" => 1, "error" => "Unable to spawn scanning pool"])); } // wait for all the threads to finish diff --git a/functions/scan/subnet-scan-telnet-execute.php b/functions/scan/subnet-scan-telnet-execute.php index 2159e70dd..b6eb8eb8c 100755 --- a/functions/scan/subnet-scan-telnet-execute.php +++ b/functions/scan/subnet-scan-telnet-execute.php @@ -21,13 +21,12 @@ */ /* functions */ -require_once( dirname(__FILE__) . '/../../functions/functions.php' ); +require_once __DIR__ . "/../functions.php"; +require_once __DIR__ . '/../classes/class.Thread.php'; # Don't corrupt output with php errors! disable_php_errors(); -require( dirname(__FILE__) . '/../../functions/classes/class.Thread.php'); - # initialize user object $Database = new Database_PDO; $Subnets = new Subnets ($Database); @@ -42,11 +41,11 @@ */ //script can only be run from cli -if(php_sapi_name()!="cli") { die(json_encode(array("status"=>1, "error"=>"This script can only be run from cli!"))); } +if(php_sapi_name()!="cli") { die(json_encode(["status"=>1, "error"=>"This script can only be run from cli!"])); } //check input parameters -if(!isset($argv[1]) || !isset($argv[2])) { die(json_encode(array("status"=>1, "error"=>"Missing required input parameters"))); } +if(!isset($argv[1]) || !isset($argv[2])) { die(json_encode(["status"=>1, "error"=>"Missing required input parameters"])); } // test to see if threading is available -if( !PingThread::available($errmsg) ) { die(json_encode(array("status"=>1, "error"=>"Threading is required for scanning subnets - Error: $errmsg\n"))); } +if( !PingThread::available($errmsg) ) { die(json_encode(["status"=>1, "error"=>"Threading is required for scanning subnets - Error: $errmsg\n"])); } /** * Create array of addresses to scan @@ -59,14 +58,14 @@ /* test */ -$ports = pf_explode(";", $argv[2]); +$ports = explode(";", $argv[2]); -$out = array(); +$out = []; //reset array, set each IP together with port foreach($scan_addresses as $k=>$v) { foreach($ports as $p) { - $addresses[] = array("ip"=>$v, "port"=>$p); + $addresses[] = ["ip"=>$v, "port"=>$p]; } } @@ -91,7 +90,7 @@ } if (empty($threads)) { - die(json_encode(array("status" => 1, "error" => "Unable to spawn scanning pool"))); + die(json_encode(["status" => 1, "error" => "Unable to spawn scanning pool"])); } //wait for all the threads to finish diff --git a/functions/scripts/clear_logs.php b/functions/scripts/clear_logs.php index df6f04417..6922aed12 100644 --- a/functions/scripts/clear_logs.php +++ b/functions/scripts/clear_logs.php @@ -12,7 +12,7 @@ if(php_sapi_name()!="cli") { die("This script can only be run from cli!"); } # include required scripts -require_once( dirname(__FILE__) . '/../functions.php' ); +require_once __DIR__ . "/../functions.php"; # initialize objects $Database = new Database_PDO; diff --git a/functions/scripts/discoveryCheck.php b/functions/scripts/discoveryCheck.php index 4fc267b76..30114df10 100755 --- a/functions/scripts/discoveryCheck.php +++ b/functions/scripts/discoveryCheck.php @@ -23,8 +23,8 @@ */ # include required scripts -require_once(dirname(__FILE__) . '/../functions.php'); -require(dirname(__FILE__) . '/../../functions/classes/class.Thread.php'); +require_once __DIR__ . "/../functions.php"; +require_once __DIR__ . '/../classes/class.Thread.php'; # initialize objects $Database = new Database_PDO; @@ -50,7 +50,7 @@ } // set ping statuses -$statuses = pf_explode(";", $Scan->settings->pingStatus); +$statuses = explode(";", (string) $Scan->settings->pingStatus); // set mail override flag if (!isset($config['discovery_check_send_mail'])) { $config['discovery_check_send_mail'] = true; @@ -324,8 +324,8 @@ $content[] = ""; $content[] = " "; $content[] = " "; - $content[] = " "; - $content[] = " "; + $content[] = " "; + $content[] = " "; $content[] = ""; //plain content @@ -343,7 +343,7 @@ $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName); //add all admins to CC foreach ($recepients as $admin) { - $phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name'])); + $phpipam_mail->Php_mailer->addAddress(addslashes((string) $admin['email']), addslashes((string) $admin['name'])); } $phpipam_mail->Php_mailer->Subject = $subject; $phpipam_mail->Php_mailer->msgHTML($content); diff --git a/functions/scripts/find_full_subnets.php b/functions/scripts/find_full_subnets.php index 79c411167..7d97fd21d 100755 --- a/functions/scripts/find_full_subnets.php +++ b/functions/scripts/find_full_subnets.php @@ -4,7 +4,7 @@ if(php_sapi_name()!="cli") { die("This script can only be run from cli!"); } # include required scripts -require_once( dirname(__FILE__) . '/../functions.php' ); +require_once __DIR__ . "/../functions.php"; # limit $limit = 80; // 80 percent threshold diff --git a/functions/scripts/find_untranslated_files.php b/functions/scripts/find_untranslated_files.php index 1738576a2..286c5e479 100755 --- a/functions/scripts/find_untranslated_files.php +++ b/functions/scripts/find_untranslated_files.php @@ -9,15 +9,17 @@ // only from cli if (php_sapi_name() != "cli") { die("Cli only!"); } +# include required scripts +require_once __DIR__ . '/../functions.php'; // search for all translated words and put them to array -$untranslated = pf_explode("\n",shell_exec("cd ".dirname(__FILE__)."/../../ && grep -r '_(' * ")); +$untranslated = explode("\n",(string) shell_exec("cd " . __DIR__ . "/../../ && grep -r '_(' * ")); // loop and search foreach ($untranslated as $u) { // find string $str = get_string_between($u, "_('", "')"); // remove "" and ' - $str = trim($str, "',\""); + $str = trim((string) $str, "',\""); // search for invalid content and remove if (substr($str, 0, 1)!="$") { $all_translations[] = $str; @@ -26,7 +28,7 @@ // find string $str = get_string_between($u, '_("', '")'); // remove "" and ' - $str = trim($str, "',\""); + $str = trim((string) $str, "',\""); // search for invalid content and remove if (substr($str, 0, 1)!="$") { $all_translations[] = $str; @@ -37,7 +39,7 @@ // search all existing translations -$untranslated = pf_explode("\n",shell_exec("cd ".dirname(__FILE__)."/../../ && more functions/locale/en/LC_MESSAGES/phpipam.po")); +$untranslated = explode("\n",(string) shell_exec("cd " . __DIR__ . "/../../ && more functions/locale/en/LC_MESSAGES/phpipam.po")); // loop and create foreach ($untranslated as $u) { // search for string @@ -71,10 +73,9 @@ // returns string between 2 separators function get_string_between($string, $start, $end){ $string = " ".$string; - $ini = strpos($string,$start); + $ini = strpos($string,(string) $start); if ($ini == 0) return ""; - $ini += strlen($start); - $len = strpos($string,$end,$ini) - $ini; + $ini += strlen((string) $start); + $len = strpos($string,(string) $end,$ini) - $ini; return substr($string,$ini,$len); } -?> diff --git a/functions/scripts/merge_databases.php b/functions/scripts/merge_databases.php index 249ec0a3b..79d187df9 100755 --- a/functions/scripts/merge_databases.php +++ b/functions/scripts/merge_databases.php @@ -22,7 +22,7 @@ if(php_sapi_name()!="cli") { die("This script can only be run from cli!"); } # include required scripts -require_once( dirname(__FILE__) . '/../functions.php' ); +require_once __DIR__ . "/../functions.php"; # New database details $db_new['host'] = "localhost"; @@ -65,7 +65,7 @@ */ // set special identifiers -$special_identifiers = array ( +$special_identifiers = [ "changelog" =>"cid", "deviceTypes" =>"tid", "firewallZoneSubnet" =>"zoneId", @@ -73,15 +73,15 @@ "vlans" =>"vlanId", "vrf" =>"vrfId", "widgets" =>"wid" - ); + ]; // ignored tables -$ignored_tables = array("lang", "loginAttempts", "instructions", "settings", "settingsMail", "widgets", "deviceTypes", "requests", "changelog", "logs", "firewallZoneMapping", "firewallZones", "firewallZoneSubnet"); +$ignored_tables = ["lang", "loginAttempts", "instructions", "settings", "settingsMail", "widgets", "deviceTypes", "requests", "changelog", "logs", "firewallZoneMapping", "firewallZones", "firewallZoneSubnet"]; // result array -$highest_ids = array(); // current highest ids -$highest_ids_old = array(); // new highest ids -$highest_ids_append = array(); // diff, to append to importing indexes -$old_data = array(); // old content data -$new_data = array(); // old content data - we will change those values +$highest_ids = []; // current highest ids +$highest_ids_old = []; // new highest ids +$highest_ids_append = []; // diff, to append to importing indexes +$old_data = []; // old content data +$new_data = []; // old content data - we will change those values @@ -96,7 +96,7 @@ // ignored databases if(!in_array($table, $ignored_tables)) { // set id - $identifier = array_key_exists($table, $special_identifiers) ? $special_identifiers[$table] : "id"; + $identifier = array_key_exists((string) $table, $special_identifiers) ? $special_identifiers[$table] : "id"; // fetch old and new $highest_id = $Database->getObjectQuery ($table, "SELECT `$identifier` FROM `$table` ORDER BY `$identifier` DESC LIMIT 0, 1;"); $lowest_id_old = $Database_old->getObjectQuery ($table, "SELECT `$identifier` FROM `$table` ORDER BY `$identifier` ASC LIMIT 0, 1;"); @@ -224,9 +224,9 @@ $new_data[$table][$lk]->type = $highest_ids_append["deviceTypes"] + $value_obj->type; } // sections - if(strlen($value_obj->sections)>1) { - $sections = pf_explode(";", $value_obj->sections); - $sections_new = array(); + if(strlen((string) $value_obj->sections)>1) { + $sections = explode(";", (string) $value_obj->sections); + $sections_new = []; foreach ($sections as $k=>$v) { $sections_new[$highest_ids_append["sections"] + $k] = $v; } @@ -263,7 +263,7 @@ // groups if($value_obj->role!="Administrator") { $groups_tmp = db_json_decode($value_obj->groups, true); - $groups_new = array(); + $groups_new = []; foreach ($groups_tmp as $gid=>$gid2) { $groups_new[$gid+$highest_ids_append["userGroups"]] = $gid+$highest_ids_append["userGroups"]; } @@ -271,8 +271,8 @@ } // favourite subnets if(!is_blank($value_obj->favourite_subnets)) { - $fs_tmp = pf_explode(";", $value_obj->favourite_subnets); - $fs_new = array(); + $fs_tmp = explode(";", (string) $value_obj->favourite_subnets); + $fs_new = []; foreach ($fs_tmp as $gid) { $fs_new[] = $gid+$highest_ids_append["subnets"]; } @@ -299,8 +299,8 @@ $new_data[$table][$lk]->id = $highest_ids_append[$table] + $value_obj->id; // permissions if(!is_blank($value_obj->permissions)) { - $fs_tmp = pf_explode(";", $value_obj->permissions); - $fs_new = array(); + $fs_tmp = explode(";", (string) $value_obj->permissions); + $fs_new = []; foreach ($fs_tmp as $gid) { $fs_new[] = $gid+$highest_ids_append["sections"]; } @@ -315,8 +315,8 @@ $new_data[$table][$lk]->vrfId = $highest_ids_append[$table] + $value_obj->vrfId; // sections if(!is_blank($value_obj->sections)) { - $fs_tmp = pf_explode(";", $value_obj->sections); - $fs_new = array(); + $fs_tmp = explode(";", (string) $value_obj->sections); + $fs_new = []; foreach ($fs_tmp as $gid) { $fs_new[] = $gid+$highest_ids_append["sections"]; } @@ -331,8 +331,8 @@ $new_data[$table][$lk]->id = $highest_ids_append[$table] + $value_obj->id; // permissions if(!is_blank($value_obj->permissions)) { - $fs_tmp = pf_explode(";", $value_obj->permissions); - $fs_new = array(); + $fs_tmp = explode(";", (string) $value_obj->permissions); + $fs_new = []; foreach ($fs_tmp as $gid) { $fs_new[] = $gid+$highest_ids_append["sections"]; } @@ -414,10 +414,10 @@ // src if (!is_blank($value_obj->src)) { $arr = json_encode($value_obj->src, true); - $arr_new = array(); + $arr_new = []; if (is_array($arr)) { foreach ($arr as $type=>$objects) { - $arr_new[$type] = array(); + $arr_new[$type] = []; if(sizeof($objects)>0) { foreach($objects as $ok=>$object) { $arr_new[$type][] = $highest_ids_append[$type] + $object; @@ -430,10 +430,10 @@ // dst if (!is_blank($value_obj->dst)) { $arr = json_encode($value_obj->dst, true); - $arr_new = array(); + $arr_new = []; if (is_array($arr)) { foreach ($arr as $type=>$objects) { - $arr_new[$type] = array(); + $arr_new[$type] = []; if(sizeof($objects)>0) { foreach($objects as $ok=>$object) { $arr_new[$type][] = $highest_ids_append[$type] + $object; diff --git a/functions/scripts/pingCheck.php b/functions/scripts/pingCheck.php index f00533e79..117d56c38 100755 --- a/functions/scripts/pingCheck.php +++ b/functions/scripts/pingCheck.php @@ -30,8 +30,8 @@ */ # include required scripts -require_once(dirname(__FILE__) . '/../functions.php'); -require(dirname(__FILE__) . '/../../functions/classes/class.Thread.php'); +require_once __DIR__ . "/../functions.php"; +require_once __DIR__ . '/../classes/class.Thread.php'; # initialize objects $Database = new Database_PDO; @@ -59,14 +59,14 @@ } // set ping statuses -$statuses = pf_explode(";", $Scan->settings->pingStatus); +$statuses = explode(";", (string) $Scan->settings->pingStatus); // set mail override flag if (!isset($config['ping_check_send_mail'])) { $config['ping_check_send_mail'] = true; } // response for mailing -$address_change = array(); // Array with differences, can be used to email to admins +$address_change = []; // Array with differences, can be used to email to admins // set now for whole script $now = time(); @@ -108,12 +108,12 @@ foreach ($scan_subnets as $s) { //set array for fping if ($Scan->icmp_type == "fping") { - $subnets[] = array( + $subnets[] = [ "id" => $s->id, "cidr" => $Subnets->transform_to_dotted($s->subnet) . "/" . $s->mask, "nsid" => $s->nameserverId, "resolveDNS" => $s->resolveDNS - ); + ]; } $subnet_addresses = $Addresses->fetch_subnet_addresses($s->id) ?: []; @@ -123,7 +123,7 @@ if ($a->excludePing != 1) { //create different array for fping if ($Scan->icmp_type == "fping") { - $addresses2[$s->id][$a->id] = array( + $addresses2[$s->id][$a->id] = [ "id" => $a->id, "ip_addr" => $a->ip_addr, "description" => $a->description, @@ -134,10 +134,10 @@ "state" => $a->state, "resolveDNS" => $s->resolveDNS, "nsid" => $s->nameserverId, - ); + ]; $addresses[$s->id][$a->id] = $a->ip_addr; } else { - $addresses[] = array( + $addresses[] = [ "id" => $a->id, "ip_addr" => $a->ip_addr, "description" => $a->description, @@ -148,7 +148,7 @@ "state" => $a->state, "resolveDNS" => $s->resolveDNS, "nsid" => $s->nameserverId, - ); + ]; } } } @@ -321,13 +321,13 @@ // loop foreach ($address_change as $k => $change) { // null old - set to epoch time - if (strtotime($change['lastSeenOld']) === false) { + if (strtotime((string) $change['lastSeenOld']) === false) { $change['lastSeenOld'] = date("Y-m-d H:i:s", 0); } // set general diffs - $deviceDiff = $now - strtotime($change['lastSeenOld']); // now - device last seen - $agentDiff = $now - strtotime($agent->last_access); // now - last agent check + $deviceDiff = $now - strtotime((string) $change['lastSeenOld']); // now - device last seen + $agentDiff = $now - strtotime((string) $agent->last_access); // now - last agent check // if now online and old offline send mail if ($change['lastSeenNew'] != NULL && $deviceDiff >= (int) $statuses[1]) { @@ -397,7 +397,7 @@ # check for recipients foreach ($Tools->fetch_multiple_objects("users", "role", "Administrator") as $admin) { if ($admin->mailNotify == "Yes") { - $recepients[] = array("name" => $admin->real_name, "email" => $admin->email); + $recepients[] = ["name" => $admin->real_name, "email" => $admin->email]; } } # none? @@ -464,10 +464,10 @@ //content $content[] = ""; - $content[] = " "; + $content[] = " "; $content[] = " "; $content[] = " "; - $content[] = " "; + $content[] = " "; $content[] = " "; $content[] = " "; $content[] = ""; @@ -485,7 +485,7 @@ $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName); //add all admins to CC foreach ($recepients as $admin) { - $phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name'])); + $phpipam_mail->Php_mailer->addAddress(addslashes((string) $admin['email']), addslashes((string) $admin['name'])); } $phpipam_mail->Php_mailer->Subject = $subject; $phpipam_mail->Php_mailer->msgHTML($content); diff --git a/functions/scripts/remove_offline_addresses.php b/functions/scripts/remove_offline_addresses.php index e74ba5395..ec337fdd6 100644 --- a/functions/scripts/remove_offline_addresses.php +++ b/functions/scripts/remove_offline_addresses.php @@ -12,7 +12,7 @@ if(php_sapi_name()!="cli") { die("This script can only be run from cli!"); } # include required scripts -require_once( dirname(__FILE__) . '/../functions.php' ); +require_once __DIR__ . "/../functions.php"; # initialize objects $Database = new Database_PDO; @@ -22,7 +22,7 @@ // response for mailing -$removed_addresses = array(); // Array with differences, can be used to email to admins +$removed_addresses = []; // Array with differences, can be used to email to admins // if config is not set die if(!isset($config['removed_addresses_timelimit'])) { die("Please set timelimit for address removal!"); } @@ -77,7 +77,7 @@ # check for recipients foreach($Subnets->fetch_multiple_objects ("users", "role", "Administrator") as $admin) { if($admin->mailNotify=="Yes") { - $recepients[] = array("name"=>$admin->real_name, "email"=>$admin->email); + $recepients[] = ["name"=>$admin->real_name, "email"=>$admin->email]; } } # none? @@ -127,7 +127,7 @@ $content[] = " "; $content[] = " "; $content[] = " "; - $content[] = " "; + $content[] = " "; $content[] = " "; $content[] = ""; @@ -143,7 +143,7 @@ $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName); //add all admins to CC foreach($recepients as $admin) { - $phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name'])); + $phpipam_mail->Php_mailer->addAddress(addslashes((string) $admin['email']), addslashes((string) $admin['name'])); } $phpipam_mail->Php_mailer->Subject = $subject; $phpipam_mail->Php_mailer->msgHTML($content); @@ -156,5 +156,3 @@ $Result->show_cli("Mailer Error: ".$e->getMessage(), true); } } - -?> diff --git a/functions/scripts/reset-admin-password.php b/functions/scripts/reset-admin-password.php index 7c7bf5ec9..06de1b98e 100755 --- a/functions/scripts/reset-admin-password.php +++ b/functions/scripts/reset-admin-password.php @@ -8,7 +8,7 @@ */ # include required scripts -require_once(dirname(__FILE__) . '/../functions.php'); +require_once __DIR__ . "/../functions.php"; # Don't corrupt output with php errors! disable_php_errors(); @@ -44,7 +44,7 @@ } // validate password -if (strlen($password) < 8) { +if (strlen((string) $password) < 8) { $Result->show_cli("Password must be at least 8 characters long", true); } @@ -88,7 +88,7 @@ # check for recipients foreach ($Admin->fetch_multiple_objects("users", "role", "Administrator") as $admin) { - $recepients[] = array("name" => $admin->real_name, "email" => $admin->email); + $recepients[] = ["name" => $admin->real_name, "email" => $admin->email]; } # none? if (!isset($recepients)) { @@ -122,7 +122,7 @@ $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName); //add all admins to CC foreach ($recepients as $admin) { - $phpipam_mail->Php_mailer->addAddress(addslashes($admin['email']), addslashes($admin['name'])); + $phpipam_mail->Php_mailer->addAddress(addslashes((string) $admin['email']), addslashes((string) $admin['name'])); } $phpipam_mail->Php_mailer->Subject = $subject; $phpipam_mail->Php_mailer->msgHTML($content); diff --git a/functions/scripts/resolveIPaddresses.php b/functions/scripts/resolveIPaddresses.php index 7646811d8..fb408ccb0 100755 --- a/functions/scripts/resolveIPaddresses.php +++ b/functions/scripts/resolveIPaddresses.php @@ -12,7 +12,7 @@ ***********************************************************************/ # include required scripts -require_once( dirname(__FILE__) . '/../functions.php' ); +require_once __DIR__ . "/../functions.php"; # Don't corrupt output with php errors! disable_php_errors(); @@ -86,9 +86,9 @@ # update if change if($hostname['class']=="resolved") { # values - $values = array("hostname"=>$hostname['name'], + $values = ["hostname"=>$hostname['name'], "id"=>$ip->id - ); + ]; # execute if(!$Admin->object_modify("ipaddresses", "edit", "id", $values)) { $Result->show_cli("Failed to update address ".$Subnets->transform_to_dotted($ip->ip_addr)); } @@ -103,4 +103,3 @@ if($config['resolve_verbose'] == true && isset($res)) { print implode("\n", $res)."\n"; } -?> diff --git a/functions/scripts/sync_ad_groups.php b/functions/scripts/sync_ad_groups.php index 8e04bcaf8..c047fa651 100755 --- a/functions/scripts/sync_ad_groups.php +++ b/functions/scripts/sync_ad_groups.php @@ -11,7 +11,7 @@ */ // functions -require_once( dirname(__FILE__) . '/../functions.php' ); +require_once __DIR__ . "/../functions.php"; // AD sync $Database = new Database_PDO; diff --git a/functions/upgrade_queries.php b/functions/upgrade_queries.php index bea08c448..445ec3982 100644 --- a/functions/upgrade_queries.php +++ b/functions/upgrade_queries.php @@ -14,14 +14,14 @@ # include all upgrade queries -include('upgrade_queries/upgrade_queries_1.2.php'); -include('upgrade_queries/upgrade_queries_1.3.php'); -include('upgrade_queries/upgrade_queries_1.4.php'); -include('upgrade_queries/upgrade_queries_1.5.php'); -include('upgrade_queries/upgrade_queries_1.6.php'); -include('upgrade_queries/upgrade_queries_1.7.php'); -include('upgrade_queries/upgrade_queries_1.8.php'); - +require __DIR__ . '/upgrade_queries/upgrade_queries_1.2.php'; +require __DIR__ . '/upgrade_queries/upgrade_queries_1.3.php'; +require __DIR__ . '/upgrade_queries/upgrade_queries_1.4.php'; +require __DIR__ . '/upgrade_queries/upgrade_queries_1.5.php'; +require __DIR__ . '/upgrade_queries/upgrade_queries_1.6.php'; +require __DIR__ . '/upgrade_queries/upgrade_queries_1.7.php'; +require __DIR__ . '/upgrade_queries/upgrade_queries_1.8.php'; +require __DIR__ . '/upgrade_queries/upgrade_queries_1.9.php'; // output if required if(!defined('VERSION') && php_sapi_name()=="cli") { diff --git a/functions/upgrade_queries/upgrade_queries_1.3.php b/functions/upgrade_queries/upgrade_queries_1.3.php index 16933f49f..a56622ce7 100644 --- a/functions/upgrade_queries/upgrade_queries_1.3.php +++ b/functions/upgrade_queries/upgrade_queries_1.3.php @@ -1,8 +1,5 @@
-- config.php file missing! Please copy default config file `config.dist.php` to `config.php` and set configuration! --

phpipam installation documentation: http://phpipam.net/documents/installation/"); } + + -/* site functions */ -require_once( 'functions/functions.php' ); + + phpIPAM installation + -/* API check - process API if requested */ -if ($Rewrite->is_api ()) { - require ("api/index.php"); -} -else { - header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1 - header("Pragma: no-cache"); //HTTP 1.0 - header("Expires: Sat, 26 Jul 2016 05:00:00 GMT"); //Date in the past + - # if not install fetch settings etc - if($GET->page!="install" ) { - # database object - $Database = new Database_PDO; +

phpIPAM v1.9.0 relocated all HTML application code from the project root directory into the \"public\" sub-directory.

- # check if this is a new installation - require('functions/checks/check_db_install.php'); +

Please update your webserver, reverse-proxy or load-balancer configuration to point to the new location.

- # initialize objects - $Result = new Result; - $User = new User ($Database); - $Sections = new Sections ($Database); - $Subnets = new Subnets ($Database); - $Tools = new Tools ($Database); - $Addresses = new Addresses ($Database); - $Log = new Logging ($Database); + - # reset url for base - $url = $User->createURL (); - } - - /** include proper subpage **/ - if($GET->page=="install") { require("app/install/index.php"); } - elseif($GET->page=="2fa") { require("app/login/2fa/index.php"); } - elseif($GET->page=="upgrade") { require("app/upgrade/index.php"); } - elseif($GET->page=="login") { require("app/login/index.php"); } - elseif($GET->page=="temp_share") { require("app/temp_share/index.php"); } - elseif($GET->page=="request_ip") { require("app/login/index.php"); } - elseif($GET->page=="opensearch") { require("app/tools/search/opensearch.php"); } - elseif($GET->page=="saml2") { require("app/saml2/index.php"); } - elseif($GET->page=="saml2-idp") { require("app/saml2/idp.php"); } - else { - # verify that user is logged in - $User->check_user_session(); - - # make upgrade and php build checks - include('functions/checks/check_db_upgrade.php'); # check if database needs upgrade - include('functions/checks/check_php_build.php'); # check for support for PHP modules and database connection - if($GET->switch && $_SESSION['realipamusername'] && $GET->switch == "back"){ - $_SESSION['ipamusername'] = $_SESSION['realipamusername']; - unset($_SESSION['realipamusername']); - print ''; - } - - # set default pagesize - if(!isset($_COOKIE['table-page-size'])) { - setcookie_samesite("table-page-size", 50, 2592000, true, $User->isHttps()); - } - ?> - - - - - - - - - - - - - - - - - - - - - - - - - - <?php print $title; ?> - - - - - - - - - - - - user->ui_theme!="white") { ?> - - - - settings->enableThreshold=="1") { ?> - - - - - - - page=="login" || $GET->page=="request_ip") { ?> - - - - - - - - - - - - - settings->enableLocations=="1") { ?> - - - - - - - - - - - - - - -
- - -
-
jQuery error! -

- Hide -
-
- - -
- - - - - -
-
- - - - - -
- - -
...
- - - - - - is_admin(false) ? ""._("Remove")."" : ""; - if($User->settings->maintaneanceMode == "1") { $Result->show("warning text-center nomargin", " "._("System is running in maintenance mode")." !".$text_append_maint, false); } - ?> - - -
-
- page!="login" && $GET->page!="request_ip" && $GET->page!="upgrade" && $GET->page!="install" && $User->user->passChange!="Yes") include('app/sections/index.php');?> -
-
- - - -
-
- page == "error") { - print "
"; - include_once('app/error.php'); - print "
"; - } - /* We are not "switched" & password reset required */ - elseif(!isset($_SESSION['realipamusername']) && $User->user->passChange=="Yes") { - print "
"; - include_once("app/tools/pass-change/form.php"); - print "
"; - } - /* dashboard */ - elseif(!isset($GET->page) || $GET->page == "dashboard") { - print "
"; - include_once("app/dashboard/index.php"); - print "
"; - } - /* widgets */ - elseif($GET->page=="widgets") { - print "
"; - include_once("app/dashboard/widgets/index.php"); - print "
"; - } - /* all sections */ - elseif($GET->page=="subnets" && is_blank($GET->section)) { - print "
"; - include_once("app/sections/all-sections.php"); - print "
"; - } - /* content */ - else { - print "
$this->mail_font_style$v
"; - $html[] = "".ucwords($n->type)." $n->name $n->description"; + $html[] = "".ucwords((string) $n->type)." $n->name $n->description"; $html[] = ""; $html[] = $actions_menu; $html[] = ""; @@ -2293,11 +2285,11 @@ public function print_nat_table ($n, $is_admin = false, $nat_id = false, $admin public function fetch_all_prefixes ($master = false, $recursive = false) { if($master && !$recursive) { $query = 'select *,concat(prefix,start) as raw from pstnPrefixes where master = ? order by raw asc;'; - $params = array($master); + $params = [$master]; } else { $query = 'select *,concat(prefix,start) as raw from pstnPrefixes order by raw asc;'; - $params = array(); + $params = []; } # fetch try { $prefixes = $this->Database->getObjectsQuery('pstnPrefixes', $query, $params); } @@ -2308,7 +2300,7 @@ public function fetch_all_prefixes ($master = false, $recursive = false) { // for master + recursive we need to go from master id to next 0 (root if($master && $recursive && $prefixes) { $master_set = false; - $out = array(); + $out = []; foreach ($prefixes as $k=>$p) { if($p->id == $master) { @@ -2336,7 +2328,7 @@ public function fetch_all_prefixes ($master = false, $recursive = false) { * @return mixed */ public function prefix_normalize ($number) { - return str_replace(array("+", " ", "-"), "", $number); + return str_replace(["+", " ", "-"], "", (string) $number); } /** @@ -2347,7 +2339,7 @@ public function prefix_normalize ($number) { * @return array */ public function fetch_prefix_parents_recursive ($id) { - $parents = array(); + $parents = []; $root = false; while($root === false) { @@ -2392,7 +2384,7 @@ public function fetch_prefix_parents_recursive ($id) { * @return array */ public function fetch_parents_recursive ($table, $parent_field, $return_field, $id, $reverse = false) { - $parents = array(); + $parents = []; $root = false; while($root === false) { @@ -2435,7 +2427,7 @@ public function check_number_duplicates ($prefix = false, $number = false) { else { $query = "select count(*) as cnt from pstnNumbers where prefix = ? and number = ?;"; # fetch - try { $cnt = $this->Database->getObjectQuery('pstnNumbers', $query, array($prefix, $number)); } + try { $cnt = $this->Database->getObjectQuery('pstnNumbers', $query, [$prefix, $number]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -2462,10 +2454,10 @@ public function print_menu_prefixes($user, $prefixes, $custom_fields) { # set hidden fields $this->get_settings(); $hidden_fields = db_json_decode($this->settings->hiddenCustomFields, true); - $hidden_fields = isset($hidden_fields['subnets']) ? $hidden_fields['subnets'] : array(); + $hidden_fields = isset($hidden_fields['subnets']) ? $hidden_fields['subnets'] : []; # set html array - $html = array(); + $html = []; # root is 0 $rootId = 0; @@ -2478,7 +2470,7 @@ public function print_menu_prefixes($user, $prefixes, $custom_fields) { } # create loop array - $children_prefixes = array(); + $children_prefixes = []; foreach ($prefixes as $item) { $item = (array) $item; $children_prefixes[(int) $item['master']][] = $item; @@ -2492,7 +2484,7 @@ public function print_menu_prefixes($user, $prefixes, $custom_fields) { # initializing $parent as the root $parent = $rootId; - $parent_stack = array(); + $parent_stack = []; # return table content (tr and td's) if (is_array($children_prefixes[$parent])) @@ -2592,7 +2584,7 @@ public function print_menu_prefixes($user, $prefixes, $custom_fields) { //text elseif ($field['type'] == "text") { if (!is_blank($option[$field['name']])) { - $html[] = ""; + $html[] = ""; } else { $html[] = ""; } @@ -2653,15 +2645,15 @@ public function print_menu_prefixes($user, $prefixes, $custom_fields) { public function print_masterprefix_dropdown_menu($prefixId = false) { # initialize vars - $children_prefixes = array(); - $parent_stack_prefixes = array(); - $html = array(); + $children_prefixes = []; + $parent_stack_prefixes = []; + $html = []; $rootId = 0; // root is 0 $parent = $rootId; // initializing $parent as the root # fetch all prefixes in section $all_prefixes = $this->fetch_all_prefixes(); - if (!is_array($all_prefixes)) $all_prefixes = array(); + if (!is_array($all_prefixes)) $all_prefixes = []; # folder or subnet? foreach ($all_prefixes as $s) { $children_prefixes[(int) $s->master][] = (array) $s; @@ -2723,7 +2715,7 @@ public function compress_pstn_ranges($numbers, $state = 4) { # set size $size = sizeof($numbers); // vars - $numbers_formatted = array(); + $numbers_formatted = []; $fIndex = null; # loop through IP addresses @@ -2793,7 +2785,7 @@ public function calculate_prefix_usege ($prefix, $numbers) { $this->get_addresses_types(); # calculate max number of hosts - $details = array(); + $details = []; $details['maxhosts'] = ($prefix->stop - $prefix->start + 1); # get IP address count per address type @@ -2827,7 +2819,7 @@ public function calculate_prefix_usage_sort_numbers ($numbers) { // fetch address types $this->get_addresses_types(); - $count = array(); + $count = []; $count['used'] = 0; //initial sum count # create array of keys with initial value of 0 foreach($this->address_types as $a) { @@ -2852,7 +2844,7 @@ public function calculate_prefix_usage_sort_numbers ($numbers) { * @return mixed */ public function explode_filtered($delimiter, $string) { - $ret = pf_explode($delimiter, $string); + $ret = explode($delimiter, $string); if (!is_array($ret)) return false; return array_filter($ret); @@ -2953,7 +2945,7 @@ public function fetch_location_objects ($id = false, $count = false) { * * @return false|array */ - public function fetch_all_circuits ($custom_circuit_fields = array ()) { + public function fetch_all_circuits ($custom_circuit_fields = []) { // set query $query[] = "select"; $query[] = "c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,c.comment,c.customer_id,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status"; @@ -2968,7 +2960,7 @@ public function fetch_all_circuits ($custom_circuit_fields = array ()) { $query[] = "from circuits as c, circuitProviders as p where c.provider = p.id"; $query[] = "order by c.cid asc;"; // fetch - try { $circuits = $this->Database->getObjectsQuery('circuits', implode("\n", $query), array()); } + try { $circuits = $this->Database->getObjectsQuery('circuits', implode("\n", $query), []); } catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); } @@ -3033,7 +3025,7 @@ public function fetch_all_logical_circuit_members ($logical_circuit_id) { * * @return false|array */ - public function fetch_all_provider_circuits ($provider_id, $custom_circuit_fields = array ()) { + public function fetch_all_provider_circuits ($provider_id, $custom_circuit_fields = []) { // set query $query[] = "select"; $query[] = "c.id,c.cid,c.type,c.device1,c.location1,c.device2,c.location2,p.name,p.description,p.contact,c.capacity,p.id as pid,c.status"; @@ -3048,7 +3040,7 @@ public function fetch_all_provider_circuits ($provider_id, $custom_circuit_field $query[] = "from circuits as c, circuitProviders as p where c.provider = p.id and c.provider = ?"; $query[] = "order by c.cid asc;"; // fetch - try { $circuits = $this->Database->getObjectsQuery('circuits', implode("\n", $query), array($provider_id)); } + try { $circuits = $this->Database->getObjectsQuery('circuits', implode("\n", $query), [$provider_id]); } catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); } @@ -3073,7 +3065,7 @@ public function fetch_all_device_circuits ($device_id) { from circuits as c, circuitProviders as p where c.provider = p.id and (c.device1 = :deviceid or c.device2 = :deviceid) order by c.cid asc;"; // fetch - try { $circuits = $this->Database->getObjectsQuery('circuits', $query, array("deviceid"=>$device_id)); } + try { $circuits = $this->Database->getObjectsQuery('circuits', $query, ["deviceid"=>$device_id]); } catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); } @@ -3112,14 +3104,14 @@ public function reformat_circuit_location ($deviceId = null, $locationId = null) return false; } else { - $array = array ( + $array = [ "type" => "devices", "id" => $device->id, "name" => $device->hostname, "icon" => "", "location" => is_null($device->location)||$device->location==0 ? NULL : $device->location, "rack" => is_null($device->rack)||$device->rack==0 ? NULL : $device->rack - ); + ]; // check rack location if not configured if ($array['location']==NULL && $array['rack']!=NULL) { $rack_location = $this->fetch_object ("racks", "id", $array['rack']); @@ -3138,14 +3130,14 @@ public function reformat_circuit_location ($deviceId = null, $locationId = null) return false; } else { - return array ( + return [ "type" => "locations", "id" => $location->id, "name" => $location->name, "icon" => "fa-map", "location" => $location->id, "rack" => NULL - ); + ]; } } else { @@ -3191,7 +3183,7 @@ public function fetch_all_domains_and_vlans ($search = false) { // filter if requested if ($search !== false && sizeof($domains)>0) { foreach ($domains as $k=>$d) { - if (strpos($d->number, $search)===false && strpos($d->name, $search)===false && strpos($d->description, $search)===false) { + if (strpos((string) $d->number, $search)===false && strpos((string) $d->name, $search)===false && strpos((string) $d->description, $search)===false) { unset($domains[$k]); } } @@ -3324,15 +3316,15 @@ public function parse_import_file ($filetype, $subnet, $custom_address_fields) { * @return mixed */ private function parse_import_file_xls ($subnet, $custom_address_fields) { - # get excel object - require_once(dirname(__FILE__).'/../../functions/php-excel-reader/excel_reader2.php'); //excel reader 2.21 - $data = new Spreadsheet_Excel_Reader(dirname(__FILE__) . '/../../app/subnets/import-subnet/upload/import.xls', false, 'utf-8'); + //excel reader 2.21 + require_once __DIR__ . '/../php-excel-reader/excel_reader2.php'; + $data = new Spreadsheet_Excel_Reader(__DIR__ . '/../../public/app/subnets/import-subnet/upload/import.xls', false, 'utf-8'); //get number of rows $numRows = $data->rowcount(0); $numRows++; - $outFile = array(); + $outFile = []; // set delimiter $this->csv_delimiter = ";"; @@ -3375,7 +3367,7 @@ private function parse_import_file_xls ($subnet, $custom_address_fields) { */ private function parse_import_file_csv () { // get file to string - $handle = fopen(dirname(__FILE__) . '/../../app/subnets/import-subnet/upload/import.csv', "r"); + $handle = fopen(__DIR__ . '/../../public/app/subnets/import-subnet/upload/import.csv', "r"); if ($handle) { while (($outFile[] = fgets($handle)) !== false) {} fclose($handle); @@ -3390,7 +3382,7 @@ private function parse_import_file_csv () { /* validate IP */ foreach($outFile as $k=>$v) { //put it to array - $field = str_getcsv ($v, $this->csv_delimiter); + $field = str_getcsv ($v, $this->csv_delimiter, '"', "\\"); if(!filter_var($field[0], FILTER_VALIDATE_IP)) { unset($outFile[$k]); @@ -3447,7 +3439,7 @@ public function set_csv_delimiter ($outFile) { * @return void */ private function parse_validate_file ($outFile, $subnet) { - $result = array(); + $result = []; $errors = 0; # present ? @@ -3458,7 +3450,7 @@ private function parse_validate_file ($outFile, $subnet) { $line = $this->convert_encoding_to_UTF8($line); //put it to array - $field = str_getcsv ($line, $this->csv_delimiter); + $field = str_getcsv ($line, $this->csv_delimiter, '"', "\\"); //verify IP address if(!filter_var($field[0], FILTER_VALIDATE_IP)) { $class = "danger"; $errors++; } @@ -3573,7 +3565,7 @@ public function fetch_addresses_for_export () { */ public function verify_translation ($code) { //verify that proper files exist - return !file_exists("functions/locale/$code/LC_MESSAGES/phpipam.mo") ? false : true; + return !file_exists(__DIR__ . "/../locale/$code/LC_MESSAGES/phpipam.mo") ? false : true; } /** @@ -3585,9 +3577,9 @@ public function verify_translation ($code) { */ public function get_translation_version ($code) { //check for version - $ver = shell_exec("grep 'Project-Id-Version:' ".dirname(__FILE__)."/../locale/$code/LC_MESSAGES/phpipam.po"); + $ver = shell_exec("grep 'Project-Id-Version:' " . __DIR__ . "/../locale/$code/LC_MESSAGES/phpipam.po"); //parse - $ver = str_replace(array("Project-Id-Version:", " ", '"', "#",'\n', ":"), "", $ver); + $ver = str_replace(["Project-Id-Version:", " ", '"', "#",'\n', ":"], "", (string) $ver); //return version return $ver; } diff --git a/functions/classes/class.User.php b/functions/classes/class.User.php index d3382a277..6c1b73d63 100644 --- a/functions/classes/class.User.php +++ b/functions/classes/class.User.php @@ -110,7 +110,7 @@ class User extends Common_functions { * * @var array */ - public $themes = array("white", "dark"); + public $themes = ["white", "dark"]; /** * (json) parameters for authentication @@ -527,7 +527,7 @@ private function set_redirect_cookie () { return; } - setcookie_samesite("phpipamredirect", preg_replace('/^\/+/', '/', $uri), 120, true, $this->isHttps()); + setcookie_samesite("phpipamredirect", preg_replace('/^\/+/', '/', (string) $uri), 120, true, $this->isHttps()); } /** @@ -558,7 +558,7 @@ public function set_maintaneance_mode ($on = false) { # set mode status $maintaneance_mode = $on ? "1" : "0"; # execute - try { $this->Database->updateObject("settings", array("id"=>1, "maintaneanceMode"=>$maintaneance_mode), "id"); } + try { $this->Database->updateObject("settings", ["id"=>1, "maintaneanceMode"=>$maintaneance_mode], "id"); } catch (Exception $e) {} } @@ -637,7 +637,7 @@ public function get_default_lang () { * @return array */ public function fetch_available_auth_method_types () { - return array("AD", "LDAP", "NetIQ", "Radius", "SAML2"); + return ["AD", "LDAP", "NetIQ", "Radius", "SAML2"]; } @@ -668,18 +668,18 @@ public function fetch_favourite_subnets () { # ok else { # store to array - $subnets = pf_explode(";", $this->user->favourite_subnets); + $subnets = explode(";", (string) $this->user->favourite_subnets); $subnets = array_filter($subnets); if(sizeof($subnets)>0) { // init - $fsubnets = array(); + $fsubnets = []; # fetch details for each subnet foreach($subnets as $id) { $query = "select `su`.`id`, `su`.`id` as `subnetId`,`se`.`id` as `sectionId`, `subnet`, `mask`,`isFull`,`su`.`description`,`se`.`description` as `section`, `vlanId`, `isFolder` from `subnets` as `su`, `sections` as `se` where `su`.`id` = ? and `su`.`sectionId` = `se`.`id` limit 1;"; - try { $fsubnet = $this->Database->getObjectQuery('subnets', $query, array($id)); } + try { $fsubnet = $this->Database->getObjectQuery('subnets', $query, [$id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage()); return false; @@ -719,11 +719,11 @@ public function edit_favourite($action, $subnetId) { */ private function remove_favourite ($subnetId) { # set old favourite subnets - $old_favourites = pf_explode(";", $this->user->favourite_subnets); + $old_favourites = explode(";", (string) $this->user->favourite_subnets); # set new - $new_favourites = implode(";", array_diff($old_favourites, array($subnetId))); + $new_favourites = implode(";", array_diff($old_favourites, [$subnetId])); # update - try { $this->Database->updateObject("users", array("favourite_subnets"=>$new_favourites, "id"=>$this->user->id), "id"); } + try { $this->Database->updateObject("users", ["favourite_subnets"=>$new_favourites, "id"=>$this->user->id], "id"); } catch (Exception $e) { return false; } @@ -739,12 +739,12 @@ private function remove_favourite ($subnetId) { */ private function add_favourite ($subnetId) { # set old favourite subnets - $old_favourites = pf_explode(";", $this->user->favourite_subnets); - $old_favourites = is_array($old_favourites) ? $old_favourites : array(); + $old_favourites = explode(";", (string) $this->user->favourite_subnets); + $old_favourites = is_array($old_favourites) ? $old_favourites : []; # set new - $new_favourites = implode(";",array_merge(array($subnetId), $old_favourites)); + $new_favourites = implode(";",array_merge([$subnetId], $old_favourites)); # update - try { $this->Database->updateObject("users", array("favourite_subnets"=>$new_favourites, "id"=>$this->user->id), "id"); } + try { $this->Database->updateObject("users", ["favourite_subnets"=>$new_favourites, "id"=>$this->user->id], "id"); } catch (Exception $e) { return false; } @@ -760,7 +760,7 @@ private function add_favourite ($subnetId) { */ public function is_subnet_favourite ($subnetId) { # check if in array - $subnets = pf_explode(";", $this->user->favourite_subnets); + $subnets = explode(";", (string) $this->user->favourite_subnets); $subnets = array_filter($subnets); # result return in_array($subnetId, $subnets) ? true : false; @@ -807,37 +807,50 @@ public function is_folder_favourite ($subnetId) { */ public function authenticate ($username, $password, $saml = false) { # first we need to check if username exists - $this->fetch_user_details ($username); + $this->fetch_user_details($username); # set method type if set, otherwise presume local auth $this->authmethodid = !is_blank(@$this->user->authMethod) ? $this->user->authMethod : 1; # 2fa - if ($this->user->{'2fa'}==1) { + if ($this->user->{'2fa'} == 1) { $this->twofa = true; } # get authentication method details - $this->get_auth_method_type (); + $this->get_auth_method_type(); - # authenticate based on name of auth method - if(!method_exists($this, $this->authmethodtype)) { - $this->Log->write ( _("User login"), _('Error: Invalid authentication method'), 2 ); - $this->Result->show("danger", _("Error: Invalid authentication method"), true); + # set method name variable + $authmethodtype = $this->authmethodtype; + + if ($saml !== false) { + $authmethodtype = 'auth_SAML2'; + } elseif ($authmethodtype == "auth_SAML2") { + $this->Result->show("danger", _("Please use") . " " . _("login") . "!", true); } - else { - # set method name variable - $authmethodtype = $this->authmethodtype; - if($saml !== false) { - $authmethodtype = 'auth_SAML2'; - } - # is auth_SAML and $saml == false throw error - if ($authmethodtype=="auth_SAML2" && $saml===false) { - $this->Result->show("danger", _("Please use")." "._("login")."!", true); - } - else { - # authenticate - $this->{$authmethodtype} ($username, $password); - } + + # authenticate + switch ($authmethodtype) { + case 'auth_local': + $this->auth_local($username, $password); + break; + case 'auth_AD': + $this->auth_AD($username, $password); + break; + case 'auth_LDAP': + $this->auth_LDAP($username, $password); + break; + case 'auth_NetIQ': + $this->auth_NetIQ($username, $password); + break; + case 'auth_Radius': + $this->auth_Radius($username, $password); + break; + case 'auth_SAML2': + $this->auth_SAML2($username); + break; + default: + $this->Log->write(_("User login"), _('Error: Invalid authentication method'), 2); + $this->Result->show("danger", _("Error: Invalid authentication method"), true); } } @@ -939,7 +952,7 @@ private function get_auth_method_type () { */ private function auth_local ($username, $password) { # auth ok - if(hash_equals($this->user->password, crypt($password, $this->user->password))) { + if(hash_equals($this->user->password, crypt((string) $password, (string) $this->user->password))) { # check login restrictions for authenticated user $this->check_login_restrictions ($username); @@ -1019,12 +1032,12 @@ private function show_http_login () { */ private function directory_connect ($authparams) { # adLDAP script - require(dirname(__FILE__) . "/../adLDAP/src/adLDAP.php"); - $dirparams = Array(); + require_once __DIR__ . '/../adLDAP/src/adLDAP.php'; + $dirparams = []; $dirparams['base_dn'] = @$authparams['base_dn']; $dirparams['ad_port'] = @$authparams['ad_port']; $dirparams['account_suffix'] = @$authparams['account_suffix']; - $dirparams['domain_controllers'] = pf_explode(";", str_replace(" ", "", $authparams['domain_controllers'])); + $dirparams['domain_controllers'] = explode(";", str_replace(" ", "", (string) $authparams['domain_controllers'])); // set ssl and tls separate for ldap and AD if ($this->ldap) { // set ssl and tls @@ -1157,63 +1170,6 @@ private function auth_NetIQ ($username, $password) { $this->auth_AD ("cn=".$username, $password); } - /** - * Authenticates user on radius server - * - * @access private - * @param mixed $username - * @param mixed $password - * @return void - */ - private function auth_radius_legacy ($username, $password) { - # decode radius parameters - $params = db_json_decode($this->authmethodparams); - - # check for socket support ! - if(!in_array("sockets", get_loaded_extensions())) { - $this->Log->write( _("Radius login"), _("php Socket extension missing"), 2 ); - $this->Result->show("danger", _("php Socket extension missing"), true); - } - - # initialize radius class - require( dirname(__FILE__) . '/class.Radius.php' ); - $Radius = new Radius ($params->hostname, $params->secret, $params->suffix, $params->timeout, $params->port); - //debugging - $this->debugging!==true ? : $Radius->SetDebugMode(TRUE); - - # authenticate - $auth = $Radius->AccessRequest($username, $password); - # debug? - if($this->debugging) { - print "
";
-            print(escape_input(implode("
", $Radius->debug_text))); - print "
"; - } - - # authenticate user - if($auth) { - # check login restrictions for authenticated user - $this->check_login_restrictions ($username); - # save to session - $this->write_session_parameters (); - - $this->Log->write( _("Radius login"), _("User")." ".$this->user->real_name." "._("logged in via radius"), 0, $username ); - $this->Result->show("success", _("Radius login successful")); - - # write last logintime - $this->update_login_time (); - # remove possible blocked IP - $this->block_remove_entry (); - } - else { - # add blocked count - $this->block_ip (); - $this->log_failed_access ($username); - $this->Log->write( _("Radius login"), _("Failed to authenticate user on radius server"), 2, $username ); - $this->Result->show("danger", _("Invalid username or password"), true); - } - } - /** * Authenticates user on radius server * @@ -1224,20 +1180,12 @@ private function auth_radius_legacy ($username, $password) { * @param mixed $password * @return void */ - private function auth_radius ($username, $password) { + private function auth_Radius ($username, $password) { # decode radius parameters $params = db_json_decode($this->authmethodparams); - # Valdate composer - if($this->composer_has_errors(["dapphp/radius"])) { - $this->Result->show("danger", _("Error in authentication method. Please contact administrator").".", true); - } - - # Composer - require __DIR__ . '/../vendor/autoload.php'; - // init client - $client = new Radius(); + $client = new \Dapphp\Radius\Radius(); // set params $client->setServer($params->hostname) ->setSecret($params->secret) @@ -1310,10 +1258,9 @@ private function auth_radius ($username, $password) { * * @access private * @param mixed $username - * @param mixed $password (default: null) * @return void */ - private function auth_SAML2 ($username, $password = null) { + private function auth_SAML2 ($username) { # check login restrictions for authenticated user $this->check_login_restrictions ($username); @@ -1606,7 +1553,7 @@ public function crypt_user_pass ($input) { # get prefix $prefix = $this->detect_crypt_type (); # return crypted variable - return crypt($input, $prefix.$salt); + return crypt((string) $input, $prefix.$salt); } /** @@ -1618,7 +1565,7 @@ public function crypt_user_pass ($input) { private function detect_crypt_type () { if(CRYPT_SHA512 == 1) { return '$6$rounds=3000$'; } elseif(CRYPT_SHA256 == 1) { return '$5$rounds=3000$'; } - elseif(CRYPT_BLOWFISH == 1) { return '$2y$'.str_pad(rand(4,31),2,0, STR_PAD_LEFT).'$'; } + elseif(CRYPT_BLOWFISH == 1) { return '$2y$'.str_pad(random_int(4,31),2,0, STR_PAD_LEFT).'$'; } elseif(CRYPT_MD5 == 1) { return '$5$rounds=3000$'; } else { $this->Result->show("danger", _("No crypt types supported"), true); } } @@ -1645,7 +1592,7 @@ public function return_crypt_type () { * @return void */ public function update_user_pass ($password) { - try { $this->Database->updateObject("users", array("password"=>$this->crypt_user_pass ($password), "passChange"=>"No", "id"=>$this->user->id), "id"); } + try { $this->Database->updateObject("users", ["password"=>$this->crypt_user_pass ($password), "passChange"=>"No", "id"=>$this->user->id], "id"); } catch (Exception $e) { $this->Result->show("danger", $e->getMessage(), true); } $this->Result->show("success", _("Hi").", ".$this->user->real_name.", "._("your password was updated").". Dashboard", false); @@ -1726,7 +1673,7 @@ public function self_update(Params $post): bool { */ public function self_update_widgets ($widgets) { # update - try { $this->Database->updateObject("users", array("widgets"=>$widgets, "id"=>$this->user->id)); } + try { $this->Database->updateObject("users", ["widgets"=>$widgets, "id"=>$this->user->id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); return false; @@ -1745,7 +1692,7 @@ public function update_login_time () { # fix for older versions if($this->settings->version!="1.1") { # update - try { $this->Database->updateObject("users", array("lastLogin"=>date("Y-m-d H:i:s"), "id"=>$this->user->id)); } + try { $this->Database->updateObject("users", ["lastLogin"=>date("Y-m-d H:i:s"), "id"=>$this->user->id]); } catch (Exception $e) { $this->Result->show("danger", _("Error: ").$e->getMessage(), false); return false; @@ -1761,7 +1708,7 @@ public function update_login_time () { */ public function update_activity_time () { # update - try { $this->Database->updateObject("users", array("lastActivity"=>date("Y-m-d H:i:s"), "id"=>$this->user->id)); } + try { $this->Database->updateObject("users", ["lastActivity"=>date("Y-m-d H:i:s"), "id"=>$this->user->id]); } catch (Exception $e) { } } @@ -1935,11 +1882,11 @@ public function get_user_permissions_from_json ($json) { $cached_item = $this->cache_check('get_user_permissions_from_json', $json); if(is_object($cached_item)) return $cached_item->result; - $groups = array(); + $groups = []; foreach((array) db_json_decode($json, true) as $group_id => $perm) { - $group_details = $this->groups_parse (array($group_id)); + $group_details = $this->groups_parse ([$group_id]); - $tmp = array(); + $tmp = []; $tmp['group_id'] = $group_id; $tmp['permission'] = $perm; $tmp['name'] = $group_details[$group_id]['g_name']; @@ -1969,11 +1916,11 @@ private function groups_parse ($group_ids) { // group details $group = $this->fetch_object ("userGroups", "g_id", $g_id); $out[$group->g_id] = (array) $group; - $out[$group->g_id]['members'] = $this->fetch_multiple_objects("users", "groups", "%\"$g_id\"%", "real_name", true, true, array("username")); + $out[$group->g_id]['members'] = $this->fetch_multiple_objects("users", "groups", "%\"$g_id\"%", "real_name", true, true, ["username"]); } } # return array of groups - return isset($out) ? $out : array(); + return isset($out) ? $out : []; } /** @@ -2017,7 +1964,7 @@ public function get_l2domain_permissions ($l2domain) { $max_permission = 0; - $ids = pf_explode(";", $valid_sections); + $ids = explode(";", (string) $valid_sections); foreach($ids as $id) { $section = $this->fetch_object("sections", "id", $id); @@ -2083,7 +2030,7 @@ private function register_user_module_permissions () { if (!is_array($permissions)) { $this->user->{'perm_'.$m} = 0; } - elseif(array_key_exists($m, $permissions)) { + elseif(array_key_exists((string) $m, $permissions)) { $this->user->{'perm_'.$m} = $permissions[$m]; } else { @@ -2118,7 +2065,7 @@ public function get_module_permissions ($module_name = "") { return User::ACCESS_RWA; if (!is_object($this->user) || !property_exists($this->user, 'perm_'.$module_name)) - return USER::ACCESS_NONE; + return User::ACCESS_NONE; return $this->user->{'perm_'.$module_name}; } diff --git a/functions/composer.json b/functions/composer.json deleted file mode 100644 index 1fa21abd0..000000000 --- a/functions/composer.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "require": { - "firehed/webauthn": "dev-main", - "firehed/cbor": "^0.1.0", - "dapphp/radius": "^3.0" - } -} diff --git a/functions/composer.lock b/functions/composer.lock deleted file mode 100644 index 33a26a30e..000000000 --- a/functions/composer.lock +++ /dev/null @@ -1,191 +0,0 @@ -{ - "_readme": [ - "This file locks the dependencies of your project to a known state", - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", - "This file is @generated automatically" - ], - "content-hash": "23e5bbc9dd993a1c1824330765401dfd", - "packages": [ - { - "name": "dapphp/radius", - "version": "v3.0.0", - "source": { - "type": "git", - "url": "https://github.com/dapphp/radius.git", - "reference": "023f538e46d20fa285f55dd65d7054fb9b370a82" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/dapphp/radius/zipball/023f538e46d20fa285f55dd65d7054fb9b370a82", - "reference": "023f538e46d20fa285f55dd65d7054fb9b370a82", - "shasum": "" - }, - "require": { - "php": "^7.3 || ^8.0" - }, - "require-dev": { - "phpunit/phpunit": "^9.5.13" - }, - "suggest": { - "ext-openssl": "To support hashing required by Pear_CHAP" - }, - "type": "library", - "autoload": { - "psr-0": { - "Crypt_CHAP_": "lib/" - }, - "psr-4": { - "Dapphp\\Radius\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "LGPL-3.0-or-later" - ], - "authors": [ - { - "name": "Drew Phillips", - "email": "drew@drew-phillips.com", - "homepage": "https://drew-phillips.com/" - }, - { - "name": "SysCo/al", - "homepage": "http://developer.sysco.ch/php/" - } - ], - "description": "A pure PHP RADIUS client based on the SysCo/al implementation", - "homepage": "https://github.com/dapphp/radius", - "keywords": [ - "Authentication", - "authorization", - "chap", - "ms-chap", - "ms-chap v2", - "pap", - "radius", - "rfc1994", - "rfc2284", - "rfc2759", - "rfc2865", - "rfc2869" - ], - "support": { - "issues": "https://github.com/dapphp/radius/issues", - "source": "https://github.com/dapphp/radius/tree/v3.0.0" - }, - "time": "2022-01-26T04:33:16+00:00" - }, - { - "name": "firehed/cbor", - "version": "0.1.0", - "source": { - "type": "git", - "url": "https://github.com/Firehed/cbor-php.git", - "reference": "eef67b1b5fdf90a3688fc8d9d13afdaf342c4b80" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Firehed/cbor-php/zipball/eef67b1b5fdf90a3688fc8d9d13afdaf342c4b80", - "reference": "eef67b1b5fdf90a3688fc8d9d13afdaf342c4b80", - "shasum": "" - }, - "require-dev": { - "phpunit/phpunit": "^8.1" - }, - "suggest": { - "ext-bcmath": "Enables parsing of very large values" - }, - "type": "library", - "autoload": { - "psr-4": { - "Firehed\\CBOR\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Eric Stern", - "email": "eric@ericstern.com" - } - ], - "description": "CBOR decoder", - "homepage": "https://github.com/Firehed/CBOR", - "keywords": [ - "cbor" - ], - "support": { - "issues": "https://github.com/Firehed/cbor-php/issues", - "source": "https://github.com/Firehed/cbor-php/tree/master" - }, - "time": "2019-05-14T06:31:13+00:00" - }, - { - "name": "firehed/webauthn", - "version": "dev-main", - "source": { - "type": "git", - "url": "https://github.com/Firehed/webauthn-php.git", - "reference": "e263a3553360d63131af707f3e563b151f4661b9" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Firehed/webauthn-php/zipball/e263a3553360d63131af707f3e563b151f4661b9", - "reference": "e263a3553360d63131af707f3e563b151f4661b9", - "shasum": "" - }, - "require": { - "ext-hash": "*", - "ext-openssl": "*", - "firehed/cbor": "^0.1.0", - "php": "^8.1" - }, - "require-dev": { - "maglnet/composer-require-checker": "^4.1", - "mheap/phpunit-github-actions-printer": "^1.5", - "nikic/php-parser": "^4.14", - "phpstan/phpstan": "^1.0", - "phpstan/phpstan-phpunit": "^1.0", - "phpstan/phpstan-strict-rules": "^1.0", - "phpunit/phpunit": "^9.3", - "squizlabs/php_codesniffer": "^3.5" - }, - "default-branch": true, - "type": "library", - "autoload": { - "psr-4": { - "Firehed\\WebAuthn\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Eric Stern", - "email": "eric@ericstern.com" - } - ], - "description": "Web Authentication", - "support": { - "issues": "https://github.com/Firehed/webauthn-php/issues", - "source": "https://github.com/Firehed/webauthn-php/tree/main" - }, - "time": "2023-12-10T19:00:08+00:00" - } - ], - "packages-dev": [], - "aliases": [], - "minimum-stability": "stable", - "stability-flags": { - "firehed/webauthn": 20 - }, - "prefer-stable": false, - "prefer-lowest": false, - "platform": [], - "platform-dev": [], - "plugin-api-version": "2.6.0" -} diff --git a/functions/functions.php b/functions/functions.php old mode 100755 new mode 100644 index c34a283a0..35a539654 --- a/functions/functions.php +++ b/functions/functions.php @@ -1,99 +1,108 @@ 'tcp://'.Config::ValueOf('proxy_server').':'.Config::ValueOf('proxy_port'), - 'request_fulluri' => true]; - - if (Config::ValueOf('proxy_use_auth') == true) { - $proxy_auth = base64_encode(Config::ValueOf('proxy_user').':'.Config::ValueOf('proxy_pass')); - $proxy_settings['header'] = "Proxy-Authorization: Basic ".$proxy_auth; - } - stream_context_set_default (['http' => $proxy_settings]); +// config file ------------------ +require_once __DIR__ . '/classes/class.Config.php'; +$config = Config::ValueOf('config'); - /* for debugging proxy config uncomment next line */ - // var_dump(stream_context_get_options(stream_context_get_default())); +// proxy to use for every internet access like update check +if (Config::ValueOf('proxy_enabled')) { + $proxy_settings = [ + 'proxy' => 'tcp://' . Config::ValueOf('proxy_server') . ':' . Config::ValueOf('proxy_port'), + 'request_fulluri' => true + ]; + + if (Config::ValueOf('proxy_use_auth')) { + $proxy_auth = base64_encode(Config::ValueOf('proxy_user') . ':' . Config::ValueOf('proxy_pass')); + $proxy_settings['header'] = "Proxy-Authorization: Basic " . $proxy_auth; + } + stream_context_set_default(['http' => $proxy_settings]); + + // for debugging proxy config uncomment next line */ + // var_dump(stream_context_get_options(stream_context_get_default())); } -/* Set UI language */ +// Set UI language set_ui_language(); -/* @http only cookies ------------------- */ -if(php_sapi_name()!="cli") - ini_set('session.cookie_httponly', 1); - -/* @debugging functions ------------------- */ -if(Config::ValueOf('debugging')==true) { - ini_set('display_errors', 1); - ini_set('display_startup_errors', 1); - error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED); -} -else { - disable_php_errors(); - error_reporting(E_ERROR | E_WARNING); +//* http only cookies ------------------- +if (php_sapi_name() != "cli") + ini_set('session.cookie_httponly', 1); + +// debugging functions ------------------- +if (Config::ValueOf('debugging')) { + ini_set('display_errors', 1); + ini_set('display_startup_errors', 1); + error_reporting(E_ALL & ~E_NOTICE); +} else { + disable_php_errors(); + error_reporting(E_ERROR | E_WARNING); } -// auto-set base if not already defined -if(!defined('BASE')) { - $root = substr($_SERVER['DOCUMENT_ROOT'],-1)=="/" ? substr($_SERVER['DOCUMENT_ROOT'],0,-1) : $_SERVER['DOCUMENT_ROOT']; // fix for missing / in some environments - define('BASE', substr(str_replace($root, "", dirname(__FILE__)),0,-9)); +// classes ---------------------- +require_once __DIR__ . '/classes/class.Params.php'; // Parameter handling class +require_once __DIR__ . '/classes/class.Rewrite.php'; // Class for POST/GET rewriting +require_once __DIR__ . '/classes/class.Common.php'; // Class common - common functions +require_once __DIR__ . '/classes/class.PDO.php'; // Class PDO - wrapper for database +require_once __DIR__ . '/classes/class.User.php'; // Class for active user management +require_once __DIR__ . '/classes/class.Log.php'; // Class for log saving +require_once __DIR__ . '/classes/class.Result.php'; // Class for result printing +require_once __DIR__ . '/classes/class.Install.php'; // Class for Install +require_once __DIR__ . '/classes/class.Sections.php'; // Class for sections +require_once __DIR__ . '/classes/class.Subnets.php'; // Class for subnets +require_once __DIR__ . '/classes/class.Tools.php'; // Class for tools +require_once __DIR__ . '/classes/class.Addresses.php'; // Class for addresses +require_once __DIR__ . '/classes/class.Scan.php'; // Class for Scanning and pinging +require_once __DIR__ . '/classes/class.DNS.php'; // Class for DNS management +require_once __DIR__ . '/classes/class.PowerDNS.php'; // Class for PowerDNS management +require_once __DIR__ . '/classes/class.FirewallZones.php'; // Class for firewall zone management +require_once __DIR__ . '/classes/class.Admin.php'; // Class for Administration +require_once __DIR__ . '/classes/class.Mail.php'; // Class for Mailing +require_once __DIR__ . '/classes/class.Rackspace.php'; // Class for Racks +require_once __DIR__ . '/classes/class.SNMP.php'; // Class for SNMP queries +require_once __DIR__ . '/classes/class.DHCP.php'; // Class for DHCP +require_once __DIR__ . '/classes/class.SubnetsTree.php'; // Class for generating list of subnets based on nested tree structure +require_once __DIR__ . '/classes/class.SubnetsMenu.php'; // Class for generating subnets menu. +require_once __DIR__ . '/classes/class.SubnetsTable.php'; // Class for generating JSON to populate subnet using boostrap-tables. +require_once __DIR__ . '/classes/class.SubnetsMasterDropDown.php'; // Class for generating HTML master subnet dropdown menus +require_once __DIR__ . '/classes/class.Devtype.php'; // Class for devtype +require_once __DIR__ . '/classes/class.Devices.php'; // Class for devices +require_once __DIR__ . '/classes/class.Crypto.php'; // Class for crypto +require_once __DIR__ . '/classes/class.Password_check.php'; // Class for password check +require_once __DIR__ . '/classes/class.Session_DB.php'; // Class for storing sessions to database +require_once __DIR__ . '/classes/class.LockForUpdate.php'; // Class for MySQL row locking +require_once __DIR__ . '/classes/class.OpenStreetMap.php'; // Class for OpenStreetMap + +// Load composer vendor/autoload.php and save error message if it fails +$composer_autoload_err = false; +if (file_exists(__DIR__ . '/../vendor/autoload.php')) { + $old_handler = set_error_handler(function ($errno, $errstr, $errfile, $errline) { + global $composer_autoload_err; + $composer_autoload_err = escape_input($errstr); + http_response_code(200); + return true; + }, E_ALL); + require_once __DIR__ . '/../vendor/autoload.php'; + set_error_handler($old_handler, E_ALL); } -/* @classes ---------------------- */ -require( dirname(__FILE__) . '/classes/class.Params.php' ); //Paramter handling class -require( dirname(__FILE__) . '/classes/class.Rewrite.php' ); //Class for POST/GET rewriting -require( dirname(__FILE__) . '/classes/class.Common.php' ); //Class common - common functions -require( dirname(__FILE__) . '/classes/class.PDO.php' ); //Class PDO - wrapper for database -require( dirname(__FILE__) . '/classes/class.User.php' ); //Class for active user management -require( dirname(__FILE__) . '/classes/class.Log.php' ); //Class for log saving -require( dirname(__FILE__) . '/classes/class.Result.php' ); //Class for result printing -require( dirname(__FILE__) . '/classes/class.Install.php' ); //Class for Install -require( dirname(__FILE__) . '/classes/class.Sections.php' ); //Class for sections -require( dirname(__FILE__) . '/classes/class.Subnets.php' ); //Class for subnets -require( dirname(__FILE__) . '/classes/class.Tools.php' ); //Class for tools -require( dirname(__FILE__) . '/classes/class.Addresses.php' ); //Class for addresses -require( dirname(__FILE__) . '/classes/class.Scan.php' ); //Class for Scanning and pinging -require( dirname(__FILE__) . '/classes/class.DNS.php' ); //Class for DNS management -require( dirname(__FILE__) . '/classes/class.PowerDNS.php' ); //Class for PowerDNS management -require( dirname(__FILE__) . '/classes/class.FirewallZones.php' ); //Class for firewall zone management -require( dirname(__FILE__) . '/classes/class.Admin.php' ); //Class for Administration -require( dirname(__FILE__) . '/classes/class.Mail.php' ); //Class for Mailing -require( dirname(__FILE__) . '/classes/class.Rackspace.php' ); //Class for Racks -require( dirname(__FILE__) . '/classes/class.SNMP.php' ); //Class for SNMP queries -require( dirname(__FILE__) . '/classes/class.DHCP.php' ); //Class for DHCP -require( dirname(__FILE__) . '/classes/class.SubnetsTree.php' ); //Class for generating list of subnets based on nested tree structure -require( dirname(__FILE__) . '/classes/class.SubnetsMenu.php' ); //Class for generating subnets menu. -require( dirname(__FILE__) . '/classes/class.SubnetsTable.php' ); //Class for generating JSON to populate subnet using boostrap-tables. -require( dirname(__FILE__) . '/classes/class.SubnetsMasterDropDown.php' ); //Class for generating HTML master subnet dropdown menus -require( dirname(__FILE__) . '/classes/class.Devtype.php' ); // -require( dirname(__FILE__) . '/classes/class.Devices.php' ); // -require( dirname(__FILE__) . '/classes/class.Crypto.php' ); // Crypto class -require( dirname(__FILE__) . '/classes/class.Password_check.php' ); // Class for password check -require( dirname(__FILE__) . '/classes/class.Session_DB.php' ); // Class for storing sessions to database -require( dirname(__FILE__) . '/classes/class.LockForUpdate.php' ); // Class for MySQL row locking -require( dirname(__FILE__) . '/classes/class.OpenStreetMap.php' ); // Class for OSM - - - -# create default GET parameters -$Rewrite = new Rewrite (); -$_GET = $Rewrite->get_url_params (); +// create default GET parameters +$Rewrite = new Rewrite(); +$_GET = $Rewrite->get_url_params(); -$GET = new Params ($_GET, null, true); // Run strip_tags() on $_GET -$POST = new Params ($_POST, null, true); // Run strip_tags() on $_POST +$GET = new Params($_GET, null, true); // Run strip_tags() on $_GET +$POST = new Params($_POST, null, true); // Run strip_tags() on $_POST -/* get version */ -require_once('version.php'); +// get version +require_once __DIR__ . '/version.php'; diff --git a/functions/global_functions.php b/functions/global_functions.php index ef8cf827d..49a6b9086 100644 --- a/functions/global_functions.php +++ b/functions/global_functions.php @@ -33,7 +33,7 @@ function create_link ($l0 = null, $l1 = null, $l2 = null, $l3 = null, $l4 = null for($i=0; $i<=6; $i++) { if (is_null(${"l$i"})) continue; - foreach(explode('/', ${"l$i"}) as $p) { + foreach(explode('/', (string) ${"l$i"}) as $p) { // url encode all $parts[] = urlencode($p); } @@ -54,10 +54,10 @@ function create_link ($l0 = null, $l1 = null, $l2 = null, $l3 = null, $l4 = null } # Normal links - $el = array("page", "section", "subnetId", "sPage", "ipaddrid", "tab"); + $el = ["page", "section", "subnetId", "sPage", "ipaddrid", "tab"]; // override for search if ($l0=="tools" && $l1=="search") - $el = array("page", "section", "ip", "addresses", "subnets", "vlans", "ip"); + $el = ["page", "section", "ip", "addresses", "subnets", "vlans", "ip"]; foreach($parts as $i=>$p) { $parts[$i] = "$el[$i]=$p"; @@ -78,7 +78,7 @@ function is_blank($data) { /** * Escape HTML and quotes in user provided input - * @param mixed $data + * @param string $data * @return string */ function escape_input($data) { @@ -88,6 +88,18 @@ function escape_input($data) { return is_string($safe_data) ? $safe_data : ''; } +/** + * Unescape HTML and quotes in user provided input + * @param string $data + * @return string + */ +function unescape_input($data) { + if (is_blank($data)) + return ''; + $safe_data = html_entity_decode($data, ENT_QUOTES, 'UTF-8'); + return is_string($safe_data) ? $safe_data : ''; +} + /** * Check if required php features are missing * @param mixed $required_extensions @@ -141,7 +153,7 @@ function set_ui_language($default_lang = null) { $sys_lang = is_string(getenv("LC_ALL")) ? getenv("LC_ALL") : null; // Read accepted HTTP languages - $http_accept_langs = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) : []; + $http_accept_langs = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? explode(',', (string) $_SERVER['HTTP_ACCEPT_LANGUAGE']) : []; // remove ;q= (q-factor weighting) $http_accept_langs = preg_replace("/;.*$/", "", $http_accept_langs); @@ -152,7 +164,7 @@ function set_ui_language($default_lang = null) { if (!is_string($lang) || strlen($lang)==0) continue; - if (!file_exists(dirname(__FILE__)."/locale/$lang/LC_MESSAGES/phpipam.mo")) + if (!file_exists(__DIR__ . "/locale/$lang/LC_MESSAGES/phpipam.mo")) continue; putenv("LC_ALL=".$lang); @@ -165,7 +177,7 @@ function set_ui_language($default_lang = null) { setlocale(LC_ALL, $lang); bind_textdomain_codeset('phpipam', 'UTF-8'); - bindtextdomain("phpipam", dirname(__FILE__)."/locale"); + bindtextdomain("phpipam", __DIR__ . '/locale'); textdomain("phpipam"); return true; @@ -192,7 +204,7 @@ function setcookie_samesite($name, $value, $lifetime, $httponly=false, $secure=f # Manually set cookie via header, php native support for samesite attribute is >=php7.3 $name = urlencode($name); - $value = urlencode($value); + $value = urlencode((string) $value); $tz = date_default_timezone_get(); date_default_timezone_set('UTC'); @@ -239,6 +251,3 @@ function gmp_pow2(int $exp) : GMP { gmp_setbit($result, $exp); return $result; } - -// Include backwards compatibility wrapper functions. -require_once('php_poly_fill.php'); diff --git a/functions/include-only.php b/functions/include-only.php deleted file mode 100644 index 4776aa82f..000000000 --- a/functions/include-only.php +++ /dev/null @@ -1,9 +0,0 @@ -show("danger", _("Invalid request"), true); -} \ No newline at end of file diff --git a/functions/parsedown b/functions/parsedown deleted file mode 160000 index b3e2fa192..000000000 --- a/functions/parsedown +++ /dev/null @@ -1 +0,0 @@ -Subproject commit b3e2fa192cea1d45404acc14598c41969df84a97 diff --git a/functions/php-excel-reader/excel_reader2.php b/functions/php-excel-reader/excel_reader2.php index eb50e9b48..602813566 100755 --- a/functions/php-excel-reader/excel_reader2.php +++ b/functions/php-excel-reader/excel_reader2.php @@ -75,13 +75,13 @@ function GetInt4d($data, $pos) { // http://uk.php.net/manual/en/function.getdate.php function gmgetdate($ts = null){ - $k = array('seconds','minutes','hours','mday','wday','mon','year','yday','weekday','month',0); + $k = ['seconds','minutes','hours','mday','wday','mon','year','yday','weekday','month',0]; return(array_comb($k,preg_split('/:/',gmdate('s:i:G:j:w:n:Y:z:l:F:U',is_null($ts)?time():$ts)))); } // Added for PHP4 compatibility function array_comb($array1, $array2) { - $out = array(); + $out = []; foreach ($array1 as $key => $value) { $out[$value] = $array2[$key]; } @@ -94,7 +94,7 @@ function v($data,$pos) { #[AllowDynamicProperties] class OLERead extends stdClass { - var $data = ''; + public $data = ''; function __construct(){ } function read($sFileName){ @@ -118,7 +118,7 @@ function read($sFileName){ $this->extensionBlock = GetInt4d($this->data, EXTENSION_BLOCK_POS); $this->numExtensionBlocks = GetInt4d($this->data, NUM_EXTENSION_BLOCK_POS); - $bigBlockDepotBlocks = array(); + $bigBlockDepotBlocks = []; $pos = BIG_BLOCK_DEPOT_BLOCKS_POS; $bbdBlocks = $this->numBigBlockDepotBlocks; if ($this->numExtensionBlocks != 0) { @@ -149,7 +149,7 @@ function read($sFileName){ // readBigBlockDepot $pos = 0; $index = 0; - $this->bigBlockChain = array(); + $this->bigBlockChain = []; for ($i = 0; $i < $this->numBigBlockDepotBlocks; $i++) { $pos = ($bigBlockDepotBlocks[$i] + 1) * BIG_BLOCK_SIZE; @@ -165,7 +165,7 @@ function read($sFileName){ $pos = 0; $index = 0; $sbdBlock = $this->sbdStartBlock; - $this->smallBlockChain = array(); + $this->smallBlockChain = []; while ($sbdBlock != -2) { $pos = ($sbdBlock + 1) * BIG_BLOCK_SIZE; @@ -181,26 +181,26 @@ function read($sFileName){ // readData(rootStartBlock) $block = $this->rootStartBlock; $pos = 0; - $this->entry = $this->__readData($block); - $this->__readPropertySets(); + $this->entry = $this->____readData($block); + $this->____readPropertySets(); } - function __readData($bl) { + private function ____readData($bl) { $block = $bl; $pos = 0; $data = ''; while ($block != -2) { $pos = ($block + 1) * BIG_BLOCK_SIZE; - $data = $data.substr($this->data, $pos, BIG_BLOCK_SIZE); + $data = $data.substr((string) $this->data, $pos, BIG_BLOCK_SIZE); $block = $this->bigBlockChain[$block]; } return $data; } - function __readPropertySets(){ + private function ____readPropertySets(){ $offset = 0; - while ($offset < strlen($this->entry)) { - $d = substr($this->entry, $offset, PROPERTY_STORAGE_BLOCK_SIZE); + while ($offset < strlen((string) $this->entry)) { + $d = substr((string) $this->entry, $offset, PROPERTY_STORAGE_BLOCK_SIZE); $nameSize = ord($d[SIZE_OF_NAME_POS]) | (ord($d[SIZE_OF_NAME_POS+1]) << 8); $type = ord($d[TYPE_POS]); $startBlock = GetInt4d($d, START_BLOCK_POS); @@ -210,11 +210,11 @@ function __readPropertySets(){ $name .= $d[$i]; } $name = str_replace("\x00", "", $name); - $this->props[] = array ( + $this->props[] = [ 'name' => $name, 'type' => $type, 'startBlock' => $startBlock, - 'size' => $size); + 'size' => $size]; if ((strtolower($name) == "workbook") || ( strtolower($name) == "book")) { $this->wrkbook = count($this->props) - 1; } @@ -229,13 +229,13 @@ function __readPropertySets(){ function getWorkBook(){ if ($this->props[$this->wrkbook]['size'] < SMALL_BLOCK_THRESHOLD){ - $rootdata = $this->__readData($this->props[$this->rootentry]['startBlock']); + $rootdata = $this->____readData($this->props[$this->rootentry]['startBlock']); $streamData = ''; $block = $this->props[$this->wrkbook]['startBlock']; $pos = 0; while ($block != -2) { $pos = $block * SMALL_BLOCK_SIZE; - $streamData .= substr($rootdata, $pos, SMALL_BLOCK_SIZE); + $streamData .= substr((string) $rootdata, $pos, SMALL_BLOCK_SIZE); $block = $this->smallBlockChain[$block]; } return $streamData; @@ -251,7 +251,7 @@ function getWorkBook(){ $pos = 0; while ($block != -2) { $pos = ($block + 1) * BIG_BLOCK_SIZE; - $streamData .= substr($this->data, $pos, BIG_BLOCK_SIZE); + $streamData .= substr((string) $this->data, $pos, BIG_BLOCK_SIZE); $block = $this->bigBlockChain[$block]; } return $streamData; @@ -314,10 +314,10 @@ function getWorkBook(){ class Spreadsheet_Excel_Reader extends stdClass { // MK: Added to make data retrieval easier - var $colnames = array(); - var $colindexes = array(); - var $standardColWidth = 0; - var $defaultColWidth = 0; + public $colnames = []; + public $colindexes = []; + public $standardColWidth = 0; + public $defaultColWidth = 0; function myHex($d) { if ($d < 16) return "0" . dechex($d); @@ -347,7 +347,7 @@ function getCol($col) { function val($row,$col,$sheet=0) { $col = $this->getCol($col); - if (array_key_exists($row,$this->sheets[$sheet]['cells']) && array_key_exists($col,$this->sheets[$sheet]['cells'][$row])) { + if (array_key_exists((string) $row,$this->sheets[$sheet]['cells']) && array_key_exists((string) $col,$this->sheets[$sheet]['cells'][$row])) { return $this->sheets[$sheet]['cells'][$row][$col]; } return ""; @@ -358,9 +358,9 @@ function value($row,$col,$sheet=0) { function info($row,$col,$type='',$sheet=0) { $col = $this->getCol($col); if (array_key_exists('cellsInfo',$this->sheets[$sheet]) - && array_key_exists($row,$this->sheets[$sheet]['cellsInfo']) - && array_key_exists($col,$this->sheets[$sheet]['cellsInfo'][$row]) - && array_key_exists($type,$this->sheets[$sheet]['cellsInfo'][$row][$col])) { + && array_key_exists((string) $row,$this->sheets[$sheet]['cellsInfo']) + && array_key_exists((string) $col,$this->sheets[$sheet]['cellsInfo'][$row]) + && array_key_exists((string) $type,$this->sheets[$sheet]['cellsInfo'][$row][$col])) { return $this->sheets[$sheet]['cellsInfo'][$row][$col][$type]; } return ""; @@ -598,7 +598,7 @@ function dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel if ($this->colhidden($i,$sheet)) { $style .= "display:none;"; } - $out .= "\n\t\t
" . strtoupper($this->colindexes[$i]) . "" . strtoupper((string) $this->colindexes[$i]) . "
$ip" . $hostnames[$ip] . "" . $Subnets->transform_to_dotted($subnet->subnet) . "/" . $subnet->mask . " - " . $subnet->description . "$section->name $section->description" . $Subnets->transform_to_dotted($subnet->subnet) . "/" . $subnet->mask . " - " . $subnet->description . "$section->name $section->description
$Subnets->mail_font_style_href " . $Subnets->transform_to_dotted($change['ip_addr']) . "$Subnets->mail_font_style_href " . $Subnets->transform_to_dotted($change['ip_addr']) . "$Subnets->mail_font_style $change[description]$Subnets->mail_font_style_href $change[hostname]$Subnets->mail_font_style_href " . $Subnets->transform_to_dotted($subnet->subnet) . "/" . $subnet->mask . "" . $subnet->description . "$Subnets->mail_font_style_href " . $Subnets->transform_to_dotted($subnet->subnet) . "/" . $subnet->mask . "" . $subnet->description . "$Subnets->mail_font_style $ago$Subnets->mail_font_style $oldStatus > $newStatus
$Subnets->mail_font_style ".$Subnets->transform_to_dotted($change['ip_addr'])."$Subnets->mail_font_style $change[description]$Subnets->mail_font_style_href $change[hostname]$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."".$subnet->description."$Subnets->mail_font_style_href ".$Subnets->transform_to_dotted($subnet->subnet)."/".$subnet->mask."".$subnet->description."$Subnets->mail_font_style $change[lastSeen]
"; - print ""; - - # fix for empty section - if( isset($GET->section) && (is_blank($GET->section)) ) { unset($GET->section); } - - # hide left menu - if( ($GET->page=="tools"||$GET->page=="administration") && !isset($GET->section)) { - //we don't display left menu on empty tools and administration - } - else { - # left menu - print ""; - - } - # content - print ""; - - print ""; - print "
"; - print ""; - print ""; - print ""; - print "
"; - } - ?> - - - - - - - - -
- - - - - - - - - - - -
- - - - - - - + \ No newline at end of file diff --git a/misc/CHANGELOG b/misc/CHANGELOG index 79d3e6004..0ac91a722 100755 --- a/misc/CHANGELOG +++ b/misc/CHANGELOG @@ -1,3 +1,18 @@ +== 1.9.0 + + Bugfixes: + ---------------------------- + + PHP8 compatibility fixes; + + Rack SVG image errors (#4595); + + Rack dropdown fails to populate while editing a device (#4602); + + Enhancements, changes: + ---------------------------- + + Minimum PHP version raised to 8.2.0; + + HTML files moved to 'public' folder (see UPDATING.md); + + Removed git submodules, full migrarion to composer (see UPDATING.md); + + Removed support for mcrypt; + == 1.8.0 Bugfixes: diff --git a/misc/Roadmap b/misc/Roadmap index 1611eaa0c..502236e12 100755 --- a/misc/Roadmap +++ b/misc/Roadmap @@ -1,4 +1,4 @@ -Feature candidates for 1.8: +Feature candidates for 1.9: --------------------------- Prio1 features / enhancements: @@ -10,10 +10,6 @@ Prio1 features / enhancements: - 2FA enhancements - After code saved require confirmation with TOTP - Other enhancements based on Jeff reported bugs - - Composer: - - Move requirements from gitmodules to composer - - new requirements via composer - - Add checks etc - Webhooks support - send data via json to external URL / script - API diff --git a/.htaccess b/public/.htaccess similarity index 100% rename from .htaccess rename to public/.htaccess diff --git a/api/.htaccess b/public/api/.htaccess similarity index 100% rename from api/.htaccess rename to public/api/.htaccess diff --git a/api/README b/public/api/README similarity index 100% rename from api/README rename to public/api/README diff --git a/api/controllers/Addresses.php b/public/api/controllers/Addresses.php similarity index 87% rename from api/controllers/Addresses.php rename to public/api/controllers/Addresses.php index 5c466e78c..3c775c266 100644 --- a/api/controllers/Addresses.php +++ b/public/api/controllers/Addresses.php @@ -55,21 +55,22 @@ public function __construct($Database, $Tools, $params, $Response) { * @access public * @return void */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result = array(); - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/addresses/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/addresses/{id}/","methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); + $result = []; + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/addresses/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/addresses/{id}/","methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -99,20 +100,21 @@ public function OPTIONS () { * @access public * @return void */ - public function GET () { + #[\Override] + public function GET () { // all if (!isset($this->_params->id) || $this->_params->id == "all") { // fetch all $result = $this->Addresses->fetch_all_objects ("ipaddresses"); // check result if ($result===false) { $this->Response->throw_exception(500, "Unable to read addresses"); } - else { return array("code"=>200, "data"=>$this->prepare_result($result, "addresses", true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result($result, "addresses", true, true)]; } } // subnet Id > read all addresses in subnet elseif($this->_params->id=="custom_fields") { // check result if(sizeof($this->custom_fields)==0) { $this->Response->throw_exception(404, 'No custom fields defined'); } - else { return array("code"=>200, "data"=>$this->custom_fields); } + else { return ["code"=>200, "data"=>$this->custom_fields]; } } // first free elseif($this->_params->id=="first_free") { @@ -127,7 +129,7 @@ public function GET () { $this->_params->ip_addr = $this->Addresses->get_first_available_address ($subnet->id); // null if ($this->_params->ip_addr==false) { $this->Response->throw_exception(404, 'No free addresses found'); } - else { return array("code"=>200, "data"=>$this->Addresses->transform_address ($this->_params->ip_addr, "dotted")); } + else { return ["code"=>200, "data"=>$this->Addresses->transform_address ($this->_params->ip_addr, "dotted")]; } } // address search inside predefined subnet elseif($this->Tools->validate_ip ($this->_params->id)!==false && isset($this->_params->id2)) { @@ -147,7 +149,7 @@ public function GET () { else { $result = $result_filtered; } } if ($result==false) { $this->Response->throw_exception(404, 'No addresses found'); } - else { return array("code"=>200, "data"=>$result); } + else { return ["code"=>200, "data"=>$result]; } } // tags elseif($this->_params->id=="tags") { @@ -178,7 +180,7 @@ public function GET () { // result if($result===false) { $this->Response->throw_exception(404, 'No addresses found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, "addresses", true, false)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, "addresses", true, false)]; } } // tags else { @@ -196,7 +198,7 @@ public function GET () { // result if($result===false) { $this->Response->throw_exception(404, 'Tag not found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, "addresses/tags", true, false)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, "addresses/tags", true, false)]; } } } // Search all addresses matching custom link_field field's value @@ -205,7 +207,7 @@ public function GET () { $result = $this->Tools->fetch_multiple_objects ("ipaddresses", $this->Addresses->Log->settings->link_field, $this->_params->id2); // result if($result===false) { $this->Response->throw_exception(404, 'No addresses found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, "addresses", true, false)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, "addresses", true, false)]; } } // // id not set @@ -223,7 +225,7 @@ public function GET () { $this->validate_address_id (); // set result - $result = array(); + $result = []; $result['scan_type'] = $Scan->icmp_type; $result['exit_code'] = $Scan->ping_address ($this->old_address->ip); $result['result_code'] = $Scan->ping_exit_explain ($result['exit_code']); @@ -231,11 +233,11 @@ public function GET () { // success if($result['exit_code']==0) { $Scan->ping_update_lastseen ($this->_params->id); } - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } // changelog elseif ($this->_params->id2=="changelog") { - return array("code"=>200, "data"=>$this->address_changelog ()); + return ["code"=>200, "data"=>$this->address_changelog ()]; } // default else { @@ -243,7 +245,7 @@ public function GET () { $result = $this->Addresses->fetch_address ("id", $this->_params->id); // check result if($result==false) { $this->Response->throw_exception(404, "Invalid Id"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, true, true)]; } } } // ip address ? @@ -255,14 +257,14 @@ public function GET () { $result = $this->Tools->fetch_multiple_objects ("ipaddresses", "ip_addr", $this->Subnets->transform_address ($this->_params->id2, "decimal")); // check result if($result===false) { $this->Response->throw_exception(404, 'Address not found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, true, true)]; } } // search host ? elseif (@$this->_params->id=="search_hostname") { $result = $this->Tools->fetch_multiple_objects ("ipaddresses", "hostname", $this->_params->id2); // check result if($result===false) { $this->Response->throw_exception(404, 'Hostname not found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, false, false));} + else { return ["code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, false, false)];} } // search host base (initial substring), return sorted by name elseif (@$this->_params->id=="search_hostbase") { @@ -270,14 +272,14 @@ public function GET () { $result = $this->Tools->fetch_multiple_objects ("ipaddresses", "hostname", $target, "hostname", true, true); // check result if($result===false) { $this->Response->throw_exception(404, 'Host name not found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, false, false));} + else { return ["code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, false, false)];} } elseif (@$this->_params->id=="search_mac") { $this->_params->id2 = $this->reformat_mac_address ($this->_params->id2, 1); $result = $this->Tools->fetch_multiple_objects ("ipaddresses", "mac", $this->_params->id2, "mac"); // check result if($result===false) { $this->Response->throw_exception(404, 'Host name not found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, false, false));} + else { return ["code"=>200, "data"=>$this->prepare_result ($result, $this->_params->controller, false, false)];} // false } else { $this->Response->throw_exception(400, "Invalid Id"); } } @@ -295,7 +297,8 @@ public function GET () { * @access public * @return void */ - public function POST () { + #[\Override] + public function POST () { // remap keys $this->remap_keys (); @@ -338,10 +341,10 @@ public function POST () { else { //set result if($this->_params->id=="first_free") { - return array("code"=>201, "message"=>"Address created", "id"=>$this->Addresses->lastId, "location"=>"/api/".$this->_params->app_id."/addresses/".$this->Addresses->lastId."/", "data"=>$this->Addresses->transform_address ($this->_params->ip_addr, "dotted")); + return ["code"=>201, "message"=>"Address created", "id"=>$this->Addresses->lastId, "location"=>"/api/".$this->_params->app_id."/addresses/".$this->Addresses->lastId."/", "data"=>$this->Addresses->transform_address ($this->_params->ip_addr, "dotted")]; } else { - return array("code"=>201, "message"=>"Address created", "id"=>$this->Addresses->lastId, "location"=>"/api/".$this->_params->app_id."/addresses/".$this->Addresses->lastId."/"); + return ["code"=>201, "message"=>"Address created", "id"=>$this->Addresses->lastId, "location"=>"/api/".$this->_params->app_id."/addresses/".$this->Addresses->lastId."/"]; } } } @@ -359,7 +362,8 @@ public function POST () { * @access public * @return void */ - public function PATCH () { + #[\Override] + public function PATCH () { // remap keys $this->remap_keys (); @@ -382,7 +386,7 @@ public function PATCH () { # append old address details and fill details if not provided - validate_update_parameters fetches $this->old_address foreach ($this->old_address as $ok=>$oa) { - if (!array_key_exists($ok, $values)) { + if (!array_key_exists((string) $ok, $values)) { if(!is_null($oa)) { $values[$ok] = $oa; } @@ -398,7 +402,7 @@ public function PATCH () { } else { //set result - return array("code"=>200, "message"=>"Address updated"); + return ["code"=>200, "message"=>"Address updated"]; } } @@ -420,7 +424,8 @@ public function PATCH () { * @access public * @return void */ - public function DELETE () { + #[\Override] + public function DELETE () { // delete by ip if ($this->Tools->validate_ip ($this->_params->id)!==false && isset($this->_params->id2)) { // find @@ -445,7 +450,7 @@ public function DELETE () { $this->validate_address_id (); // set variables for delete - $values = array(); + $values = []; $values["id"] = $this->_params->id; $values["action"] = "delete"; @@ -463,7 +468,7 @@ public function DELETE () { { $this->Response->throw_exception(500, "Failed to delete address"); } else { //set result - return array("code"=>200, "message"=>"Address deleted"); + return ["code"=>200, "message"=>"Address deleted"]; } } @@ -634,7 +639,7 @@ private function address_changelog () { if (sizeof($clogs)>0) { foreach ($clogs as $l) { // diff to array - $l->cdiff = explode("\r\n", str_replace(["[","]"], "", trim($l->cdiff))); + $l->cdiff = explode("\r\n", str_replace(["[","]"], "", trim((string) $l->cdiff))); // save $clogs_formatted[] = [ "user" => $l->real_name, diff --git a/api/controllers/Circuits.php b/public/api/controllers/Circuits.php similarity index 83% rename from api/controllers/Circuits.php rename to public/api/controllers/Circuits.php index 62a153816..a0f37cda1 100644 --- a/api/controllers/Circuits.php +++ b/public/api/controllers/Circuits.php @@ -89,25 +89,26 @@ private function rewrite_controller_params ($params) { * @access public * @return void */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/circuits/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/circuits/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - array("href"=>"/api/".$this->_params->app_id."/circuits/providers/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/circuits/providers/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/circuits/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/circuits/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ["href"=>"/api/".$this->_params->app_id."/circuits/providers/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/circuits/providers/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -133,13 +134,14 @@ public function OPTIONS () { * @access public * @return void|array */ - public function GET () { + #[\Override] + public function GET () { // all if (!isset($this->_params->id) || $this->_params->id == "all") { $result = $this->Tools->fetch_all_objects ($this->type, 'id'); // check result if($result===false) { $this->Response->throw_exception(404, "No {$this->type_text}s configured"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // provider circuits elseif($this->type==="circuitProviders" && isset($this->_params->id2)) { @@ -147,7 +149,7 @@ public function GET () { $result = $this->Tools->fetch_multiple_objects ("circuits", "provider", $this->_params->id); // check result if($result==NULL) { $this->Response->throw_exception(404, "No circuits belonging to provider"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } else { $this->Response->throw_exception(400, "Invalid API query"); @@ -158,7 +160,7 @@ public function GET () { $result = $this->Tools->fetch_object ($this->type, "cid", $this->_params->id2); // check result if($result==NULL) { $this->Response->throw_exception(404, "{$this->type_text} not found"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // read details else { @@ -168,7 +170,7 @@ public function GET () { $result = $this->Tools->fetch_object ($this->type, "id", $this->_params->id); // check result if($result==NULL) { $this->Response->throw_exception(404, "{$this->type_text} not found"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } } @@ -185,7 +187,8 @@ public function GET () { * @access public * @return void */ - public function POST () { + #[\Override] + public function POST () { # remap keys $this->remap_keys (); # validate id @@ -203,10 +206,10 @@ public function POST () { else { //set result if($this->type=="circuits") { - return array("code"=>201, "message"=>"{$this->type_text} created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/circuits/".$this->Admin->lastId."/"); + return ["code"=>201, "message"=>"{$this->type_text} created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/circuits/".$this->Admin->lastId."/"]; } else { - return array("code"=>201, "message"=>"{$this->type_text} created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/circuits/providers/".$this->Admin->lastId."/"); + return ["code"=>201, "message"=>"{$this->type_text} created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/circuits/providers/".$this->Admin->lastId."/"]; } } } @@ -225,7 +228,8 @@ public function POST () { * * @return void|array */ - public function PATCH () { + #[\Override] + public function PATCH () { # remap keys $this->remap_keys (); # validate id @@ -244,7 +248,7 @@ public function PATCH () { { $this->Response->throw_exception(500, "{$this->type_text} edit failed"); } else { //set result - return array("code"=>200, "message"=>"{$this->type_text} updated"); + return ["code"=>200, "message"=>"{$this->type_text} updated"]; } } @@ -261,12 +265,13 @@ public function PATCH () { * * @return void|array */ - public function DELETE () { + #[\Override] + public function DELETE () { # verify $this->validate_id ("delete"); # set variables for delete - $values = array(); + $values = []; $values["id"] = $this->_params->id; # validate that something is present $this->validate_values ($values); @@ -280,7 +285,7 @@ public function DELETE () { $this->Admin->remove_object_references ("circuits", "id", $this->_params->id); } // set result - return array("code"=>200, "message"=>"{$this->type_text} deleted"); + return ["code"=>200, "message"=>"{$this->type_text} deleted"]; } } @@ -428,7 +433,7 @@ private function validate_cid ($action, $old_object) { private function validate_circuit_type ($action="add") { if(isset($this->_params->type)) { $type_desc = $this->Database->getFieldInfo ("circuits", "type"); - $all_types = pf_explode(",", str_replace(array("enum","(",")","'"), "",$type_desc->Type)); + $all_types = explode(",", str_replace(["enum","(",")","'"], "",(string) $type_desc->Type)); if(!in_array($this->_params->type, $all_types)) { $this->Response->throw_exception(400, "Invalid circuit type"); } } else { @@ -449,7 +454,7 @@ private function validate_circuit_type ($action="add") { */ private function validate_circuit_status ($action="add") { if (isset($this->_params->status)) { - $statuses = array ("Active", "Inactive", "Reserved"); + $statuses = ["Active", "Inactive", "Reserved"]; if(!in_array($this->_params->status, $statuses)) { $this->Response->throw_exception(400, _("Invalid status")); } } else { diff --git a/api/controllers/Common.php b/public/api/controllers/Common.php similarity index 87% rename from api/controllers/Common.php rename to public/api/controllers/Common.php index 7f9468464..d868bfd39 100644 --- a/api/controllers/Common.php +++ b/public/api/controllers/Common.php @@ -13,9 +13,10 @@ class API_params extends Params { * @param bool $html_escape * @return void */ - public function read($args, $strip_tags = false, $html_escape = false) { + #[\Override] + public function read($args, $strip_tags = false, $html_escape = false) { if (is_array($args) && isset($args['controller'])) { - $args['controller'] = strtolower($args['controller']); + $args['controller'] = strtolower((string) $args['controller']); } parent::read($args, $strip_tags, $html_escape); @@ -167,7 +168,7 @@ class Common_api_functions { */ private function NOT_IMPLEMENTED() { - return array("code"=>501, "message"=>"Method not implemented"); + return ["code"=>501, "message"=>"Method not implemented"]; } public function OPTIONS () { @@ -234,7 +235,7 @@ protected function init_object ($Object_name, $Database) { */ protected function set_valid_keys ($controller) { # array of controller keys - $this->controller_keys = array("app_id", "controller"); + $this->controller_keys = ["app_id", "controller"]; # array of all valid keys - fetch from SCHEMA $this->valid_keys = $this->Tools->fetch_standard_fields ($controller); @@ -257,7 +258,7 @@ protected function set_valid_keys ($controller) { } # set items to remove - $this->remove_keys = array("editDate"); + $this->remove_keys = ["editDate"]; # remove update time foreach($this->valid_keys as $k=>$v) { if(in_array($v, $this->remove_keys)) { @@ -324,7 +325,7 @@ protected function prepare_result ($result, $controller = null, $links = true, $ * @param array $result * @return object[] */ - protected function filter_result ($result = array ()) { + protected function filter_result ($result = []) { // remap keys before applying filter $result = $this->remap_keys ($result, false); // validate @@ -345,11 +346,11 @@ protected function filter_result ($result = array ()) { if ($this->_params->filter_match == 'partial') { // match partial string - if (strpos($r->{$this->_params->filter_by}, $this->_params->filter_value) === false) + if (strpos((string) $r->{$this->_params->filter_by}, (string) $this->_params->filter_value) === false) continue; } elseif ($this->_params->filter_match == 'regex') { // match regular expression - if (preg_match($this->_params->filter_value, $r->{$this->_params->filter_by}) !== 1) + if (preg_match($this->_params->filter_value, (string) $r->{$this->_params->filter_by}) !== 1) continue; } else { // match full string @@ -415,7 +416,7 @@ protected function validate_filter_by ($result) { */ protected function add_links ($result, $controller=null) { // lower controller - $controller = strtolower($controller); + $controller = strtolower((string) $controller); // multiple options if(is_array($result)) { @@ -494,111 +495,111 @@ protected function add_links ($result, $controller=null) { */ private function define_links ($controller) { // init - $result = array(); + $result = []; // sections if($controller=="sections") { - $result["self"] = array ("GET","POST","DELETE","PATCH"); - $result["subnets"] = array ("GET"); + $result["self"] = ["GET","POST","DELETE","PATCH"]; + $result["subnets"] = ["GET"]; // return return $result; } // subnets elseif($controller=="subnets") { - $result["self"] = array ("GET","POST","DELETE","PATCH"); - $result["addresses"] = array ("GET"); - $result["addresses/{ip}"] = array ("GET"); - $result["usage"] = array ("GET"); - $result["first_free"] = array ("GET"); - $result["slaves"] = array ("GET"); - $result["slaves_recursive"] = array ("GET"); - $result["truncate"] = array ("DELETE"); - $result["permissions"] = array ("DELETE", "PATCH"); - $result["resize"] = array ("PATCH"); - $result["split"] = array ("PATCH"); + $result["self"] = ["GET","POST","DELETE","PATCH"]; + $result["addresses"] = ["GET"]; + $result["addresses/{ip}"] = ["GET"]; + $result["usage"] = ["GET"]; + $result["first_free"] = ["GET"]; + $result["slaves"] = ["GET"]; + $result["slaves_recursive"] = ["GET"]; + $result["truncate"] = ["DELETE"]; + $result["permissions"] = ["DELETE", "PATCH"]; + $result["resize"] = ["PATCH"]; + $result["split"] = ["PATCH"]; // return return $result; } // addresses elseif($controller=="addresses") { - $result["self"] = array ("GET","POST","DELETE","PATCH"); - $result["ping"] = array ("GET"); + $result["self"] = ["GET","POST","DELETE","PATCH"]; + $result["ping"] = ["GET"]; // return return $result; } // tags elseif($controller=="addresses/tags") { - $result["self"] = array ("GET"); - $result["addresses"] = array ("GET"); + $result["self"] = ["GET"]; + $result["addresses"] = ["GET"]; // return return $result; } // tools - devices elseif($controller=="tools/devices") { - $result["self"] = array ("GET","POST","DELETE","PATCH"); - $result["addresses"] = array ("GET"); + $result["self"] = ["GET","POST","DELETE","PATCH"]; + $result["addresses"] = ["GET"]; // return return $result; } // tools - devices elseif($controller=="tools/devicetypes") { - $result["self"] = array ("GET","POST","DELETE","PATCH"); - $result["devices"] = array ("GET"); + $result["self"] = ["GET","POST","DELETE","PATCH"]; + $result["devices"] = ["GET"]; // return return $result; } // tools - tags elseif($controller=="tools/iptags") { - $result["self"] = array ("GET","POST","DELETE","PATCH"); - $result["addresses"] = array ("GET"); + $result["self"] = ["GET","POST","DELETE","PATCH"]; + $result["addresses"] = ["GET"]; // return return $result; } // tools - tags elseif($controller=="tools/vlans") { - $result["self"] = array ("GET"); - $result["subnets"] = array ("GET"); + $result["self"] = ["GET"]; + $result["subnets"] = ["GET"]; // return return $result; } // tools - tags elseif($controller=="tools/vrf") { - $result["self"] = array ("GET"); - $result["subnets"] = array ("GET"); + $result["self"] = ["GET"]; + $result["subnets"] = ["GET"]; // return return $result; } // tags elseif($controller=="iptags") { - $result["self"] = array ("GET"); - $result["addresses"] = array ("GET"); + $result["self"] = ["GET"]; + $result["addresses"] = ["GET"]; // return return $result; } // tags elseif($controller=="devices") { - $result["self"] = array ("GET"); - $result["addresses"] = array ("GET"); + $result["self"] = ["GET"]; + $result["addresses"] = ["GET"]; // return return $result; } // vlan domains elseif($controller=="l2domains") { - $result["self"] = array ("GET","POST","DELETE","PATCH"); - $result["vlans"] = array ("GET"); + $result["self"] = ["GET","POST","DELETE","PATCH"]; + $result["vlans"] = ["GET"]; // return return $result; } // vlans elseif($controller=="vlans") { - $result["self"] = array ("GET","POST","DELETE","PATCH"); - $result["subnets"] = array ("GET"); + $result["self"] = ["GET","POST","DELETE","PATCH"]; + $result["subnets"] = ["GET"]; // return return $result; } // vrfs elseif($controller=="vrfs") { - $result["self"] = array ("GET","POST","DELETE","PATCH"); - $result["subnets"] = array ("GET"); + $result["self"] = ["GET","POST","DELETE","PATCH"]; + $result["subnets"] = ["GET"]; // return return $result; } @@ -647,7 +648,7 @@ protected function transform_address ($result) { */ protected function validate_keys () { // init values - $values = array(); + $values = []; // loop foreach($this->_params as $pk=>$pv) { if(!in_array($pk, $this->valid_keys)) { $this->Response->throw_exception(400, 'Invalid request key '.$pk); } @@ -672,7 +673,7 @@ protected function validate_keys () { */ protected function validate_options_request () { foreach($this->_params as $key=>$val) { - if(!in_array($key, array("app_id", "controller", "id"))) { + if(!in_array($key, ["app_id", "controller", "id"])) { { $this->Response->throw_exception(400, 'Invalid request key parameter '.$key); } } } @@ -708,7 +709,7 @@ public function validate_mac ($mac) { */ public function reformat_mac_address ($mac, $format = 1) { // strip al tags first - $mac = strtolower(str_replace(array(":",".","-"), "", $mac)); + $mac = strtolower(str_replace([":",".","-"], "", $mac)); // format 4 if ($format==4) { return $mac; @@ -739,12 +740,12 @@ public function reformat_mac_address ($mac, $format = 1) { * @return array */ public function get_possible_permissions() { - return array( + return [ "na" => 0, "ro" => 1, "rw" => 2, "rwa" => 3 - ); + ]; } /** @@ -820,7 +821,7 @@ protected function remove_subnets($result) { */ protected function remap_keys ($result = null, $controller = null, $tools_table = null) { // define keys array - $this->keys = array("switch"=>"deviceId", "state"=>"tag", "ip_addr"=>"ip"); + $this->keys = ["switch"=>"deviceId", "state"=>"tag", "ip_addr"=>"ip"]; // exceptions if($controller=="vlans") { $this->keys['vlanId'] = "id"; } @@ -876,7 +877,7 @@ private function remap_result_keys ($result) { // search and replace if(is_array($result) || is_object($result)) { foreach($result as $k=>$v) { - if(array_key_exists($k, $this->keys)) { + if(array_key_exists((string) $k, $this->keys)) { // replace $key = $this->keys[$k]; $result_remapped->{$key} = $v; @@ -890,7 +891,7 @@ private function remap_result_keys ($result) { # array else { // create a new array for the remapped data - $result_remapped = array(); + $result_remapped = []; // loop foreach ($result as $m=>$r) { @@ -899,7 +900,7 @@ private function remap_result_keys ($result) { // search and replace foreach($r as $k=>$v) { - if(array_key_exists($k, $this->keys)) { + if(array_key_exists((string) $k, $this->keys)) { // replace $key_val = $this->keys[$k]; $result_remapped[$m]->{$key_val} = $v; diff --git a/api/controllers/Devices.php b/public/api/controllers/Devices.php similarity index 84% rename from api/controllers/Devices.php rename to public/api/controllers/Devices.php index 5e5c99954..3d741ffb1 100644 --- a/api/controllers/Devices.php +++ b/public/api/controllers/Devices.php @@ -12,7 +12,7 @@ class Devices_controller extends Common_api_functions { * * @var mixed */ - protected $default_search_fields = array('hostname','ip_addr','description'); + protected $default_search_fields = ['hostname','ip_addr','description']; /** @@ -48,6 +48,7 @@ public function __construct($Database, $Tools, $params, $Response) { * @access public * @return void */ + #[\Override] public function OPTIONS () { // validate $this->validate_options_request(); @@ -56,17 +57,17 @@ public function OPTIONS () { $app = $this->Tools->fetch_object('api', 'app_id', $this->_params->app_id); // methods - $result = array(); - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/devices/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/devices/search/{search_term}", "methods"=>array(array("rel"=>"search", "method"=>"GET"))), - array("href"=>"/api/".$this->_params->app_id."/devices/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); + $result = []; + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/devices/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/devices/search/{search_term}", "methods"=>[["rel"=>"search", "method"=>"GET"]]], + ["href"=>"/api/".$this->_params->app_id."/devices/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; # Response - return array('code'=>200, 'data'=>$result); + return ['code'=>200, 'data'=>$result]; } @@ -88,6 +89,7 @@ public function OPTIONS () { * @access public * @return void */ + #[\Override] public function GET () { // all objects if (!isset($this->_params->id) || $this->_params->id == "all") { @@ -95,7 +97,7 @@ public function GET () { $result = $this->Tools->fetch_all_objects('devices', 'id'); // result if(!$result) { return $this->Response->throw_exception(404, "No devices configured"); } - else { return array('code'=>200, 'data'=>$this->prepare_result($result, 'devices', true, false)); } + else { return ['code'=>200, 'data'=>$this->prepare_result($result, 'devices', true, false)]; } } // parameters are set else { @@ -130,7 +132,7 @@ function ($k) { // result if(!$result) { return $this->Response->throw_exception(404, "No devices found"); } - else { return array('code'=>200, 'data'=>$this->prepare_result($result, 'devices', true, false)); } + else { return ['code'=>200, 'data'=>$this->prepare_result($result, 'devices', true, false)]; } } else { $this->Response->throw_exception(400, 'No search term given'); @@ -165,7 +167,7 @@ function ($k) { // all ok, prepare result if($result === false) { return $this->Response->throw_exception(404, "No ".$this->_params->id2." found"); } - else { return array('code'=>200, 'data'=>$this->prepare_result($result, 'devices', true, false)); } + else { return ['code'=>200, 'data'=>$this->prepare_result($result, 'devices', true, false)]; } } } } @@ -180,6 +182,7 @@ function ($k) { * * @method POST */ + #[\Override] public function POST () { # Put incoming keys in order $this->remap_keys (); @@ -205,7 +208,7 @@ public function POST () { } else { //set result - return array("code"=>201, "message"=>"Device created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/devices/".$this->Admin->lastId."/"); + return ["code"=>201, "message"=>"Device created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/devices/".$this->Admin->lastId."/"]; } } @@ -219,6 +222,7 @@ public function POST () { * * @method PATCH */ + #[\Override] public function PATCH (){ # Put incoming keys back in order $this->remap_keys(); @@ -238,7 +242,7 @@ public function PATCH (){ $this->Response->throw_exception(500, 'Device edit failed'); } else { // fetch the updated object and hand it back to the client - return array("code"=>200, "message"=>"Device updated", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/devices/".$values['id']."/"); + return ["code"=>200, "message"=>"Device updated", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/devices/".$values['id']."/"]; } } @@ -252,12 +256,13 @@ public function PATCH (){ * * @method DELETE */ + #[\Override] public function DELETE () { # validations $this->validate_device_edit(); # set variables for delete - $values = array(); + $values = []; $values['id'] = $this->_params->id; # execute delete @@ -269,7 +274,7 @@ public function DELETE () { $this->Admin->remove_object_references('ipaddresses', 'switch', $this->_params->id); // set result - return array("code"=>200, "message"=>"Device deleted"); + return ["code"=>200, "message"=>"Device deleted"]; } } @@ -307,7 +312,7 @@ private function get_all_sections_delimited () { $sections = $this->Admin->fetch_all_objects ("sections"); // reformat if($sections!==false) { - $sections_all = array (); + $sections_all = []; foreach ($sections as $s) { $sections_all[$s->id] = $s->id; } diff --git a/api/controllers/Folders.php b/public/api/controllers/Folders.php similarity index 100% rename from api/controllers/Folders.php rename to public/api/controllers/Folders.php diff --git a/api/controllers/L2domains.php b/public/api/controllers/L2domains.php similarity index 79% rename from api/controllers/L2domains.php rename to public/api/controllers/L2domains.php index 5252931a7..0a8036404 100644 --- a/api/controllers/L2domains.php +++ b/public/api/controllers/L2domains.php @@ -40,21 +40,22 @@ public function __construct($Database, $Tools, $params, $Response) { * @access public * @return void */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result = array(); - $result['methods'] = array( - array("href"=>"/api/l2domains/".$this->_params->app_id."/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/l2domains/".$this->_params->app_id."/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); + $result = []; + $result['methods'] = [ + ["href"=>"/api/l2domains/".$this->_params->app_id."/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/l2domains/".$this->_params->app_id."/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -74,20 +75,21 @@ public function OPTIONS () { * @access public * @return void */ - public function GET () { + #[\Override] + public function GET () { // all domains if(!isset($this->_params->id) || $this->_params->id == "all") { $result = $this->Tools->fetch_all_objects ("vlanDomains", 'id', true); // check result if($result===false) { $this->Response->throw_exception(404, 'No domains configured'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // set else { // custom fields if($this->_params->id=="custom_fields") { if(sizeof($this->custom_fields)==0) { $this->Response->throw_exception(404, 'No custom fields defined'); } - else { return array("code"=>200, "data"=>$this->custom_fields); } + else { return ["code"=>200, "data"=>$this->custom_fields]; } } // vlans elseif (@$this->_params->id2=="vlans") { @@ -97,7 +99,7 @@ public function GET () { $result = $this->Tools->fetch_multiple_objects ("vlans", "domainId", $this->_params->id, 'vlanId', true); // check result if($result==NULL) { $this->Response->throw_exception(404, "No vlans belonging to this domain"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // id else { @@ -107,7 +109,7 @@ public function GET () { $result = $this->Tools->fetch_object ("vlanDomains", "id", $this->_params->id); // check result if($result==NULL) { $this->Response->throw_exception(404, "Invalid domain id"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } } @@ -124,7 +126,8 @@ public function GET () { * @access public * @return void */ - public function POST () { + #[\Override] + public function POST () { # remap keys $this->remap_keys (); @@ -139,7 +142,7 @@ public function POST () { { $this->Response->throw_exception(500, "Domain creation failed"); } else { //set result - return array("code"=>201, "message"=>"L2 domain created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/l2domains/".$this->Admin->lastId."/"); + return ["code"=>201, "message"=>"L2 domain created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/l2domains/".$this->Admin->lastId."/"]; } } @@ -153,7 +156,8 @@ public function POST () { * @access public * @return void */ - public function PATCH () { + #[\Override] + public function PATCH () { # remap keys $this->remap_keys (); @@ -170,7 +174,7 @@ public function PATCH () { { $this->Response->throw_exception(500, "Domain edit failed"); } else { //set result - return array("code"=>200, "message"=>"L2 domain updated"); + return ["code"=>200, "message"=>"L2 domain updated"]; } } @@ -186,12 +190,13 @@ public function PATCH () { * @access public * @return void */ - public function DELETE () { + #[\Override] + public function DELETE () { # check that domain exists $this->validate_domain_edit (); # set variables for update - $values = array(); + $values = []; $values["id"] = $this->_params->id; # execute delete @@ -202,7 +207,7 @@ public function DELETE () { $this->Admin->update_object_references ("vlans", "domainId", $this->_params->id, 1); // set result - return array("code"=>200, "message"=>"L2 domain deleted and vlans migrated to default domain"); + return ["code"=>200, "message"=>"L2 domain deleted and vlans migrated to default domain"]; } } diff --git a/api/controllers/Nat.php b/public/api/controllers/Nat.php similarity index 83% rename from api/controllers/Nat.php rename to public/api/controllers/Nat.php index 389c56234..102515ca5 100644 --- a/api/controllers/Nat.php +++ b/public/api/controllers/Nat.php @@ -96,13 +96,13 @@ public function __construct($Database, $Tools, $params, $Response) { $this->init_object ("Addresses", $Database); $this->init_object ("Devices", $Database); $this->set_valid_keys ("nat"); - $this->valid_types = array("source", "destination", "static"); - $this->validation_data = array( - "ipaddresses" => array( + $this->valid_types = ["source", "destination", "static"]; + $this->validation_data = [ + "ipaddresses" => [ "object" => $this->Addresses, "function" => 'fetch_address', - ) - ); + ] + ]; } /** @@ -111,20 +111,21 @@ public function __construct($Database, $Tools, $params, $Response) { * @access public * @return void */ + #[\Override] public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result = array(); - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/nat/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/nat/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); - return array("code"=>200, "data"=>$result); + $result = []; + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/nat/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/nat/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; + return ["code"=>200, "data"=>$result]; } /** @@ -139,15 +140,16 @@ public function OPTIONS () { * @access public * @return void */ + #[\Override] public function GET () { # Get all NATs from DB if (!isset($this->_params->id) || $this->_params->id == "all") { $result = $this->Tools->fetch_all_objects ("nat", 'id'); - return array("code"=>200, "data"=>$this->convert_from_DB($result), true, true);#$this->prepare_result ($result, null, true, true)); + return ["code"=>200, "data"=>$this->convert_from_DB($result), true, true];#$this->prepare_result ($result, null, true, true)); } elseif (isset($this->_params->id) && is_numeric($this->_params->id)) { $result = $this->Tools->fetch_multiple_objects ("nat", "id", $this->_params->id, 'id', true); - return array("code"=>200, "data"=>$this->convert_from_DB($result), true, true); + return ["code"=>200, "data"=>$this->convert_from_DB($result), true, true]; } else { $this->Response->throw_exception(400, "Invalid ID format"); @@ -162,12 +164,12 @@ public function GET () { * @return list of formatted results **/ private function convert_from_DB($results) { - $out = array(); + $out = []; foreach ($results as $r) { - $rr = array( - "src" => array(), - "dst" => array() - ); + $rr = [ + "src" => [], + "dst" => [] + ]; foreach ($r as $k => $v) { if ($k != "src" && $k != "dst") { $rr[$k] = $v; @@ -176,7 +178,7 @@ private function convert_from_DB($results) { # Better source and destination presentation (json decode values from DB) $jd = (array) db_json_decode($v, true); if ($jd && $jd["ipaddresses"]) { - $rr[$k] = array('ipaddresses' => $jd["ipaddresses"]); + $rr[$k] = ['ipaddresses' => $jd["ipaddresses"]]; } } } @@ -191,6 +193,7 @@ private function convert_from_DB($results) { * @access public * @return void */ + #[\Override] public function HEAD () { return $this->GET (); } @@ -201,18 +204,19 @@ public function HEAD () { * @access public * @return void */ + #[\Override] public function POST () { # check for valid keys $values = $this->validate_keys (); # validate input format $this->validate_nat_edit(); - foreach (array("src","dst") as $k) + foreach (["src","dst"] as $k) $values[$k] = json_encode($values[$k]); #$this->Response->throw_exception(500, "AAA".json_encode($values['src'])); if (!$this->Admin->object_modify ("nat", "add", "id", $values)) { $this->Response->throw_exception(500, "NAT creation failed"); } - return array("code"=>201, "message"=>"NAT created", "id"=>$this->Admin->lastId, "location"=>"/api".$this->_params->app_id."/nat/".$this->Admin->lastId."/"); + return ["code"=>201, "message"=>"NAT created", "id"=>$this->Admin->lastId, "location"=>"/api".$this->_params->app_id."/nat/".$this->Admin->lastId."/"]; } @@ -222,12 +226,13 @@ public function POST () { * @access public * @return void */ + #[\Override] public function PATCH () { # check for valid keys $values = $this->validate_keys (); # validate input format $this->validate_nat_edit(); - foreach (array("src","dst") as $k) { + foreach (["src","dst"] as $k) { if ( array_key_exists($k, $values) ) { $values[$k] = json_encode($values[$k]); } @@ -236,7 +241,7 @@ public function PATCH () { if (!$this->Admin->object_modify ("nat", "edit", "id", $values)) { $this->Response->throw_exception(500, "NAT modification failed"); } - return array("code"=>200, "message"=>"NAT modified", "id"=>$this->_params->id, "location"=>"/api".$this->_params->app_id."/nat/".$this->Admin->lastId."/"); + return ["code"=>200, "message"=>"NAT modified", "id"=>$this->_params->id, "location"=>"/api".$this->_params->app_id."/nat/".$this->Admin->lastId."/"]; } /** @@ -257,12 +262,12 @@ private function validate_nat_edit() { if ($_SERVER['REQUEST_METHOD']=="POST" || $_SERVER['REQUEST_METHOD']=="PATCH") { # Check optional fields format # TBD: subnets for src & dst ? - foreach (array("src_port", "dst_port") as $k) { + foreach (["src_port", "dst_port"] as $k) { if ( $this->_params->$k && !is_numeric($this->_params->$k) ) { $this->Response->throw_exception(400, "Invalid value for $k (must be numeric)"); } } - foreach (array("src","dst") as $k) { + foreach (["src","dst"] as $k) { $this->verify_src_dst($k); } $this->verify_device(); @@ -313,7 +318,7 @@ private function verify_src_dst($k) { if (!is_array($input_param)) { $this->Response->throw_exception(400, "Invalid $k format (Must be an array"); } - $input_out = array(); + $input_out = []; foreach ($input_param as $pk => $pv) { if (!in_array($pk, array_keys($this->validation_data))) { $this->Response->throw_exception(400, "Invalid key identifier for $k ($pk)"); @@ -321,7 +326,7 @@ private function verify_src_dst($k) { if (!is_array($pv)) { $this->Response->throw_exception(400, "Invalid value for $k (must be an array)"); } - $values = array(); + $values = []; foreach ($pv as $v) { if (!is_numeric($v)) { $this->Response->throw_exception(400, "Invalid value $v (must be an integer)"); @@ -338,7 +343,7 @@ private function verify_src_dst($k) { } } } - array_push($input_out, array($pk => $values)); + array_push($input_out, [$pk => $values]); } } } @@ -349,6 +354,7 @@ private function verify_src_dst($k) { * @access public * @return void */ + #[\Override] public function DELETE () { $values = $this->validate_keys(); $this->validate_nat_edit(); @@ -359,7 +365,7 @@ public function DELETE () { $this->Response->throw_exception(500, "NAT delete failed"); } else { - return array("code"=>200, "message"=>"NAT deleted"); + return ["code"=>200, "message"=>"NAT deleted"]; } } else { diff --git a/api/controllers/Prefix.php b/public/api/controllers/Prefix.php similarity index 92% rename from api/controllers/Prefix.php rename to public/api/controllers/Prefix.php index c384e629f..d97eff64f 100644 --- a/api/controllers/Prefix.php +++ b/public/api/controllers/Prefix.php @@ -124,7 +124,7 @@ class Prefix_controller extends Common_api_functions { * @var array * @access private */ - private $valid_address_types = array("IPv4", "IPv6", "v4", "v6", "4", "6"); + private $valid_address_types = ["IPv4", "IPv6", "v4", "v6", "4", "6"]; /** * List of ignored subnet fields @@ -136,7 +136,7 @@ class Prefix_controller extends Common_api_functions { * @var array * @access private */ - private $ignored_prefix_fields = array( + private $ignored_prefix_fields = [ "linked_subnet", "firewallAddressObject", "pingSubnet", @@ -157,7 +157,7 @@ class Prefix_controller extends Common_api_functions { "location", "isFolder", "editDate" - ); + ]; /** * List of ignored addresses fields @@ -169,7 +169,7 @@ class Prefix_controller extends Common_api_functions { * @var array * @access private */ - private $ignored_addresses_fields = array( + private $ignored_addresses_fields = [ "state", "deviceId", "switch", @@ -181,7 +181,7 @@ class Prefix_controller extends Common_api_functions { "PTR", "firewallAddressObject", "editDate" - ); + ]; /** * Query type, overrides if addresses are requested @@ -275,7 +275,7 @@ public function __construct($Database, $Tools, $params, $Response) { */ private function init_subnets_controller () { // file - require( dirname(__FILE__) . "/Subnets.php"); + require( __DIR__ . "/Subnets.php"); // validate parameters on Subnets_controller $this->Subnets_controller = new Subnets_controller ($this->Database, $this->Tools, $this->_params, $this->Response); } @@ -287,7 +287,7 @@ private function init_subnets_controller () { */ private function init_addresses_controller () { // file - require( dirname(__FILE__) . "/Addresses.php"); + require( __DIR__ . "/Addresses.php"); // validate parameters on Subnets_controller $this->Addresses_controller = new Addresses_controller ($this->Database, $this->Tools, $this->_params, $this->Response); } @@ -347,19 +347,20 @@ private function override_custom_fields () { * @access public * @return array */ + #[\Override] public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result = array(); - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/sections/", "methods"=>array(array("rel"=>"options","method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/sections/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"))) - ); + $result = []; + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/sections/", "methods"=>[["rel"=>"options","method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/sections/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"]]] + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -377,6 +378,7 @@ public function OPTIONS () { * @access public * @return array */ + #[\Override] public function GET () { // external identifier if($this->_params->id == "external_id") { @@ -401,9 +403,9 @@ public function GET () { } // result if($subnets===false && $addresses===false) { $this->Response->throw_exception(404, "No objects found"); } - elseif($addresses===false) { return array("code"=>200, "data"=>array("subnets"=>$subnets)); } - elseif($subnets===false) { return array("code"=>200, "data"=>array("addresses"=>$addresses)); } - else { return array("code"=>200, "data"=>array("subnets"=>$subnets, "addresses"=>$addresses)); } + elseif($addresses===false) { return ["code"=>200, "data"=>["subnets"=>$subnets]]; } + elseif($subnets===false) { return ["code"=>200, "data"=>["addresses"=>$addresses]]; } + else { return ["code"=>200, "data"=>["subnets"=>$subnets, "addresses"=>$addresses]]; } } // get all subnets involved in querying elseif(!isset($this->_params->id3)) { @@ -429,7 +431,7 @@ public function GET () { $subnets[$k]->usage = $this->calculate_subnet_usage ($s->id); } } - return array("code"=>200, "data"=>$this->prepare_result ($subnets, "subnets", $this->use_links, true)); + return ["code"=>200, "data"=>$this->prepare_result ($subnets, "subnets", $this->use_links, true)]; } } // get prefix @@ -450,7 +452,7 @@ public function GET () { // response if($available===false) { $this->Response->throw_exception(404, "No $this->query_type found"); } - else { return array("code"=>200, "data"=>$available); } + else { return ["code"=>200, "data"=>$available]; } } } @@ -467,6 +469,7 @@ public function GET () { * @access public * @return array */ + #[\Override] public function POST () { // validate parameters $this->validate_all_request_parameters (); @@ -521,7 +524,7 @@ private function POST_SUBNET ($subnets) { } else { //set result - return array("code"=>201, "message"=>"Subnet created", "id"=>$this->Subnets->lastInsertId, "data"=>$this->Tools->transform_address ($values['subnet'], "dotted")."/".$values['mask'], "location"=>"/api/".$this->_params->app_id."/subnets/".$this->Subnets->lastInsertId."/"); + return ["code"=>201, "message"=>"Subnet created", "id"=>$this->Subnets->lastInsertId, "data"=>$this->Tools->transform_address ($values['subnet'], "dotted")."/".$values['mask'], "location"=>"/api/".$this->_params->app_id."/subnets/".$this->Subnets->lastInsertId."/"]; } } @@ -568,7 +571,7 @@ private function POST_ADDRESS ($subnets) { } else { //set result - return array("code"=>201, "message"=>"Address created", "id"=>$this->Addresses->lastId, "subnetId"=>$this->master_subnet->id, "data"=>$this->Addresses->transform_address ($this->_params->ip_addr, "dotted"), "location"=>"/api/".$this->_params->app_id."/addresses/".$this->Addresses->lastId."/"); + return ["code"=>201, "message"=>"Address created", "id"=>$this->Addresses->lastId, "subnetId"=>$this->master_subnet->id, "data"=>$this->Addresses->transform_address ($this->_params->ip_addr, "dotted"), "location"=>"/api/".$this->_params->app_id."/addresses/".$this->Addresses->lastId."/"]; } } @@ -629,9 +632,9 @@ private function validate_request_parameters_custom_field () { */ private function set_address_type () { // ipv4 - if ( strpos($this->_params->id2, "6")!==false ) { $this->address_type = "IPv6"; } + if ( strpos((string) $this->_params->id2, "6")!==false ) { $this->address_type = "IPv6"; } // ipv6 - elseif ( strpos($this->_params->id2, "4")!==false ) { $this->address_type = "IPv4"; } + elseif ( strpos((string) $this->_params->id2, "4")!==false ) { $this->address_type = "IPv4"; } // both else { $this->Response->throw_exception(400, "Invalid address type"); } } @@ -684,7 +687,7 @@ private function search_custom_field_name_subnets () { else { $limit = ""; } // set query and params $query = "select * from `subnets` where `".$this->custom_field_name."` = ? $limit order by `".$this->custom_field_orderby."` ".$this->custom_field_order_direction.";"; - $params = array($this->_params->id); + $params = [$this->_params->id]; // search try { $subnets = $this->Database->getObjectsQuery('subnets', $query, $params); } catch (Exception $e) { $this->Response->throw_exception(500, "Error: ".$e->getMessage()); } @@ -841,18 +844,18 @@ private function find_external_id_subnets_addresses ($type = "subnets") { public function get_subnet_select_parameters ($type = "subnets") { // subnets or addresses if($type=="subnets") { - return array( + return [ "name"=>$this->custom_field_name, "order"=>$this->custom_field_orderby, "direction"=>$this->custom_field_order_direction - ); + ]; } else { - return array( + return [ "name"=>$this->custom_field_name_addr, "order"=>$this->custom_field_orderby_addr, "direction"=>$this->custom_field_order_direction_addr - ); + ]; } } } diff --git a/api/controllers/Responses.php b/public/api/controllers/Responses.php similarity index 94% rename from api/controllers/Responses.php rename to public/api/controllers/Responses.php index dcf9639b6..35c52099d 100644 --- a/api/controllers/Responses.php +++ b/public/api/controllers/Responses.php @@ -45,7 +45,7 @@ public function __construct() { * @param array $custom_fields * @return void */ - public function formulate_result ($result, $time = false, $nest_custom_fields = false, $custom_fields = array()) { + public function formulate_result ($result, $time = false, $nest_custom_fields = false, $custom_fields = []) { // make sure result is array $this->result = is_null($this->result) ? (array) $result : $this->result; @@ -82,9 +82,9 @@ public function formulate_result ($result, $time = false, $nest_custom_fields = public function validate_content_type () { // remove charset if provided if(isset($_SERVER['CONTENT_TYPE'])) - $_SERVER['CONTENT_TYPE'] = array_shift(pf_explode(";", $_SERVER['CONTENT_TYPE'])); + $_SERVER['CONTENT_TYPE'] = array_shift(explode(";", (string) $_SERVER['CONTENT_TYPE'])); // not set, presume json - if( !isset($_SERVER['CONTENT_TYPE']) || strlen(@$_SERVER['CONTENT_TYPE'])==0 ) {} + if( !isset($_SERVER['CONTENT_TYPE']) || strlen((string) @$_SERVER['CONTENT_TYPE'])==0 ) {} // post elseif($_SERVER['CONTENT_TYPE']=="application/x-www-form-urlencoded") {} // set, verify @@ -159,7 +159,7 @@ private function set_success_header () { * @param array $custom_fields * @return void */ - private function nest_custom_fields ($custom_fields = array()) { + private function nest_custom_fields ($custom_fields = []) { // make sure custom_fields is array if(!is_array($custom_fields)) { $custom_fields = []; } @@ -264,7 +264,7 @@ private function array_to_xml(SimpleXMLElement $object, array $data) { // loop through values foreach ($data as $key => $value) { // if spaces exist in key replace them with underscores - if(strpos($key, " ")>0) { $key = str_replace(" ", "_", $key); } + if(strpos((string) $key, " ")>0) { $key = str_replace(" ", "_", (string) $key); } // if key is numeric append item if(is_numeric($key)) $key = "item".$key; @@ -296,7 +296,7 @@ private function array_to_xml(SimpleXMLElement $object, array $data) { * @license http://creativecommons.org/licenses/by/3.0/ * @license CC-BY-3.0 */ - public function xml_to_array ( $xmlObject, $out = array () ) { + public function xml_to_array ( $xmlObject, $out = [] ) { foreach ( (array) $xmlObject as $index => $node ) $out[$index] = ( is_object ( $node ) ) ? $this->xml_to_array ( $node ) : $node; @@ -314,7 +314,7 @@ private function object_to_array ($obj) { // object to array if(is_object($obj)) $obj = (array) $obj; if(is_array($obj)) { - $new = array(); + $new = []; foreach($obj as $key => $val) { $new[$key] = $this->object_to_array($val); } diff --git a/api/controllers/Search.php b/public/api/controllers/Search.php similarity index 81% rename from api/controllers/Search.php rename to public/api/controllers/Search.php index 16bb54a23..ce8024c59 100755 --- a/api/controllers/Search.php +++ b/public/api/controllers/Search.php @@ -46,7 +46,7 @@ public function __construct($Database, $Tools, $params, $Response) { */ private function define_search_items () { foreach ($this->_params as $item => $value) { - if (array_key_exists($item, $this->search_items)) { + if (array_key_exists((string) $item, $this->search_items)) { if($value==0 || $value==1) { $this->search_items[$item] = $value; } @@ -63,17 +63,18 @@ private function define_search_items () { * @access public * @return void */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result = array(); - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/search/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"))), - ); + $result = []; + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/search/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"]]], + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -96,7 +97,8 @@ public function OPTIONS () { * @access public * @return void */ - public function GET () { + #[\Override] + public function GET () { // start search if(isset($this->_params->id)) { // set result array @@ -114,7 +116,7 @@ public function GET () { $result['search_filter'] = $this->search_items; // return result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } // search string missing else { @@ -152,10 +154,10 @@ private function search_subnets () { // result if(sizeof($result)==0) { - return array("code"=>404, "data"=>"No subnets found"); + return ["code"=>404, "data"=>"No subnets found"]; } else { - return array("code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, false)); + return ["code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, false)]; } } @@ -172,10 +174,10 @@ private function search_addresses () { // result if(sizeof($result)==0) { - return array("code"=>404, "data"=>"No addresses found"); + return ["code"=>404, "data"=>"No addresses found"]; } else { - return array("code"=>200, "data"=>$this->prepare_result ($result, "addresses", true, false)); + return ["code"=>200, "data"=>$this->prepare_result ($result, "addresses", true, false)]; } } @@ -190,10 +192,10 @@ private function search_vlans () { // result if(sizeof($result)==0) { - return array("code"=>404, "data"=>"No vlan found"); + return ["code"=>404, "data"=>"No vlan found"]; } else { - return array("code"=>200, "data"=>$this->prepare_result ($result, "vlans", true, false)); + return ["code"=>200, "data"=>$this->prepare_result ($result, "vlans", true, false)]; } } @@ -208,10 +210,10 @@ private function search_vrfs () { // result if(sizeof($result)==0) { - return array("code"=>404, "data"=>"No vrf found"); + return ["code"=>404, "data"=>"No vrf found"]; } else { - return array("code"=>200, "data"=>$this->prepare_result ($result, "vrfs", true, false)); + return ["code"=>200, "data"=>$this->prepare_result ($result, "vrfs", true, false)]; } } } diff --git a/api/controllers/Sections.php b/public/api/controllers/Sections.php similarity index 80% rename from api/controllers/Sections.php rename to public/api/controllers/Sections.php index 52331e307..bdbc2a2ee 100755 --- a/api/controllers/Sections.php +++ b/public/api/controllers/Sections.php @@ -38,21 +38,22 @@ public function __construct($Database, $Tools, $params, $Response) { * @access public * @return void */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result = array(); - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/sections/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/sections/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); + $result = []; + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/sections/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/sections/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -75,7 +76,8 @@ public function OPTIONS () { * @access public * @return void */ - public function GET () { + #[\Override] + public function GET () { // fetch subnets in section if(@$this->_params->id2=="subnets" && is_numeric($this->_params->id)) { // we don't need id2 anymore @@ -117,21 +119,21 @@ public function GET () { if(empty($result)) { $this->Response->throw_exception(404, "No subnets found"); } else { $this->custom_fields = $this->Tools->fetch_custom_fields('subnets'); - return array("code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, true)); + return ["code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, true)]; } } // verify ID elseif(isset($this->_params->id)) { # changelog if($this->_params->id2=="changelog") { - return array("code"=>200, "data"=>$this->section_changelog ()); + return ["code"=>200, "data"=>$this->section_changelog ()]; } # fetch by id elseif(is_numeric($this->_params->id)) { $result = $this->Sections->fetch_section ("id", $this->_params->id); // check result if($result===false) { $this->Response->throw_exception(404, "Section does not exist"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } # Custom fields not supported elseif($this->_params->id=="custom_fields") { @@ -142,7 +144,7 @@ public function GET () { $result = $this->Sections->fetch_section ("name", $this->_params->id); // check result if($result==false) { $this->Response->throw_exception(404, $this->Response->errors[404]); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } } # all sections @@ -150,8 +152,8 @@ public function GET () { // all sections $result = $this->Sections->fetch_all_sections(); // check result - if($result===false) { return array("code"=>200, "message"=>"No sections available"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + if($result===false) { return ["code"=>200, "message"=>"No sections available"]; } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } } @@ -165,7 +167,8 @@ public function GET () { * @access public * @return void */ - public function POST () { + #[\Override] + public function POST () { # check for valid keys $values = $this->validate_keys (); @@ -173,7 +176,7 @@ public function POST () { unset($values['editDate']); # validate mandatory parameters - if(strlen($this->_params->name)<3) { $this->Response->throw_exception(400, 'Name is mandatory or too short (mininum 3 characters)'); } + if(strlen((string) $this->_params->name)<3) { $this->Response->throw_exception(400, 'Name is mandatory or too short (mininum 3 characters)'); } # verify masterSection if(isset($this->_params->masterSection)) { @@ -188,7 +191,7 @@ public function POST () { { $this->Response->throw_exception(500, "Section create failed"); } else { //set result - return array("code"=>201, "message"=>"Section created", "id"=>$this->Sections->lastInsertId, "location"=>"/api/".$this->_params->app_id."/sections/".$this->Sections->lastInsertId."/"); + return ["code"=>201, "message"=>"Section created", "id"=>$this->Sections->lastInsertId, "location"=>"/api/".$this->_params->app_id."/sections/".$this->Sections->lastInsertId."/"]; } } @@ -202,7 +205,8 @@ public function POST () { * @access public * @return void */ - public function PATCH () { + #[\Override] + public function PATCH () { # Check for id if(!isset($this->_params->id)) { $this->Response->throw_exception(400, "Section Id required"); } # check that section exists @@ -217,7 +221,7 @@ public function PATCH () { { $this->Response->throw_exception(500, "Section update failed"); } else { //set result - return array("code"=>200, "data"=>NULL); + return ["code"=>200, "data"=>NULL]; } } @@ -231,7 +235,8 @@ public function PATCH () { * @access public * @return void */ - public function DELETE () { + #[\Override] + public function DELETE () { # Check for id if(!isset($this->_params->id)) { $this->Response->throw_exception(400, "Section Id required"); } # check that section exists @@ -239,7 +244,7 @@ public function DELETE () { { $this->Response->throw_exception(404, "Section does not exist"); } # set variables for update - $values = array(); + $values = []; $values["id"] = $this->_params->id; # execute update @@ -247,7 +252,7 @@ public function DELETE () { { $this->Response->throw_exception(500, "Section delete failed"); } else { //set result - return array("code"=>200, "data"=>NULL); + return ["code"=>200, "data"=>NULL]; } } @@ -286,7 +291,7 @@ private function section_changelog () { if (sizeof($clogs)>0) { foreach ($clogs as $l) { // diff to array - $l->cdiff = explode("\r\n", str_replace(["[","]"], "", trim($l->cdiff))); + $l->cdiff = explode("\r\n", str_replace(["[","]"], "", trim((string) $l->cdiff))); // save $clogs_formatted[] = [ "user" => $l->real_name, diff --git a/api/controllers/Subnets.php b/public/api/controllers/Subnets.php similarity index 89% rename from api/controllers/Subnets.php rename to public/api/controllers/Subnets.php index 537dab5f8..e82213e0c 100644 --- a/api/controllers/Subnets.php +++ b/public/api/controllers/Subnets.php @@ -48,21 +48,22 @@ public function __construct($Database, $Tools, $params, $Response) { * @access public * @return array */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result = array(); - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/subnets/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/subnets/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); + $result = []; + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/subnets/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/subnets/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -80,7 +81,8 @@ public function OPTIONS () { * @access public * @return array */ - public function POST () { + #[\Override] + public function POST () { # add required parameters if(!isset($this->_params->isFolder)) { $this->_params->isFolder = "0"; } elseif($this->_params->isFolder==1) { unset($this->_params->subnet, $this->_params->mask); } @@ -106,7 +108,7 @@ public function POST () { } else { //set result - return array("code"=>201, "message"=>"Subnet created", "id"=>$this->Subnets->lastInsertId, "data"=>$this->Addresses->transform_address($values['subnet'] ,"dotted")."/".$values['mask'], "location"=>"/api/".$this->_params->app_id."/subnets/".$this->Subnets->lastInsertId."/"); + return ["code"=>201, "message"=>"Subnet created", "id"=>$this->Subnets->lastInsertId, "data"=>$this->Addresses->transform_address($values['subnet'] ,"dotted")."/".$values['mask'], "location"=>"/api/".$this->_params->app_id."/subnets/".$this->Subnets->lastInsertId."/"]; } } @@ -160,13 +162,14 @@ private function post_find_free_subnet($direction = Subnets::SEARCH_FIND_FIRST) * @access public * @return array */ - public function GET () { + #[\Override] + public function GET () { // all if (!isset($this->_params->id) || $this->_params->id == "all") { $result = $this->read_all_subnets(); // check result if ($result===false) { $this->Response->throw_exception(500, "Unable to read subnets"); } - else { return array("code"=>200, "data"=>$this->prepare_result($result, "subnets", true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result($result, "subnets", true, true)]; } } // cidr check // check if id2 is set ? @@ -176,13 +179,13 @@ public function GET () { $result = $this->read_search_subnet (); // check result if($result==false) { $this->Response->throw_exception(404, "No subnets found"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } if($this->_params->id=="overlapping") { $result = $this->read_overlapping_subnet (); if($result==false) { $this->Response->throw_exception(404, "No subnets found"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // validate id @@ -206,7 +209,7 @@ public function GET () { if($result===false) { $this->Response->throw_exception(404, "No addresses found"); } else { $this->custom_fields = $this->Tools->fetch_custom_fields('ipaddresses'); - return array("code"=>200, "data"=>$this->prepare_result ($result, "addresses", true, true)); + return ["code"=>200, "data"=>$this->prepare_result ($result, "addresses", true, true)]; } } // slaves @@ -214,27 +217,27 @@ public function GET () { $result = $this->read_subnet_slaves (); // check result if($result==NULL) { $this->Response->throw_exception(404, "No slaves"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // slaves-recursive elseif ($this->_params->id2=="slaves_recursive") { $result = $this->read_subnet_slaves_recursive (); // check result if($result==NULL) { $this->Response->throw_exception(404, "No slaves"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // usage - elseif ($this->_params->id2=="usage") { return array("code"=>200, "data"=>$this->subnet_usage ()); } + elseif ($this->_params->id2=="usage") { return ["code"=>200, "data"=>$this->subnet_usage ()]; } // first available address - elseif ($this->_params->id2=="first_free") { return array("code"=>200, "data"=>$this->subnet_first_free_address ()); } + elseif ($this->_params->id2=="first_free") { return ["code"=>200, "data"=>$this->subnet_first_free_address ()]; } // search for new free subnet - elseif ($this->_params->id2=="all_subnets") { return array("code"=>200, "data"=>$this->subnet_find_free (Subnets::SEARCH_FIND_ALL, Subnets::SEARCH_FIND_FIRST)); } + elseif ($this->_params->id2=="all_subnets") { return ["code"=>200, "data"=>$this->subnet_find_free (Subnets::SEARCH_FIND_ALL, Subnets::SEARCH_FIND_FIRST)]; } // search for new free subnet - elseif ($this->_params->id2=="first_subnet"){ return array("code"=>200, "data"=>$this->subnet_find_free (1, Subnets::SEARCH_FIND_FIRST)); } + elseif ($this->_params->id2=="first_subnet"){ return ["code"=>200, "data"=>$this->subnet_find_free (1, Subnets::SEARCH_FIND_FIRST)]; } // search for new free subnet - elseif ($this->_params->id2=="last_subnet") { return array("code"=>200, "data"=>$this->subnet_find_free (1, Subnets::SEARCH_FIND_LAST)); } + elseif ($this->_params->id2=="last_subnet") { return ["code"=>200, "data"=>$this->subnet_find_free (1, Subnets::SEARCH_FIND_LAST)]; } // return changelog - elseif ($this->_params->id2=="changelog") { return array("code"=>200, "data"=>$this->subnet_changelog ()); } + elseif ($this->_params->id2=="changelog") { return ["code"=>200, "data"=>$this->subnet_changelog ()]; } // fail else { $this->Response->throw_exception(400, 'Invalid request'); } } @@ -242,14 +245,14 @@ public function GET () { elseif ($this->_params->id=="custom_fields") { // check result if(sizeof($this->custom_fields)==0) { $this->Response->throw_exception(404, 'No custom fields defined'); } - else { return array("code"=>200, "data"=>$this->custom_fields); } + else { return ["code"=>200, "data"=>$this->custom_fields]; } } // id elseif (is_numeric($this->_params->id)) { $result = $this->read_subnet (); // check result if($result==false) { $this->Response->throw_exception(400, "Invalid subnet Id (".$this->_params->id.")"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, true)]; } } // false else { $this->Response->throw_exception(404, 'Invalid Id'); } @@ -274,7 +277,8 @@ public function GET () { * @access public * @return array */ - public function PATCH () { + #[\Override] + public function PATCH () { // Check for id $this->validate_subnet_id (); @@ -311,7 +315,7 @@ public function PATCH () { if(!$this->Subnets->modify_subnet ("edit", $values)) { $this->Response->throw_exception(500, 'Subnet update failed'); } else { - return array("code"=>200, "message"=>"Subnet updated"); + return ["code"=>200, "message"=>"Subnet updated"]; } } } @@ -332,7 +336,8 @@ public function PATCH () { * @access public * @return array */ - public function DELETE () { + #[\Override] + public function DELETE () { // Check for id $this->validate_subnet_id (); @@ -348,7 +353,7 @@ public function DELETE () { // ok, delete subnet else { # set variables for delete - $values = array(); + $values = []; $values["id"] = $this->_params->id; # execute update @@ -356,7 +361,7 @@ public function DELETE () { { $this->Response->throw_exception(500, "Failed to delete subnet"); } else { //set result - return array("code"=>200, "message"=>"Subnet deleted"); + return ["code"=>200, "message"=>"Subnet deleted"]; } } } @@ -379,7 +384,7 @@ private function subnet_truncate () { // ok, try to truncate $this->Subnets->modify_subnet ("truncate", (array) $this->_params); //set result - return array("code"=>200, "message"=>"Subnet truncated"); + return ["code"=>200, "message"=>"Subnet truncated"]; } @@ -416,14 +421,14 @@ private function subnet_resize () { } # set update values - $values = array("id"=>$this->_params->id, + $values = ["id"=>$this->_params->id, "subnet"=>$subnet_new, "mask"=>$this->_params->mask - ); + ]; $this->Subnets->modify_subnet ("resize", $values); //set result - return array("code"=>200, "message"=>"Subnet resized"); + return ["code"=>200, "message"=>"Subnet resized"]; } @@ -454,7 +459,7 @@ private function subnet_split () { $this->Subnets->subnet_split ($subnet_old, $this->_params->number, $this->_params->prefix, $this->_params->group, $this->_params->copy_custom); //set result - return array("code"=>200, "message"=>"Subnet split"); + return ["code"=>200, "message"=>"Subnet split"]; } @@ -485,7 +490,7 @@ private function subnet_change_permissions () { if(!$this->Subnets->modify_subnet ("edit", $values)) { $this->Response->throw_exception(500, 'Subnet permissions update failed'); } else { - return array("code"=>200, "message"=>"Subnet permissions updated", "data"=>$this->_params->permissions_text); + return ["code"=>200, "message"=>"Subnet permissions updated", "data"=>$this->_params->permissions_text]; } } @@ -499,8 +504,8 @@ private function validate_create_permissions () { // set valid permissions array $valid_permissions_array = $this->get_possible_permissions (); // requested permissions - $requested_permissions = array(); - $requested_permissions_full = array(); + $requested_permissions = []; + $requested_permissions_full = []; // save ids $id = $this->_params->id; unset($this->_params->controller, $this->_params->app_id, $this->_params->id, $this->_params->id2, $this->_params->isFolder); @@ -520,7 +525,7 @@ private function validate_create_permissions () { } } else { - if(!array_key_exists($perm, $valid_permissions_array)) { + if(!array_key_exists((string) $perm, $valid_permissions_array)) { $this->Response->throw_exception(500, "Invalid permissions ".$perm); } else { @@ -558,9 +563,9 @@ private function subnet_remove_permissions () { // Check for id $this->validate_subnet_id (); // ok, try to truncate - $this->Subnets->modify_subnet ("edit", array("id"=>$this->_params->id, "permissions"=>"")); + $this->Subnets->modify_subnet ("edit", ["id"=>$this->_params->id, "permissions"=>""]); //set result - return array("code"=>200, "message"=>"Subnet permissions removed"); + return ["code"=>200, "message"=>"Subnet permissions removed"]; } @@ -652,7 +657,7 @@ private function subnet_changelog () { if (sizeof($clogs)>0) { foreach ($clogs as $l) { // diff to array - $l->cdiff = explode("\r\n", str_replace(["[","]"], "", trim($l->cdiff))); + $l->cdiff = explode("\r\n", str_replace(["[","]"], "", trim((string) $l->cdiff))); // save $clogs_formatted[] = [ "user" => $l->real_name, @@ -750,7 +755,7 @@ private function read_all_subnets() { if(!empty($result->location)) { $result->location = $this->Tools->fetch_object ("locations", "id", $result->location); } else { - $result->location = array(); + $result->location = []; } // erase old values @@ -797,7 +802,7 @@ private function read_subnet_slaves_recursive () { // get array of ids $this->Subnets->fetch_subnet_slaves_recursive ($this->_params->id); // init result - $result = array (); + $result = []; // fetch all; foreach($this->Subnets->slaves as $s) { $result[] = $this->read_subnet ($s); diff --git a/api/controllers/Tools.php b/public/api/controllers/Tools.php similarity index 85% rename from api/controllers/Tools.php rename to public/api/controllers/Tools.php index 6bc3d2149..6bd3d89ae 100644 --- a/api/controllers/Tools.php +++ b/public/api/controllers/Tools.php @@ -77,7 +77,7 @@ public function __construct($Database, $Tools, $params, $Response) { * @return void */ private function define_tools_controllers () { - $this->subcontrollers = array( + $this->subcontrollers = [ "ipTags" => "tags", "devices" => "devices", "deviceTypes" => "device_types", @@ -89,7 +89,7 @@ private function define_tools_controllers () { "racks" => "racks", "nat" => "nat", "customers" => "customers" - ); + ]; } /** @@ -99,19 +99,19 @@ private function define_tools_controllers () { * @return void */ private function define_available_identifiers () { - $this->identifiers = array( - "ipTags" => array("id2", "id3"), - "devices" => array("id2", "id3"), - "deviceTypes" => array("id2", "id3"), - "vlans" => array("id2", "id3"), - "vrf" => array("id2", "id3"), - "nameservers" => array("id2"), - "scanAgents" => array("id2"), - "locations" => array("id2", "id3"), - "racks" => array("id2", "id3"), - "nat" => array("id2", "id3"), - "customers" => array("id2") - ); + $this->identifiers = [ + "ipTags" => ["id2", "id3"], + "devices" => ["id2", "id3"], + "deviceTypes" => ["id2", "id3"], + "vlans" => ["id2", "id3"], + "vrf" => ["id2", "id3"], + "nameservers" => ["id2"], + "scanAgents" => ["id2"], + "locations" => ["id2", "id3"], + "racks" => ["id2", "id3"], + "nat" => ["id2", "id3"], + "customers" => ["id2"] + ]; } /** @@ -140,7 +140,8 @@ private function define_sort_key () { * @access public * @return void */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); @@ -148,22 +149,22 @@ public function OPTIONS () { $app = $this->Tools->fetch_object ("api", "app_id", $this->_params->app_id); // controllers - $controllers = array( - array("rel"=>"sections", "href"=>"/api/".$_GET['app_id']."/sections/"), - array("rel"=>"subnets", "href"=>"/api/".$_GET['app_id']."/subnets/"), - array("rel"=>"folders", "href"=>"/api/".$_GET['app_id']."/folders/"), - array("rel"=>"addresses", "href"=>"/api/".$_GET['app_id']."/addresses/"), - array("rel"=>"vlans", "href"=>"/api/".$_GET['app_id']."/vlan/"), - array("rel"=>"vrfs", "href"=>"/api/".$_GET['app_id']."/vrf/"), - array("rel"=>"nameservers", "href"=>"/api/".$_GET['app_id']."/tools/nameservers/"), - array("rel"=>"scanAgents", "href"=>"/api/".$_GET['app_id']."/tools/scanagents/"), - array("rel"=>"locations", "href"=>"/api/".$_GET['app_id']."/tools/locations/"), - array("rel"=>"racks", "href"=>"/api/".$_GET['app_id']."/tools/racks/"), - array("rel"=>"nat", "href"=>"/api/".$_GET['app_id']."/tools/nat/"), - array("rel"=>"tools", "href"=>"/api/".$_GET['app_id']."/tools/") - ); + $controllers = [ + ["rel"=>"sections", "href"=>"/api/".$_GET['app_id']."/sections/"], + ["rel"=>"subnets", "href"=>"/api/".$_GET['app_id']."/subnets/"], + ["rel"=>"folders", "href"=>"/api/".$_GET['app_id']."/folders/"], + ["rel"=>"addresses", "href"=>"/api/".$_GET['app_id']."/addresses/"], + ["rel"=>"vlans", "href"=>"/api/".$_GET['app_id']."/vlan/"], + ["rel"=>"vrfs", "href"=>"/api/".$_GET['app_id']."/vrf/"], + ["rel"=>"nameservers", "href"=>"/api/".$_GET['app_id']."/tools/nameservers/"], + ["rel"=>"scanAgents", "href"=>"/api/".$_GET['app_id']."/tools/scanagents/"], + ["rel"=>"locations", "href"=>"/api/".$_GET['app_id']."/tools/locations/"], + ["rel"=>"racks", "href"=>"/api/".$_GET['app_id']."/tools/racks/"], + ["rel"=>"nat", "href"=>"/api/".$_GET['app_id']."/tools/nat/"], + ["rel"=>"tools", "href"=>"/api/".$_GET['app_id']."/tools/"] + ]; # Response - return array("code"=>200, "data"=>array("permissions"=>$this->Subnets->parse_permissions($app->app_permissions), "controllers"=>$controllers)); + return ["code"=>200, "data"=>["permissions"=>$this->Subnets->parse_permissions($app->app_permissions), "controllers"=>$controllers]]; } @@ -203,7 +204,8 @@ public function OPTIONS () { * @access public * @return void */ - public function GET () { + #[\Override] + public function GET () { # validate identifiers $this->validate_subcontroller_identifier (); @@ -212,7 +214,7 @@ public function GET () { $result = $this->Tools->fetch_all_objects ($this->_params->id, $this->sort_key); // result if($result===false) { $this->Response->throw_exception(404, 'No objects found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, "tools/".$this->_params->id, true, false)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, "tools/".$this->_params->id, true, false)]; } } # by parameter elseif (isset($this->_params->id3)) { @@ -308,7 +310,7 @@ public function GET () { } // result if($result===false) { $this->Response->throw_exception(404, 'No objects found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, "tools/".$this->_params->id, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, "tools/".$this->_params->id, true, true)]; } } # by id @@ -319,7 +321,7 @@ public function GET () { $result = $this->Tools->fetch_object ($this->_params->id, $this->sort_key, $this->_params->id2); // result if($result===false) { $this->Response->throw_exception(404, 'No objects found'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, "tools/".$this->_params->id, true, false)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, "tools/".$this->_params->id, true, false)]; } } } @@ -338,7 +340,8 @@ public function GET () { * @access public * @return void */ - public function POST () { + #[\Override] + public function POST () { # rewrite tool controller _params $table_name = $this->rewrite_tool_input_params (); @@ -361,7 +364,7 @@ public function POST () { $this->Response->throw_exception(500, $table_name." object creation failed"); //set result - return array("code"=>201, "data"=>$table_name." object created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/tools/".$table_name."/".$this->Admin->lastId."/"); + return ["code"=>201, "data"=>$table_name." object created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/tools/".$table_name."/".$this->Admin->lastId."/"]; } @@ -374,7 +377,8 @@ public function POST () { * @access public * @return void */ - public function PATCH () { + #[\Override] + public function PATCH () { # rewrite tool controller _params $table_name = $this->rewrite_tool_input_params(); @@ -400,7 +404,7 @@ public function PATCH () { $this->Response->throw_exception(500, $table_name." object edit failed"); //set result - return array("code"=>200, "message"=>$table_name." object updated"); + return ["code"=>200, "message"=>$table_name." object updated"]; } @@ -413,7 +417,8 @@ public function PATCH () { * @access public * @return void */ - public function DELETE () { + #[\Override] + public function DELETE () { # rewrite tool controller _params $table_name = $this->rewrite_tool_input_params(); @@ -421,7 +426,7 @@ public function DELETE () { $this->validate_tools_object ($table_name); # set variables for delete - $values = array(); + $values = []; $values[$this->sort_key] = $this->_params->{$this->sort_key}; # execute delete @@ -437,7 +442,7 @@ public function DELETE () { $this->Admin->remove_object_references ("ipaddresses", $update_field, $this->_params->{$this->sort_key}); // set result - return array("code"=>200, "message"=>$table_name." object deleted"); + return ["code"=>200, "message"=>$table_name." object deleted"]; } /** @@ -584,7 +589,7 @@ private function parse_nat_objects ($obj) { return(db_json_decode($obj, true)); } else { - return array (); + return []; } } diff --git a/api/controllers/User.php b/public/api/controllers/User.php similarity index 91% rename from api/controllers/User.php rename to public/api/controllers/User.php index ad9165950..1476242c7 100644 --- a/api/controllers/User.php +++ b/public/api/controllers/User.php @@ -100,20 +100,21 @@ public function __construct ($Database, $Tools, $params, $Response) { * @access public * @return void */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result = array(); - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/user/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); + $result = []; + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/user/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -132,7 +133,8 @@ public function OPTIONS () { * - /all/ // returns all phpipam users * - /admins/ // returns ipam admins */ - public function GET () { + #[\Override] + public function GET () { // token_expires if ($this->_params->id=="token_expires" || $this->_params->id=="token" || !isset($this->_params->id) || $this->_params->id=="all" || $this->_params->id=="admins") { // block IP @@ -151,15 +153,15 @@ public function GET () { else { // admins or all if ($this->_params->id=="admins") { - return array("code"=>200, "data"=>$this->User->fetch_multiple_objects ("users", "role", "Administrator", "id", true, false, "*")); + return ["code"=>200, "data"=>$this->User->fetch_multiple_objects ("users", "role", "Administrator", "id", true, false, "*")]; } else { - return array("code"=>200, "data"=>$this->User->fetch_all_objects ("users", "id", true)); + return ["code"=>200, "data"=>$this->User->fetch_all_objects ("users", "id", true)]; } } } else { - return array("code"=>200, "data"=>array("expires"=>$this->token_expires)); + return ["code"=>200, "data"=>["expires"=>$this->token_expires]]; } } // return success for backwards compatibility @@ -178,7 +180,8 @@ public function GET () { * @access public * @return void */ - public function POST () { + #[\Override] + public function POST () { // block IP $this->validate_block (); // authenticate user and provide token @@ -195,7 +198,8 @@ public function POST () { * @access public * @return void */ - public function PATCH () { + #[\Override] + public function PATCH () { // block IP $this->validate_block (); // validate token @@ -203,7 +207,7 @@ public function PATCH () { // refresh $this->refresh_token_expiration (); // ok - return array("code"=>200, "data"=>array("expires"=>$this->token_expires)); + return ["code"=>200, "data"=>["expires"=>$this->token_expires]]; } @@ -217,7 +221,8 @@ public function PATCH () { * @access public * @return void */ - public function DELETE () { + #[\Override] + public function DELETE () { // block IP $this->validate_block (); // validate token @@ -225,7 +230,7 @@ public function DELETE () { // remove token $this->remove_token (); // result - return array("code"=>200, "data"=>array("Token removed")); + return ["code"=>200, "data"=>["Token removed"]]; } @@ -324,7 +329,7 @@ private function authenticate () { } # result - return array("code"=>200, "data"=>array("token"=>$this->token, "expires"=>$this->token_expires)); + return ["code"=>200, "data"=>["token"=>$this->token, "expires"=>$this->token_expires]]; } /** @@ -421,11 +426,11 @@ public function set_token_length ($length = null) { */ private function save_user_token () { # set token values - $values = array( + $values = [ "id"=>$this->User->user->id, "token"=>$this->token, "token_valid_until"=>$this->token_expires - ); + ]; # save token to database if(!$this->Admin->object_modify ("users", "edit", "id", $values )) { $this->Response->throw_exception(500, "Failed to update token"); } @@ -546,7 +551,7 @@ private function validate_requested_token_code ($app_id) { * @return void */ private function validate_token_expiration () { - return strtotime($this->token_expires) < time() ? true : false; + return strtotime((string) $this->token_expires) < time() ? true : false; } /** @@ -560,7 +565,7 @@ private function refresh_token_expiration () { $this->token = $this->User->user->token; // convert existing expiry date string to a timestamp - $expire_time = strtotime($this->token_expires); + $expire_time = strtotime((string) $this->token_expires); // Write Throttling from token updates // In order to keep the DB writes from token updates to a minimum, only update the expire time @@ -571,10 +576,10 @@ private function refresh_token_expiration () { $this->token_expires = date("Y-m-d H:i:s", time()+$this->token_valid_time); # set token values - $values = array( + $values = [ "id"=>$this->User->user->id, "token_valid_until"=>$this->token_expires - ); + ]; # save token to database if(!$this->Admin->object_modify ("users", "edit", "id", $values )) { $this->Response->throw_exception(500, "Failed to update token expiration date"); } @@ -588,11 +593,11 @@ private function refresh_token_expiration () { */ private function remove_token () { # set token values - $values = array( + $values = [ "id"=>$this->User->user->id, "token"=>null, "token_valid_until"=>null - ); + ]; # save token to database if(!$this->Admin->object_modify ("users", "edit", "id", $values )) { $this->Response->throw_exception(500, "Failed to remove token"); } diff --git a/api/controllers/Vlan.php b/public/api/controllers/Vlan.php similarity index 100% rename from api/controllers/Vlan.php rename to public/api/controllers/Vlan.php diff --git a/api/controllers/Vlans.php b/public/api/controllers/Vlans.php similarity index 83% rename from api/controllers/Vlans.php rename to public/api/controllers/Vlans.php index 10a95e9a3..f23e8d513 100755 --- a/api/controllers/Vlans.php +++ b/public/api/controllers/Vlans.php @@ -49,20 +49,21 @@ public function __construct($Database, $Tools, $params, $Response) { * @access public * @return void */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/vlans/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/vlans/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/vlans/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/vlans/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -84,13 +85,14 @@ public function OPTIONS () { * @access public * @return void */ - public function GET () { + #[\Override] + public function GET () { // all if (!isset($this->_params->id) || $this->_params->id == "all") { $result = $this->Tools->fetch_all_objects ("vlans", 'vlanId'); // check result if($result===false) { $this->Response->throw_exception(404, 'No vlans configured'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // check weather to read belonging subnets elseif(@$this->_params->id2=="subnets") { @@ -124,28 +126,28 @@ public function GET () { if($result==NULL) { $this->Response->throw_exception(404, "No subnets found"); } else { $this->custom_fields = $this->Tools->fetch_custom_fields('subnets'); - return array("code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, true)); + return ["code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, true)]; } } // custom fields elseif (@$this->_params->id=="custom_fields") { // check result if(sizeof($this->custom_fields)==0) { $this->Response->throw_exception(404, 'No custom fields defined'); } - else { return array("code"=>200, "data"=>$this->custom_fields); } + else { return ["code"=>200, "data"=>$this->custom_fields]; } } // search elseif (@$this->_params->id=="search") { $result = $this->Tools->fetch_multiple_objects ("vlans", "number", $this->_params->id2, "vlanId"); // check result if($result==NULL) { $this->Response->throw_exception(404, "Vlans not found"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // read vlan details else { $result = $this->Tools->fetch_object ("vlans", "vlanId", $this->_params->id); // check result if($result==NULL) { $this->Response->throw_exception(404, "Vlan not found"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } } @@ -159,7 +161,8 @@ public function GET () { * @access public * @return void */ - public function POST () { + #[\Override] + public function POST () { # check for valid keys $values = $this->validate_keys (); @@ -174,7 +177,7 @@ public function POST () { { $this->Response->throw_exception(500, "Vlan creation failed"); } else { //set result - return array("code"=>201, "message"=>"Vlan created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/vlans/".$this->Admin->lastId."/"); + return ["code"=>201, "message"=>"Vlan created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/vlans/".$this->Admin->lastId."/"]; } } @@ -188,7 +191,8 @@ public function POST () { * @access public * @return void */ - public function PATCH () { + #[\Override] + public function PATCH () { # verify $this->validate_vlan_edit (); # check that it exists @@ -206,7 +210,7 @@ public function PATCH () { { $this->Response->throw_exception(500, "Vlan edit failed"); } else { //set result - return array("code"=>200, "message"=>"Vlan updated"); + return ["code"=>200, "message"=>"Vlan updated"]; } } @@ -222,12 +226,13 @@ public function PATCH () { * @access public * @return void */ - public function DELETE () { + #[\Override] + public function DELETE () { # verify $this->validate_vlan (); # set variables for update - $values = array(); + $values = []; $values["vlanId"] = $this->_params->id; # execute delete @@ -238,7 +243,7 @@ public function DELETE () { $this->Admin->remove_object_references ("subnets", "vlanId", $this->_params->id); // set result - return array("code"=>200, "message"=>"Vlan deleted"); + return ["code"=>200, "message"=>"Vlan deleted"]; } } diff --git a/api/controllers/Vrf.php b/public/api/controllers/Vrf.php similarity index 100% rename from api/controllers/Vrf.php rename to public/api/controllers/Vrf.php diff --git a/api/controllers/Vrfs.php b/public/api/controllers/Vrfs.php similarity index 80% rename from api/controllers/Vrfs.php rename to public/api/controllers/Vrfs.php index cd070649a..135fe86a1 100755 --- a/api/controllers/Vrfs.php +++ b/public/api/controllers/Vrfs.php @@ -40,20 +40,21 @@ public function __construct($Database, $Tools, $params, $Response) { * @access public * @return void */ - public function OPTIONS () { + #[\Override] + public function OPTIONS () { // validate $this->validate_options_request (); // methods - $result['methods'] = array( - array("href"=>"/api/".$this->_params->app_id."/vrfs/", "methods"=>array(array("rel"=>"options", "method"=>"OPTIONS"))), - array("href"=>"/api/".$this->_params->app_id."/vrfs/{id}/", "methods"=>array(array("rel"=>"read", "method"=>"GET"), - array("rel"=>"create", "method"=>"POST"), - array("rel"=>"update", "method"=>"PATCH"), - array("rel"=>"delete", "method"=>"DELETE"))), - ); + $result['methods'] = [ + ["href"=>"/api/".$this->_params->app_id."/vrfs/", "methods"=>[["rel"=>"options", "method"=>"OPTIONS"]]], + ["href"=>"/api/".$this->_params->app_id."/vrfs/{id}/", "methods"=>[["rel"=>"read", "method"=>"GET"], + ["rel"=>"create", "method"=>"POST"], + ["rel"=>"update", "method"=>"PATCH"], + ["rel"=>"delete", "method"=>"DELETE"]]], + ]; # result - return array("code"=>200, "data"=>$result); + return ["code"=>200, "data"=>$result]; } @@ -75,19 +76,20 @@ public function OPTIONS () { * @access public * @return void */ - public function GET () { + #[\Override] + public function GET () { // all if (!isset($this->_params->id) || $this->_params->id == "all") { $result = $this->Tools->fetch_all_objects ("vrf", 'vrfId'); // check result if($result===false) { $this->Response->throw_exception(404, 'No vrfs configured'); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } // custom fields if($this->_params->id=="custom_fields") { // check result if(sizeof($this->custom_fields)==0) { $this->Response->throw_exception(404, 'No custom fields defined'); } - else { return array("code"=>200, "data"=>$this->custom_fields); } + else { return ["code"=>200, "data"=>$this->custom_fields]; } } // subnets elseif (isset($this->_params->id2)) { @@ -111,7 +113,7 @@ public function GET () { if($result===false) { $this->Response->throw_exception(404, 'No subnets belonging to this vrf'); } else { $this->custom_fields = $this->Tools->fetch_custom_fields('subnets'); - return array("code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, true)); + return ["code"=>200, "data"=>$this->prepare_result ($result, "subnets", true, true)]; } } // error @@ -127,7 +129,7 @@ public function GET () { $result = $this->Tools->fetch_object ("vrf", "vrfId", $this->_params->id); // check result if($result===false) { $this->Response->throw_exception(404, "VRF not found"); } - else { return array("code"=>200, "data"=>$this->prepare_result ($result, null, true, true)); } + else { return ["code"=>200, "data"=>$this->prepare_result ($result, null, true, true)]; } } } @@ -141,7 +143,8 @@ public function GET () { * @access public * @return void */ - public function POST () { + #[\Override] + public function POST () { # check for valid keys $values = $this->validate_keys (); @@ -153,7 +156,7 @@ public function POST () { { $this->Response->throw_exception(500, "VRF creation failed"); } else { //set result - return array("code"=>201, "message"=>"VRF created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/vrfs/".$this->Admin->lastId."/"); + return ["code"=>201, "message"=>"VRF created", "id"=>$this->Admin->lastId, "location"=>"/api/".$this->_params->app_id."/vrfs/".$this->Admin->lastId."/"]; } } @@ -167,7 +170,8 @@ public function POST () { * @access public * @return void */ - public function PATCH () { + #[\Override] + public function PATCH () { # verify $this->validate_vrf (); # check that it exists @@ -185,7 +189,7 @@ public function PATCH () { { $this->Response->throw_exception(500, "Vrf edit failed"); } else { //set result - return array("code"=>200, "message"=>"VRF updated"); + return ["code"=>200, "message"=>"VRF updated"]; } } @@ -200,12 +204,13 @@ public function PATCH () { * @access public * @return void */ - public function DELETE () { + #[\Override] + public function DELETE () { # check that vrf exists $this->validate_vrf (); # set variables for update - $values = array(); + $values = []; $values["vrfId"] = $this->_params->id; # execute delete @@ -216,7 +221,7 @@ public function DELETE () { $this->Admin->remove_object_references ("subnets", "vrfId", $this->_params->id); // set result - return array("code"=>200, "message"=>"VRF deleted"); + return ["code"=>200, "message"=>"VRF deleted"]; } } diff --git a/api/controllers/custom/.gitignore b/public/api/controllers/custom/.gitignore similarity index 100% rename from api/controllers/custom/.gitignore rename to public/api/controllers/custom/.gitignore diff --git a/api/index.php b/public/api/index.php similarity index 86% rename from api/index.php rename to public/api/index.php index 8f2db25e5..0d4e60997 100755 --- a/api/index.php +++ b/public/api/index.php @@ -18,12 +18,11 @@ */ # include functions -if(!function_exists("create_link")) - require_once( dirname(__FILE__) . '/../functions/functions.php' ); // functions and objects from phpipam +require_once __DIR__ . '/../../functions/functions.php'; // functions and objects from phpipam # include common API controllers -require_once( dirname(__FILE__) . '/controllers/Common.php'); // common methods -require_once( dirname(__FILE__) . '/controllers/Responses.php'); // exception, header and response handling +require_once( __DIR__ . '/controllers/Common.php'); // common methods +require_once( __DIR__ . '/controllers/Responses.php'); // exception, header and response handling # Don't corrupt output with php errors! disable_php_errors(); @@ -85,7 +84,7 @@ $encryption_method = Config::ValueOf('api_crypt_encryption_library', 'openssl-128-cbc'); // decrypt request - form_encoded - if(strpos($content_type, "application/x-www-form-urlencoded")!==false) { + if(strpos((string) $content_type, "application/x-www-form-urlencoded")!==false) { $decoded = $User->Crypto->decrypt($_GET['enc_request'], $app->app_code, $encryption_method); if ($decoded === false) $Response->throw_exception(503, 'Invalid enc_request'); $decoded = $decoded[0]=="?" ? substr($decoded, 1) : $decoded; @@ -133,7 +132,7 @@ // Append Global API parameters / POST parameters if POST,PATCH or DELETE if($_SERVER['REQUEST_METHOD']=="GET" || $_SERVER['REQUEST_METHOD']=="POST" || $_SERVER['REQUEST_METHOD']=="PATCH" || $_SERVER['REQUEST_METHOD']=="DELETE") { // if application tupe is JSON (application/json) - if(strpos($content_type, "application/json")!==false){ + if(strpos((string) $content_type, "application/json")!==false){ $rawPostData = file_get_contents('php://input'); if (is_string($rawPostData) && !is_blank($rawPostData)) { $json = db_json_decode($rawPostData, true); @@ -145,7 +144,7 @@ } } // if application tupe is XML (application/json) - elseif(strpos($content_type, "application/xml")!==false){ + elseif(strpos((string) $content_type, "application/xml")!==false){ $rawPostData = file_get_contents('php://input'); if (is_string($rawPostData) && !is_blank($rawPostData)) { $xml = $Response->xml_to_array($rawPostData); @@ -179,7 +178,7 @@ if ($Params->controller != "user") { if($app->app_security=="ssl_token" || $app->app_security=="none") { // start auth class and validate connection - require_once( dirname(__FILE__) . '/controllers/User.php'); // authentication and token handling + require_once( __DIR__ . '/controllers/User.php'); // authentication and token handling $Authentication = new User_controller ($Database, $Tools, $Params, $Response); $Authentication->check_auth (); } @@ -187,7 +186,7 @@ // validate ssl_code if($app->app_security=="ssl_code") { // start auth class and validate connection - require_once( dirname(__FILE__) . '/controllers/User.php'); // authentication and token handling + require_once( __DIR__ . '/controllers/User.php'); // authentication and token handling $Authentication = new User_controller ($Database, $Tools, $Params, $Response); $Authentication->check_auth_code ($app->app_id); } @@ -197,7 +196,7 @@ // validate ssl_code if($app->app_security=="ssl_code" && $_SERVER['REQUEST_METHOD']!="GET") { // start auth class and validate connection - require_once( dirname(__FILE__) . '/controllers/User.php'); // authentication and token handling + require_once( __DIR__ . '/controllers/User.php'); // authentication and token handling $Authentication = new User_controller ($Database, $Tools, $Params, $Response); $Authentication->check_auth_code ($app->app_id); @@ -228,16 +227,16 @@ /* Initialize controller ---------- */ // get the controller and format it correctly - $controller_name = ucfirst($Params->controller)."_controller"; - $controller_file = ucfirst($Params->controller); + $controller_name = ucfirst((string) $Params->controller)."_controller"; + $controller_file = ucfirst((string) $Params->controller); // check if the controller exists. if not, throw an exception - if( file_exists( dirname(__FILE__) . "/controllers/$controller_file.php") ) { - require_once( dirname(__FILE__) . "/controllers/$controller_file.php"); + if( file_exists( __DIR__ . "/controllers/$controller_file.php") ) { + require_once( __DIR__ . "/controllers/$controller_file.php"); } // check custom controllers - elseif( file_exists( dirname(__FILE__) . "/controllers/custom/$controller_file.php") ) { - require_once( dirname(__FILE__) . "/controllers/custom/$controller_file.php"); + elseif( file_exists( __DIR__ . "/controllers/custom/$controller_file.php") ) { + require_once( __DIR__ . "/controllers/custom/$controller_file.php"); } else { $Response->throw_exception(400, 'Invalid controller'); @@ -254,17 +253,17 @@ // POST and PATCH. This only works for controllers that support custom // fields and if the app has nested custom fields enabled, otherwise // this is skipped. - if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST' || strtoupper($_SERVER['REQUEST_METHOD']) == 'PATCH') { + if (strtoupper((string) $_SERVER['REQUEST_METHOD']) == 'POST' || strtoupper((string) $_SERVER['REQUEST_METHOD']) == 'PATCH') { $controller->unmarshal_nested_custom_fields(); } // check if the action exists in the controller. if not, throw an exception. - if( method_exists($controller, strtolower($_SERVER['REQUEST_METHOD'])) === false ) { + if( method_exists($controller, strtolower((string) $_SERVER['REQUEST_METHOD'])) === false ) { $Response->throw_exception(501, $Response->errors[501]); } // Transaction locking is only enabled for POST, PUT, PATCH and DELETE requests. - if (in_array(strtoupper($_SERVER['REQUEST_METHOD']), ["POST", "PUT", "PATCH", "DELETE"])) { + if (in_array(strtoupper((string) $_SERVER['REQUEST_METHOD']), ["POST", "PUT", "PATCH", "DELETE"])) { $lock_type = $app->app_lock_type; if ($lock_type == "Auto") { diff --git a/app/admin/2fa/edit_user.php b/public/app/admin/2fa/edit_user.php similarity index 95% rename from app/admin/2fa/edit_user.php rename to public/app/admin/2fa/edit_user.php index 716b7965d..9d7affe23 100644 --- a/app/admin/2fa/edit_user.php +++ b/public/app/admin/2fa/edit_user.php @@ -5,7 +5,7 @@ *************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; diff --git a/app/admin/2fa/index.php b/public/app/admin/2fa/index.php similarity index 100% rename from app/admin/2fa/index.php rename to public/app/admin/2fa/index.php diff --git a/app/admin/2fa/save.php b/public/app/admin/2fa/save.php similarity index 76% rename from app/admin/2fa/save.php rename to public/app/admin/2fa/save.php index 5ca672cdd..2cbcc3cdb 100644 --- a/app/admin/2fa/save.php +++ b/public/app/admin/2fa/save.php @@ -5,7 +5,7 @@ **************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -29,16 +29,12 @@ if(!in_array($POST->{'2fa_provider'}, $providers)) { $Result->show("danger", _("Invalid provider"), true); } // verify name -if(strlen($POST->{'2fa_name'})>32 || is_blank($POST->{'2fa_name'})) { $Result->show("danger", _("Invalid application name"), true); } +if(strlen((string) $POST->{'2fa_name'})>32 || is_blank($POST->{'2fa_name'})) { $Result->show("danger", _("Invalid application name"), true); } // verify length if(!is_numeric($POST->{'2fa_length'})) { $Result->show("danger", _("Invalid value for length"), true); } if($POST->{'2fa_length'}>32 || $POST->{'2fa_length'}<26) { $Result->show("danger", _("Invalid length"), true); } -// make sure all git submodules are included -if (!file_exists(dirname(__FILE__)."/../../../functions/GoogleAuthenticator/PHPGangsta/GoogleAuthenticator.php")) { $Result->show("danger", _("GoogleAuthenticator submodule missing."), true); } -if (!file_exists(dirname(__FILE__)."/../../../functions/qrcodejs/qrcode.js")) { $Result->show("danger", _("QRCode submodule missing."), true); } - // change $POST->{'2fa_userchange'} = isset($POST->{'2fa_userchange'}) ? $POST->{'2fa_userchange'} : 0; diff --git a/app/admin/admin-menu-config.php b/public/app/admin/admin-menu-config.php similarity index 100% rename from app/admin/admin-menu-config.php rename to public/app/admin/admin-menu-config.php diff --git a/app/admin/admin-menu.php b/public/app/admin/admin-menu.php similarity index 100% rename from app/admin/admin-menu.php rename to public/app/admin/admin-menu.php diff --git a/app/admin/api/edit-result.php b/public/app/admin/api/edit-result.php similarity index 85% rename from app/admin/api/edit-result.php rename to public/app/admin/api/edit-result.php index fff8e40e8..65247814f 100755 --- a/app/admin/api/edit-result.php +++ b/public/app/admin/api/edit-result.php @@ -5,7 +5,7 @@ *************************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -27,15 +27,15 @@ $User->Crypto->csrf_cookie ("validate", "apiedit", $POST->csrf_cookie) === false ? $Result->show("danger", _("Invalid CSRF cookie"), true) : ""; /* checks */ -$error = array(); +$error = []; if($POST->action!="delete") { # code must be exactly 32 chars long and alphanumeric if app_security = crypt if($POST->app_security=="crypt") { - if(strlen($POST->app_code)!=32 || !preg_match("#^[a-zA-Z0-9-_=]+$#", $POST->app_code)) { $error[] = "Invalid application code"; } + if(strlen((string) $POST->app_code)!=32 || !preg_match("#^[a-zA-Z0-9-_=]+$#", (string) $POST->app_code)) { $error[] = "Invalid application code"; } } # name must be more than 2 and alphanumeric - if(strlen($POST->app_id)<3 || strlen($POST->app_id)>12 || !preg_match("#^[a-zA-Z0-9-_=]+$#",$POST->app_id)) { $error[] = "Invalid application id"; } + if(strlen((string) $POST->app_id)<3 || strlen((string) $POST->app_id)>12 || !preg_match("#^[a-zA-Z0-9-_=]+$#",(string) $POST->app_id)) { $error[] = "Invalid application id"; } # permissions must be 0,1,2 if($POST->app_security!="user") { if(!($POST->app_permissions==0 || $POST->app_permissions==1 || $POST->app_permissions ==2 || $POST->app_permissions ==3 )) { $error[] = "Invalid permissions"; } @@ -57,7 +57,7 @@ } else { # create array of values for modification - $values = array( + $values = [ "id" =>$POST->id, "app_id" =>$POST->app_id, "app_code" =>$POST->app_code, @@ -68,7 +68,7 @@ "app_nest_custom_fields" =>$POST->app_nest_custom_fields, "app_show_links" =>$POST->app_show_links, "app_comment" =>$POST->app_comment - ); + ]; # execute if(!$Admin->object_modify("api", $POST->action, "id", $values)) { $Result->show("danger", _("API"). " " . $User->get_post_action() ." "._("error"), true); } diff --git a/app/admin/api/edit.php b/public/app/admin/api/edit.php similarity index 94% rename from app/admin/api/edit.php rename to public/app/admin/api/edit.php index 8cc39c815..826b81bd3 100755 --- a/app/admin/api/edit.php +++ b/public/app/admin/api/edit.php @@ -5,7 +5,7 @@ *************************************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -81,7 +81,7 @@
' . $a['app_permissions'] . '' . $a['app_security'] . ' $user_num
"; diff --git a/app/admin/custom-fields/index.php b/public/app/admin/custom-fields/index.php similarity index 90% rename from app/admin/custom-fields/index.php rename to public/app/admin/custom-fields/index.php index 4c3762a90..79ede8d75 100755 --- a/app/admin/custom-fields/index.php +++ b/public/app/admin/custom-fields/index.php @@ -10,7 +10,7 @@ $User->is_admin(); /* fetch all custom fields */ -$custom_tables = array( +$custom_tables = [ "ipaddresses" => _("IP addresses"), "requests" => _("IP requests"), "subnets" => _("Subnets"), @@ -32,7 +32,7 @@ "vaults" => _("Vaults"), "vaultItems" => _("Vault items"), //"routing_ospf" => _("OSPF Routing") - ); + ]; # create array foreach($custom_tables as $k=>$f) { @@ -79,14 +79,14 @@ # get custom fields $ffields = db_json_decode($User->settings->hiddenCustomFields, true); - $ffields = is_array(@$ffields[$table]) ? $ffields[$table] : array(); + $ffields = is_array(@$ffields[$table]) ? $ffields[$table] : []; print "
"; - print "
"._($title)."
"; + print "
"._((string) $title)."
"; print "
"; - print " "; + print " "; print "
'. _($type->tname) .''. _($type->tdescription) .''. _((string) $type->tname) .''. _((string) $type->tdescription) .''. $type->bgcolor .''. $type->fgcolor .'
".$Result->show ("danger", _("Invalid ID"), false, false, true)."
snmp_queries); - $queries = is_array($queries) ? $queries : array(); + $queries = explode(";", (string) $device->snmp_queries); + $queries = is_array($queries) ? $queries : []; // loop foreach($Snmp->snmp_queries as $k=>$m) { if(in_array($k, $queries)) { print '
'. $k .'
'. "\n"; } diff --git a/app/admin/devices/edit.php b/public/app/admin/devices/edit.php similarity index 97% rename from app/admin/devices/edit.php rename to public/app/admin/devices/edit.php index b6c61c8a2..6753ed1a2 100755 --- a/app/admin/devices/edit.php +++ b/public/app/admin/devices/edit.php @@ -5,7 +5,7 @@ ************************/ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -45,7 +45,7 @@ } // defaults else { - $device = array (); + $device = []; $device['type'] = 9; $device['rack_start'] = 1; $device['rack_size'] = 1; @@ -134,7 +134,7 @@ fetch_all_objects("deviceTypes", "tid"); // if the type of this device isn't found in the list of device types, then prepend it - if (!in_array($device['type'],array_column($types,'tid'))) array_unshift($types,(object) array("tid"=>$device['type'],"tname"=>"Undefined")); + if (!in_array($device['type'],array_column($types,'tid'))) array_unshift($types,(object) ["tid"=>$device['type'],"tname"=>"Undefined"]); foreach($types as $name) { if($device['type'] == $name->tid) { print ""; } else { print ""; } @@ -257,8 +257,8 @@ $sections = $Sections->fetch_all_sections(); # reformat device sections to array - $deviceSections = pf_explode(";", @$device['sections']); - $deviceSections = is_array($deviceSections) ? $deviceSections : array(); + $deviceSections = explode(";", (string) @$device['sections']); + $deviceSections = is_array($deviceSections) ? $deviceSections : []; if ($sections!==false) { foreach($sections as $section) { diff --git a/app/admin/devices/index.php b/public/app/admin/devices/index.php similarity index 67% rename from app/admin/devices/index.php rename to public/app/admin/devices/index.php index c8a0d4ee0..43c77922c 100755 --- a/app/admin/devices/index.php +++ b/public/app/admin/devices/index.php @@ -4,7 +4,7 @@ * Script to print devices ***************************/ -include (dirname(__FILE__)."/../../tools/devices/all-devices.php"); +include (__DIR__."/../../tools/devices/all-devices.php"); ?> diff --git a/app/admin/dhcp/index.php b/public/app/admin/dhcp/index.php similarity index 85% rename from app/admin/dhcp/index.php rename to public/app/admin/dhcp/index.php index bfb0407d6..e87b1b9d2 100644 --- a/app/admin/dhcp/index.php +++ b/public/app/admin/dhcp/index.php @@ -5,7 +5,7 @@ $User->check_module_permissions ("dhcp", User::ACCESS_R, true, false); // valid tabs -$tabs = array("subnets", "leases", "reservations", "settings", "config"); +$tabs = ["subnets", "leases", "reservations", "settings", "config"]; ?>
@@ -26,7 +26,7 @@ $Result->show("danger", "Error parsing DHCP settings: ".$Tools->json_error, false); // settings - include(dirname(__FILE__) . "/settings.php"); + include(__DIR__ . "/settings.php"); } else { # parse and verify settings @@ -61,9 +61,9 @@
subnetId.".php")) { $Result->show("danger", "Invalid request", true); } + if(!file_exists(__DIR__ . "/".$GET->subnetId.".php")) { $Result->show("danger", "Invalid request", true); } elseif (!in_array($GET->subnetId, $tabs)) { $Result->show("danger", "Invalid request", true); } - else { include(dirname(__FILE__) . "/".$GET->subnetId.".php"); } + else { include(__DIR__ . "/".$GET->subnetId.".php"); } ?>
check_module_permissions ("dhcp", User::ACCESS_R, true, false); # print leases -include(dirname(__FILE__)."/../../tools/dhcp/leases.php"); \ No newline at end of file +include(__DIR__."/../../tools/dhcp/leases.php"); \ No newline at end of file diff --git a/app/admin/dhcp/reservations.php b/public/app/admin/dhcp/reservations.php similarity index 73% rename from app/admin/dhcp/reservations.php rename to public/app/admin/dhcp/reservations.php index 2ad5af468..6de6fc463 100644 --- a/app/admin/dhcp/reservations.php +++ b/public/app/admin/dhcp/reservations.php @@ -6,4 +6,4 @@ $User->check_module_permissions ("dhcp", User::ACCESS_R, true, false); # print reservations -include(dirname(__FILE__)."/../../tools/dhcp/reservations.php"); \ No newline at end of file +include(__DIR__."/../../tools/dhcp/reservations.php"); \ No newline at end of file diff --git a/app/admin/dhcp/settings.php b/public/app/admin/dhcp/settings.php similarity index 100% rename from app/admin/dhcp/settings.php rename to public/app/admin/dhcp/settings.php diff --git a/app/admin/dhcp/subnets.php b/public/app/admin/dhcp/subnets.php similarity index 81% rename from app/admin/dhcp/subnets.php rename to public/app/admin/dhcp/subnets.php index 346b13b6c..96c06b73b 100644 --- a/app/admin/dhcp/subnets.php +++ b/public/app/admin/dhcp/subnets.php @@ -10,4 +10,4 @@ $User->check_module_permissions ("dhcp", User::ACCESS_R, true, false); # print subnets -include(dirname(__FILE__)."/../../tools/dhcp/subnets.php"); \ No newline at end of file +include(__DIR__."/../../tools/dhcp/subnets.php"); \ No newline at end of file diff --git a/app/admin/filter-fields/filter-result.php b/public/app/admin/filter-fields/filter-result.php similarity index 81% rename from app/admin/filter-fields/filter-result.php rename to public/app/admin/filter-fields/filter-result.php index 7808d96c4..26aaa5369 100755 --- a/app/admin/filter-fields/filter-result.php +++ b/public/app/admin/filter-fields/filter-result.php @@ -6,7 +6,7 @@ /* functions */ -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize user object $Database = new Database_PDO; @@ -23,8 +23,8 @@ $User->check_maintaneance_mode (); # set fields to update -$values = array("id"=>1, - "IPfilter"=>implode(';', $POST->as_array())); +$values = ["id"=>1, + "IPfilter"=>implode(';', $POST->as_array())]; # update if(!$Admin->object_modify("settings", "edit", "id", $values)) { diff --git a/app/admin/filter-fields/index.php b/public/app/admin/filter-fields/index.php similarity index 97% rename from app/admin/filter-fields/index.php rename to public/app/admin/filter-fields/index.php index e4bbefd9f..2c213f957 100755 --- a/app/admin/filter-fields/index.php +++ b/public/app/admin/filter-fields/index.php @@ -58,7 +58,7 @@ print '
'. ucfirst($field_print) .''. ucfirst((string) $field_print) .'
$l[real_name]"._(ucwords($l['caction'])).""._(ucwords((string) $l['caction'])).""._(ucwords("$l[cresult]"))."$l[cdate]

".$l['cdiff']."

$l[real_name]"._(ucwords($l['caction'])).""._(ucwords((string) $l['caction'])).""._(ucwords("$l[cresult]"))."$l[cdate]

$l[cdiff]

"; diff --git a/app/subnets/addresses/address-details/address-details.php b/public/app/subnets/addresses/address-details/address-details.php similarity index 96% rename from app/subnets/addresses/address-details/address-details.php rename to public/app/subnets/addresses/address-details/address-details.php index cc343b67a..0e0ccea40 100644 --- a/app/subnets/addresses/address-details/address-details.php +++ b/public/app/subnets/addresses/address-details/address-details.php @@ -15,7 +15,7 @@ # check if it exists, otherwise print error if(sizeof($address)>1) { - $address['description'] = str_replace("\n", "
", $address['description']); + $address['description'] = str_replace("\n", "
", (string) $address['description']); print "
"; print ""; @@ -121,7 +121,7 @@ print ""; print " "; if($customer!==false) - print " "; + print " "; else print " "; print ""; @@ -192,7 +192,7 @@ # last edited print ""; print " "; - if(strlen($address['editDate'])>1) { + if(strlen((string) $address['editDate'])>1) { print " "; } else { print " "; @@ -205,7 +205,7 @@ print ""; # calculate - $tDiff = time() - strtotime($address['lastSeen']); + $tDiff = time() - strtotime((string) $address['lastSeen']); if($address['excludePing']==1) { $seen_status = ""; $seen_text = ""; } elseif($address['lastSeen'] == "0000-00-00 00:00:00") { $seen_status = "neutral"; $seen_text = _("Device is offline")."
"._("Last seen").": "._("Never");} elseif($address['lastSeen'] == "1970-01-01 00:00:01") { $seen_status = "neutral"; $seen_text = _("Device is offline")."
"._("Last seen").": "._("Never");} @@ -251,7 +251,7 @@ foreach($custom_fields as $key=>$field) { if(!is_blank($address[$key])) { - $address[$key] = str_replace(array("\n", "\r\n"), "
",$address[$key]); + $address[$key] = str_replace(["\n", "\r\n"], "
",(string) $address[$key]); print "
"; print " "; print " @@ -310,8 +310,8 @@ function validate_mac (ip, mac, sectionId, vlanId, id) { print ' '. "\n"; print ' '. "\n"; @@ -404,7 +404,7 @@ function validate_mac (ip, mac, sectionId, vlanId, id) { } //search also for CNAME records - $dns_cname_unique = array(); + $dns_cname_unique = []; $dns_records_cname = $PowerDNS->seach_aliases ($r->name); if(is_array($dns_records_cname)) { foreach ($dns_records_cname as $cn) { @@ -509,7 +509,7 @@ function validate_mac (ip, mac, sectionId, vlanId, id) { foreach($devices as $device) { $device = (array) $device; //check if permitted in this section! - $sections=pf_explode(";", $device['sections']); + $sections=explode(";", (string) $device['sections']); if(in_array($subnet['sectionId'], $sections)) { //if same if($device['id'] == $address['switch']) { print ''. "\n"; } diff --git a/app/subnets/addresses/address-resolve.php b/public/app/subnets/addresses/address-resolve.php similarity index 88% rename from app/subnets/addresses/address-resolve.php rename to public/app/subnets/addresses/address-resolve.php index 347887321..059540a0c 100755 --- a/app/subnets/addresses/address-resolve.php +++ b/public/app/subnets/addresses/address-resolve.php @@ -5,7 +5,7 @@ */ # include required scripts -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize required objects $Database = new Database_PDO; diff --git a/app/subnets/addresses/export-field-select.php b/public/app/subnets/addresses/export-field-select.php similarity index 96% rename from app/subnets/addresses/export-field-select.php rename to public/app/subnets/addresses/export-field-select.php index 61bdddd54..efe2f1ab1 100644 --- a/app/subnets/addresses/export-field-select.php +++ b/public/app/subnets/addresses/export-field-select.php @@ -5,7 +5,7 @@ */ # include required scripts -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize required objects $Database = new Database_PDO; @@ -135,7 +135,7 @@ foreach($custom_fields as $myField) { //change spaces to ___ - $myField['nameTemp'] = str_replace(" ", "___", $myField['name']); + $myField['nameTemp'] = str_replace(" ", "___", (string) $myField['name']); print " "; print " "; diff --git a/app/subnets/addresses/export-subnet.php b/public/app/subnets/addresses/export-subnet.php similarity index 94% rename from app/subnets/addresses/export-subnet.php rename to public/app/subnets/addresses/export-subnet.php index 9c714f306..1ba6b7de6 100755 --- a/app/subnets/addresses/export-subnet.php +++ b/public/app/subnets/addresses/export-subnet.php @@ -5,13 +5,12 @@ *********************************/ # include required scripts -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; +require_once __DIR__ . '/../../../../functions/PEAR/Spreadsheet/Excel/Writer.php'; # Don't corrupt output with php errors! disable_php_errors(); -require( dirname(__FILE__) . '/../../../functions/PEAR/Spreadsheet/Excel/Writer.php'); - # initialize required objects $Database = new Database_PDO; $Result = new Result; @@ -92,7 +91,7 @@ // Create a worksheet -$worksheet_name = strlen($subnet['description']) > 30 ? substr($subnet['description'],0,27).'...' : $subnet['description']; +$worksheet_name = strlen((string) $subnet['description']) > 30 ? substr((string) $subnet['description'],0,27).'...' : $subnet['description']; $worksheet =& $workbook->addWorksheet($worksheet_name); $worksheet->setInputEncoding("utf-8"); @@ -173,7 +172,7 @@ if(sizeof($custom_fields) > 0) { foreach($custom_fields as $myField) { //set temp name - replace space with three ___ - $myField['nameTemp'] = str_replace(" ", "___", $myField['name']); + $myField['nameTemp'] = str_replace(" ", "___", (string) $myField['name']); if( (isset($GET->{$myField['nameTemp']})) && ($GET->{$myField['nameTemp']} == "on") ) { $worksheet->write($lineCount, $rowCount, $myField['name'] ,$format_title); @@ -190,7 +189,7 @@ $ip_types = $Addresses->addresses_types_fetch(); //fetch devices and reorder $devices = $Tools->fetch_all_objects("devices", "hostname"); -$devices_indexed = array(); +$devices_indexed = []; if ($devices!==false) { foreach($devices as $d) { $devices_indexed[$d->id] = (object) $d; @@ -202,7 +201,7 @@ //fetch locations and reorder $locations = $Tools->fetch_all_objects("locations", "id"); -$locations_indexed = array(); +$locations_indexed = []; if ($locations!==false) { foreach($locations as $d) { $locations_indexed[$d->id] = (object) $d; @@ -278,7 +277,7 @@ if(sizeof($custom_fields) > 0) { foreach($custom_fields as $myField) { //set temp name - replace space with three ___ - $myField['nameTemp'] = str_replace(" ", "___", $myField['name']); + $myField['nameTemp'] = str_replace(" ", "___", (string) $myField['name']); if( (isset($GET->{$myField['nameTemp']})) && ($GET->{$myField['nameTemp']} == "on") ) { $worksheet->write($lineCount, $rowCount, $ip[$myField['name']]); diff --git a/app/subnets/addresses/index.php b/public/app/subnets/addresses/index.php similarity index 100% rename from app/subnets/addresses/index.php rename to public/app/subnets/addresses/index.php diff --git a/app/subnets/addresses/mail-notify-check.php b/public/app/subnets/addresses/mail-notify-check.php similarity index 88% rename from app/subnets/addresses/mail-notify-check.php rename to public/app/subnets/addresses/mail-notify-check.php index 79f5c6749..6554f26b2 100644 --- a/app/subnets/addresses/mail-notify-check.php +++ b/public/app/subnets/addresses/mail-notify-check.php @@ -5,7 +5,7 @@ *************************************************/ # include required scripts -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize required objects $Database = new Database_PDO; @@ -19,7 +19,7 @@ $User->check_user_session(); # verify each recipient -foreach (pf_explode(",", $POST->recipients) as $rec) { +foreach (explode(",", (string) $POST->recipients) as $rec) { if(!filter_var(trim($rec), FILTER_VALIDATE_EMAIL)) { $Result->show("danger", _("Invalid email address")." - ".$rec, true); } @@ -39,13 +39,13 @@ // set html content $content[] = "
"._('Customer')."$customer->title $customer->title "._("None")."
"._('Last edited')."$address[editDate]"._('Never')."
" . $Tools->print_custom_field_name($key) . ""; @@ -346,7 +346,7 @@ print " "; print " "; if(isset($zone)) { - print " "; + print " "; } print " "; //share diff --git a/app/subnets/addresses/address-modify-submit.php b/public/app/subnets/addresses/address-modify-submit.php similarity index 96% rename from app/subnets/addresses/address-modify-submit.php rename to public/app/subnets/addresses/address-modify-submit.php index efad3f096..2b69058a2 100644 --- a/app/subnets/addresses/address-modify-submit.php +++ b/public/app/subnets/addresses/address-modify-submit.php @@ -6,7 +6,7 @@ *************************************************/ # include required scripts -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize required objects $Database = new Database_PDO; @@ -58,15 +58,15 @@ if($User->settings->enableLocations=="0") { unset($required_ip_fields['location']); } // set default array - $required_field_errors = array(); + $required_field_errors = []; // Check that all required fields are present foreach ($required_ip_fields as $required_field) { if (!isset($POST->{$required_field}) || is_blank($POST->{$required_field})) { - $required_field_errors[] = ucwords($required_field)." "._("is required"); + $required_field_errors[] = ucwords((string) $required_field)." "._("is required"); } } // Check that certain required fields are not zero - foreach (array("customer_id","switch","location") as $drop_down_field) { + foreach (["customer_id","switch","location"] as $drop_down_field) { if (in_array($drop_down_field,$required_ip_fields)) { if ($POST->{$drop_down_field} == "0") { $required_field_errors[] = ucwords($drop_down_field)." "._("is required"); @@ -82,7 +82,7 @@ # remove all spaces in hostname -if (!is_blank($POST->hostname)) { $POST->hostname = str_replace(" ", "", $POST->hostname); } +if (!is_blank($POST->hostname)) { $POST->hostname = str_replace(" ", "", (string) $POST->hostname); } # required fields isset($POST->action) ?: $Result->show("danger", _("Missing required fields"). " action", true); @@ -141,16 +141,16 @@ $subnet_is_multicast = $Subnets->is_multicast ($subnet['subnet']); # are we adding/editing range? -if (!is_blank(strstr($POST->ip_addr,"-"))) { +if (!is_blank(strstr((string) $POST->ip_addr,"-"))) { # set flag for updating $POST->type = "series"; # remove possible spaces - $POST->ip_addr = str_replace(" ", "", $POST->ip_addr); + $POST->ip_addr = str_replace(" ", "", (string) $POST->ip_addr); # get start and stop of range - $range = pf_explode("-", $POST->ip_addr); + $range = explode("-", $POST->ip_addr); $POST->start = $range[0]; $POST->stop = $range[1]; @@ -180,7 +180,7 @@ # check if delete is confirmed if ($action=="delete" && !isset($POST->deleteconfirm)) { - $range = str_replace("-", " - ", $POST->ip_addr); + $range = str_replace("-", " - ", (string) $POST->ip_addr); # for ajax to prevent reload print "
alert alert-danger
"; # result @@ -289,7 +289,7 @@ # validate and normalize MAC address if($action!=="delete") { if(!is_blank($POST->mac)) { - $POST->mac = trim($POST->mac); + $POST->mac = trim((string) $POST->mac); if($User->validate_mac ($POST->mac)===false) { $Result->show("danger", _('Invalid MAC address')."!", true); } diff --git a/app/subnets/addresses/address-modify.php b/public/app/subnets/addresses/address-modify.php similarity index 97% rename from app/subnets/addresses/address-modify.php rename to public/app/subnets/addresses/address-modify.php index 6ba35a254..ee1e43b98 100644 --- a/app/subnets/addresses/address-modify.php +++ b/public/app/subnets/addresses/address-modify.php @@ -8,7 +8,7 @@ # include required scripts -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize required objects $Database = new Database_PDO; @@ -38,7 +38,7 @@ # fetch subnet $subnet = (array) $Subnets->fetch_subnet(null, $subnetId); -if (strpos($_SERVER['HTTP_REFERER'], "verify-database")==0) +if (strpos((string) $_SERVER['HTTP_REFERER'], "verify-database")==0) sizeof($subnet)>0 ?: $Result->show("danger", _("Invalid subnet"), true, true); # set and check permissions @@ -218,7 +218,7 @@ function validate_mac (ip, mac, sectionId, vlanId, id) { "; } + if (strpos((string) $_SERVER['HTTP_REFERER'], "verify-database")!=0) { print ""; } ?>
$myField[name]
"; $content[] = ""; - foreach(pf_explode("\r\n", $POST->content) as $c) { + foreach(explode("\r\n", (string) $POST->content) as $c) { $content[] = ""; } $content[] = ""; //set al content $content_plain[] = "$subject"."\r\n------------------------------\r\n"; - $content_plain[] = str_replace("·", "\t - ", $POST->content); + $content_plain[] = str_replace("·", "\t - ", (string) $POST->content); $content_plain[] = "\r\n\r\n"._("Sent by user")." ".$User->user->real_name." at ".date('Y/m/d H:i'); $content[] = "
$User->mail_font_style$subject
$User->mail_font_style $c
$User->mail_font_style_light Sent by user ".$User->user->real_name." at ".date('Y/m/d H:i')."
"; @@ -54,7 +54,7 @@ $content_plain = implode("\r\n",$content_plain); $phpipam_mail->Php_mailer->setFrom($mail_settings->mAdminMail, $mail_settings->mAdminName); - foreach(pf_explode(",", $POST->recipients) as $r) { + foreach(explode(",", (string) $POST->recipients) as $r) { $phpipam_mail->Php_mailer->addAddress(addslashes(trim($r))); } $phpipam_mail->Php_mailer->Subject = $subject; diff --git a/app/subnets/addresses/mail-notify.php b/public/app/subnets/addresses/mail-notify.php similarity index 95% rename from app/subnets/addresses/mail-notify.php rename to public/app/subnets/addresses/mail-notify.php index 3e0e7e34d..f20251a53 100644 --- a/app/subnets/addresses/mail-notify.php +++ b/public/app/subnets/addresses/mail-notify.php @@ -5,7 +5,7 @@ ********************************************/ # include required scripts -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize required objects $Database = new Database_PDO; @@ -71,7 +71,7 @@ # Nameserver sets if ( !empty( $subnet['nameserverId'] ) ) { - $nslist = str_replace(";", ", ", $nameservers['namesrv1']); + $nslist = str_replace(";", ", ", (string) $nameservers['namesrv1']); $content[] = "• "._('Nameservers').": \t $nslist ({$nameservers['name']})"; } @@ -93,7 +93,7 @@ if(sizeof($custom_fields) > 0) { foreach($custom_fields as $custom_field) { if(!empty($address[$custom_field['name']])) { - $content[] = "• ". _($custom_field['name']).":\t".$address[$custom_field['name']]; + $content[] = "• ". _((string) $custom_field['name']).":\t".$address[$custom_field['name']]; } } } diff --git a/app/subnets/addresses/move-address.php b/public/app/subnets/addresses/move-address.php similarity index 97% rename from app/subnets/addresses/move-address.php rename to public/app/subnets/addresses/move-address.php index 5bf272055..569a6216c 100644 --- a/app/subnets/addresses/move-address.php +++ b/public/app/subnets/addresses/move-address.php @@ -8,7 +8,7 @@ # include required scripts -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize required objects $Database = new Database_PDO; diff --git a/app/subnets/addresses/ping-address.php b/public/app/subnets/addresses/ping-address.php similarity index 97% rename from app/subnets/addresses/ping-address.php rename to public/app/subnets/addresses/ping-address.php index db84331d5..cea190861 100644 --- a/app/subnets/addresses/ping-address.php +++ b/public/app/subnets/addresses/ping-address.php @@ -5,7 +5,7 @@ */ # include required scripts -require_once( dirname(__FILE__) . '/../../../functions/functions.php' ); +require_once __DIR__ . '/../../../../functions/functions.php'; # initialize required objects $Database = new Database_PDO; diff --git a/app/subnets/addresses/print-address-table.php b/public/app/subnets/addresses/print-address-table.php similarity index 96% rename from app/subnets/addresses/print-address-table.php rename to public/app/subnets/addresses/print-address-table.php index e028bf351..0f59fc1f3 100644 --- a/app/subnets/addresses/print-address-table.php +++ b/public/app/subnets/addresses/print-address-table.php @@ -51,7 +51,7 @@ function unset_array_value(&$array, $value) { $custom_fields = $Tools->fetch_custom_fields ('ipaddresses'); # set hidden custom fields $hidden_cfields = db_json_decode($User->settings->hiddenCustomFields, true) ? : ['ipaddresses'=>null]; -$hidden_cfields = is_array($hidden_cfields['ipaddresses']) ? $hidden_cfields['ipaddresses'] : array(); +$hidden_cfields = is_array($hidden_cfields['ipaddresses']) ? $hidden_cfields['ipaddresses'] : []; # set selected address fields array $selected_ip_fields = $Tools->explode_filtered(";", $User->settings->IPfilter); //format to array @@ -63,11 +63,12 @@ function unset_array_value(&$array, $value) { if($User->settings->enableCustomers != 1) { unset_array_value($selected_ip_fields, 'customer_id'); } /* Addresses and fields manupulations */ +if (!isset($addresses) || !is_array($addresses)) + $addresses = []; # save for visual display ! $addresses_visual = $addresses; # new compress functions -$addresses=[]; $Addresses->addresses_types_fetch(); foreach($Addresses->address_types as $t) { if($t['compress']=="Yes" && $User->user->compressOverride!="Uncompress") { @@ -119,7 +120,7 @@ function unset_array_value(&$array, $value) { } # set ping statuses for warning and offline -$statuses = pf_explode(";", $User->settings->pingStatus); +$statuses = explode(";", (string) $User->settings->pingStatus); # Set $zone if(in_array('firewallAddressObject', $selected_ip_fields)) { @@ -264,7 +265,7 @@ function unset_array_value(&$array, $value) { # status icon if($subnet['pingSubnet']=="1") { //calculate - $tDiff = !is_null($addresses[$n]->lastSeen)>0 ? time() - strtotime($addresses[$n]->lastSeen) : time(); + $tDiff = !is_null($addresses[$n]->lastSeen)>0 ? time() - strtotime((string) $addresses[$n]->lastSeen) : time(); if($addresses[$n]->excludePing=="1" ) { $hStatus = "padded"; $hTooltip = ""; } elseif(is_null($addresses[$n]->lastSeen)) { $hStatus = "neutral"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address was never online")."'"; } elseif($addresses[$n]->lastSeen == "0000-00-00 00:00:00") { $hStatus = "neutral"; $hTooltip = "rel='tooltip' data-container='body' data-html='true' data-placement='left' title='"._("Address is offline")."
"._("Last seen").": "._("Never")."'";} @@ -295,7 +296,7 @@ function unset_array_value(&$array, $value) { $Addresses->ptr_link($addresses[$n]->id, $ptr->id); } else { $Addresses->ptr_link($addresses[$n]->id, 0); } } - unset($dns_records); + $dns_records = []; if (is_array($records) || $ptr!==false) { $dns_records[] = "
"; $dns_records[] = ""; // if none ignore - $dns_records = sizeof($dns_records)==3 ? "" : implode(" ", $dns_records); + $dns_records_txt = sizeof($dns_records)==3 ? "" : implode(" ", $dns_records); } else { - $dns_records = ""; + $dns_records_txt = ""; } // search for IP records $records2 = $PowerDNS->search_records ("content", $addresses[$n]->ip, 'content', true); - unset($dns_records2); + $dns_records2 = []; if (is_array($records2)) { - $dns_cname_unique = array(); // unique CNAME records to prevent multiple - unset($cname); + $dns_cname_unique = []; // unique CNAME records to prevent multiple + $cname = []; $dns_records2[] = "
"; $dns_records2[] = ""; // if none ignore - $dns_records2 = sizeof($dns_records2)==3 ? "" : implode(" ", $dns_records2); + $dns_records2_txt = sizeof($dns_records2)==3 ? "" : implode(" ", $dns_records2); } else { - $dns_records2 = ""; + $dns_records2_txt = ""; } } // disabled else { - $dns_records = ""; - $dns_records2 = ""; + $dns_records_txt = ""; + $dns_records2_txt = ""; $button = ""; } // add button @@ -378,7 +379,7 @@ function unset_array_value(&$array, $value) { $Addresses->print_nat_link($all_nats, $all_nats_per_object, $subnet, $addresses[$n]); } - print $dns_records2.""; + print $dns_records2_txt.""; # resolve dns name $resolve = $DNS->resolve_address($addresses[$n]->ip_addr, $addresses[$n]->hostname, false, $subnet['nameserverId']); @@ -387,7 +388,7 @@ function unset_array_value(&$array, $value) { $Addresses->update_address_hostname ($addresses[$n]->ip_addr, $addresses[$n]->id, $resolve['name']); $addresses[$n]->hostname = $resolve['name']; } - { print "$resolve[name] $button $dns_records"; } + { print "$resolve[name] $button $dns_records_txt"; } # print firewall address object - mandatory if enabled if($zone) { @@ -417,27 +418,27 @@ function unset_array_value(&$array, $value) { $minfo = ""; // formulate object if ($duplicates!==false) { - $mobjects = array(); + $mobjects = []; $mobjects[] = "

Duplicated addresses:

"; $mobjects[] = "