diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..611bf56 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,23 @@ +# Cacti reportit Plugin AI Instructions + +## Project Overview +This is a Cacti plugin. It integrates with the Cacti monitoring platform via the plugin hook architecture. + +## Technology Stack +- PHP 7.4+ (targeting Cacti 1.2.x compatibility) +- MySQL/MariaDB via Cacti's DB abstraction layer +- PSR-12 coding standards + +## Key Rules +- Use prepared statements (db_execute_prepared, db_fetch_row_prepared, etc.) for ALL queries with variables +- Use get_request_var() / get_filter_request_var() for ALL user input, never raw $_REQUEST/$_GET/$_POST +- Use html_escape() / htmlspecialchars() for ALL output of DB/user values in HTML context +- Use cacti_escapeshellarg() for ALL shell command arguments +- No PHP 8.0+ features (str_contains, match, union types, named args) - target PHP 7.4 +- Use ?? and ??= operators (PHP 7.4) instead of isset() ternary patterns +- All unserialize() calls must use allowed_classes => false + +## Testing +- Tests in tests/ directory +- Use Pest PHP or PHPUnit +- php -l lint check required before commit diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml new file mode 100644 index 0000000..53058e1 --- /dev/null +++ b/.github/workflows/plugin-ci-workflow.yml @@ -0,0 +1,225 @@ +# +-------------------------------------------------------------------------+ +# | Copyright (C) 2004-2026 The Cacti Group | +# | | +# | This program is free software; you can redistribute it and/or | +# | modify it under the terms of the GNU General Public License | +# | as published by the Free Software Foundation; either version 2 | +# | of the License, or (at your option) any later version. | +# | | +# | This program is distributed in the hope that it will be useful, | +# | but WITHOUT ANY WARRANTY; without even the implied warranty of | +# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | +# | GNU General Public License for more details. | +# +-------------------------------------------------------------------------+ +# | Cacti: The Complete RRDtool-based Graphing Solution | +# +-------------------------------------------------------------------------+ +# | This code is designed, written, and maintained by the Cacti Group. See | +# | about.php and/or the AUTHORS file for specific developer information. | +# +-------------------------------------------------------------------------+ +# | http://www.cacti.net/ | +# +-------------------------------------------------------------------------+ + +name: Plugin Integration Tests + +on: + push: + branches: + - main + - develop + pull_request: + branches: + - main + - develop + +jobs: + integration-test: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + php: ['8.1', '8.2', '8.3', '8.4'] + os: [ubuntu-latest] + + services: + mariadb: + image: mariadb:10.6 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + name: PHP ${{ matrix.php }} Integration Test on ${{ matrix.os }} + + steps: + - name: Checkout Cacti + uses: actions/checkout@v4 + with: + repository: Cacti/cacti + path: cacti + + - name: Checkout reportit Plugin + uses: actions/checkout@v4 + with: + path: cacti/plugins/reportit + + - name: Install PHP ${{ matrix.php }} + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: intl, mysql, gd, ldap, gmp, xml, curl, json, mbstring + ini-values: "post_max_size=256M, max_execution_time=60, date.timezone=America/New_York" + + - name: Check PHP version + run: php -v + + - name: Run apt-get update + run: sudo apt-get update + + - name: Install System Dependencies + run: sudo apt-get install -y apache2 snmp snmpd rrdtool fping + + - name: Start SNMPD Agent and Test + run: | + sudo systemctl start snmpd + sudo snmpwalk -c public -v2c -On localhost .1.3.6.1.2.1.1 + + - name: Setup Permissions + run: | + sudo chown -R www-data:runner ${{ github.workspace }}/cacti + sudo find ${{ github.workspace }}/cacti -type d -exec chmod 775 {} \; + sudo find ${{ github.workspace }}/cacti -type f -exec chmod 664 {} \; + sudo chmod +x ${{ github.workspace }}/cacti/cmd.php + sudo chmod +x ${{ github.workspace }}/cacti/poller.php + + - name: Create MySQL Config + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + cat ~/.my.cnf + + - name: Initialize Cacti Database + env: + MYSQL_AUTH_USR: '--defaults-file=~/.my.cnf' + run: | + mysql $MYSQL_AUTH_USR -e 'CREATE DATABASE IF NOT EXISTS cacti;' + mysql $MYSQL_AUTH_USR -e "CREATE USER IF NOT EXISTS 'cactiuser'@'localhost' IDENTIFIED BY 'cactiuser';" + mysql $MYSQL_AUTH_USR -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "FLUSH PRIVILEGES;" + mysql $MYSQL_AUTH_USR cacti < ${{ github.workspace }}/cacti/cacti.sql + mysql $MYSQL_AUTH_USR -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '/usr/bin/php')" cacti + + - name: Validate composer files + run: | + cd ${{ github.workspace }}/cacti + if [ -f composer.json ]; then + composer validate --strict || true + fi + + - name: Install Composer Dependencies + run: | + cd ${{ github.workspace }}/cacti + if [ -f composer.json ]; then + sudo composer install --prefer-dist --no-progress + fi + + - name: Create Cacti config.php + run: | + cat ${{ github.workspace }}/cacti/include/config.php.dist | \ + sed -r "s/localhost/127.0.0.1/g" | \ + sed -r "s/'cacti'/'cacti'/g" | \ + sed -r "s/'cactiuser'/'cactiuser'/g" | \ + sed -r "s/'cactiuser'/'cactiuser'/g" > ${{ github.workspace }}/cacti/include/config.php + sudo chmod 664 ${{ github.workspace }}/cacti/include/config.php + + - name: Configure Apache + run: | + cat << 'EOF' | sed 's#GITHUB_WORKSPACE#${{ github.workspace }}#g' > /tmp/cacti.conf + + ServerAdmin webmaster@localhost + DocumentRoot GITHUB_WORKSPACE/cacti + + + Options Indexes FollowSymLinks + AllowOverride All + Require all granted + + + ErrorLog ${APACHE_LOG_DIR}/error.log + CustomLog ${APACHE_LOG_DIR}/access.log combined + + EOF + sudo cp /tmp/cacti.conf /etc/apache2/sites-available/000-default.conf + sudo systemctl restart apache2 + + - name: Install Cacti via CLI + run: | + cd ${{ github.workspace }}/cacti + sudo php cli/install_cacti.php --accept-eula --install --force + + - name: Install reportit Plugin + run: | + cd ${{ github.workspace }}/cacti + sudo php cli/plugin_manage.php --plugin=reportit --install --enable + +# - name: import reportit Plugin Sample Data +# run: | +# cd ${{ github.workspace }}/cacti/plugins/reportit +# sudo php cli_import.php --filename=.github/workflows/reportit_sample_data.xml +# if [ $? -ne 0 ]; then +# echo "Failed to import Thold sample data" +# exit 1 +# fi + + - name: Check PHP Syntax for Plugin + run: | + cd ${{ github.workspace }}/cacti/plugins/reportit + if find . -name '*.php' -exec php -l {} 2>&1 \; | grep -iv 'no syntax errors detected'; then + echo "Syntax errors found!" + exit 1 + fi + + - name: Remove the plugins directory exclusion from the .phpstan.neon + run: sed '/plugins/d' -i .phpstan.neon + working-directory: ${{ github.workspace }}/cacti + + - name: Mark composer scripts executable + run: sudo chmod +x ${{ github.workspace }}/cacti/include/vendor/bin/* + + - name: Run Linter on base code + run: composer run-script lint ${{ github.workspace }}/cacti/plugins/reportit + working-directory: ${{ github.workspace }}/cacti + + - name: Checking coding standards on base code + run: composer run-script phpcsfixer ${{ github.workspace }}/cacti/plugins/reportit + working-directory: ${{ github.workspace }}/cacti + +# - name: Run PHPStan at Level 6 on base code outside of Composer due to technical issues +# run: ./include/vendor/bin/phpstan analyze --level 6 ${{ github.workspace }}/cacti/plugins/reportit +# working-directory: ${{ github.workspace }}/cacti + + - name: Run Cacti Poller + run: | + cd ${{ github.workspace }}/cacti + sudo php poller.php --poller=1 --force --debug + if ! grep -q "SYSTEM STATS" log/cacti.log; then + echo "Cacti poller did not finish successfully" + cat log/cacti.log + exit 1 + fi + + - name: View Cacti Logs + if: always() + run: | + if [ -f ${{ github.workspace }}/cacti/log/cacti.log ]; then + echo "=== Cacti Log ===" + sudo cat ${{ github.workspace }}/cacti/log/cacti.log + fi diff --git a/include/global_arrays.php b/include/global_arrays.php index 878b3fa..b1d1d71 100644 --- a/include/global_arrays.php +++ b/include/global_arrays.php @@ -22,32 +22,32 @@ +-------------------------------------------------------------------------+ */ -$report_template_actions = array( - 'templates' => array( +$report_template_actions = [ + 'templates' => [ 1 => __('Delete', 'reportit'), 2 => __('Duplicate', 'reportit'), 3 => __('Lock', 'reportit'), 4 => __('Unlock', 'reportit'), 5 => __('Export', 'reportit'), - ), - 'data_templates' => array( + ], + 'data_templates' => [ 1 => __('Delete', 'reportit'), - ), - 'groups' => array( + ], + 'groups' => [ 1 => __('Delete', 'reportit') - ), - 'variables' => array( + ], + 'variables' => [ 1 => __('Delete', 'reportit'), 2 => __('Duplicate', 'reportit'), - ), - 'measurands' => array( + ], + 'measurands' => [ 1 => __('Delete', 'reportit'), 2 => __('Duplicate', 'reportit'), - ) -); + ] +]; -$report_template_display_text = array( - 'variables' => array( +$report_template_display_text = [ + 'variables' => [ __('Name', 'reportit'), __('Internal Name', 'reportit'), __('Maximum', 'reportit'), @@ -56,8 +56,8 @@ __('Stepping', 'reportit'), __('Input Type', 'reportit'), __('Options', 'reportit'), - ), - 'measurands' => array( + ], + 'measurands' => [ __('ID', 'reportit'), __('Abbreviation', 'reportit'), __('Group', 'reportit'), @@ -66,28 +66,27 @@ __('Visible', 'reportit'), __('Separate', 'reportit'), __('Calculation Formula', 'reportit') - ), - 'groups' => array( + ], + 'groups' => [ __('ID', 'reportit'), __('Name', 'reportit'), __('Generic ID', 'reportit'), __('Elements', 'reportit'), __('Metrics', 'reportit'), __('Associated Data Templates', 'reportit'), - ) -); + ] +]; -$report_template_tabs = array( +$report_template_tabs = [ 'general' => __esc('General', 'reportit'), 'data_templates' => __esc('Data Templates', 'reportit'), 'groups' => __esc('Groups', 'reportit'), 'measurands' => __esc('Metrics', 'reportit'), 'variables' => __esc('Variables', 'reportit'), -); +]; - -#TODO :remove $report_time_frames -$report_time_frames = array( +// TODO :remove $report_time_frames +$report_time_frames = [ __('Today'), __('Last 1 Day'), __('Last 2 Days'), @@ -111,24 +110,23 @@ __('Current Year'), __('Last Year'), __('Last 2 Years') -); - +]; -$report_schedule_frequency = array( +$report_schedule_frequency = [ 'daily' => __('Daily', 'reportit'), 'weekly' => __('Weekly', 'reportit'), 'monthly' => __('Monthly', 'reportit'), 'quarterly' => __('Quarterly', 'reportit'), 'yearly' => __('Yearly', 'reportit'), -); +]; -$variable_input_types = array( +$variable_input_types = [ 1 => __('Dropdown', 'reportit'), 2 => __('Input field', 'reportit') -); +]; -/* - Begin measurands - */ -$measurand_type_specifier = array( //TODO update script: increase every value by one! +// - Begin measurands - +$measurand_type_specifier = [ // TODO update script: increase every value by one! 0 => __('None', 'reportit'), 1 => __('Binary', 'reportit'), 2 => __('Floating point', 'reportit'), @@ -138,391 +136,391 @@ 6 => __('Hexadecimal (upper-case)', 'reportit'), 7 => __('Octal', 'reportit'), 8 => __('Scientific Notation', 'reportit') -); +]; -$measurand_precision = array( - 0 => __('None', 'reportit'), - 1 => 1, - 2 => 2, - 3 => 3, - 4 => 4, - 5 => 5, - 6 => 6, - 7 => 7, - 8 => 8, - 9 => 9, +$measurand_precision = [ + 0 => __('None', 'reportit'), + 1 => 1, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 5, + 6 => 6, + 7 => 7, + 8 => 8, + 9 => 9, -1 => __('Unchanged', 'reportit') -); +]; -$measurand_rounding = array( +$measurand_rounding = [ 0 => __('off', 'reportit'), 1 => __('Binary SI-Prefixes (Base 1024)', 'reportit'), 2 => __('Decimal SI-Prefixes (Base 1000)', 'reportit') -); +]; -$measurand_ops_and_opds = array( - 0 => array( - 'f_avg' => array( +$measurand_ops_and_opds = [ + 0 => [ + 'f_avg' => [ 'title' => __('f_avg - Arithmetic Average', 'reportit'), 'description' => __('Returns the average value of all measured values per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_avg', 'examples' => 'f_avg*8' - ), - 'f_max' => array( + ], + 'f_max' => [ 'title' => __('f_max - Maximum Value', 'reportit'), 'description' => __('Returns the highest measured value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_max', 'examples' => '(f_max-f_min)*8' - ), - 'f_min' => array( + ], + 'f_min' => [ 'title' => __('f_min - Minimum Value', 'reportit'), 'description' => __('Returns the lowest measured value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_min', 'examples' => 'f_min*8' - ), - 'f_sum' => array( + ], + 'f_sum' => [ 'title' => __('f_sum - Sum', 'reportit'), 'description' => __('Returns the sum of all measured values per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_sum', 'examples' => 'f_sum*8' - ), - 'f_num' => array( + ], + 'f_num' => [ 'title' => __('f_num - Number of Values (Not NaN)', 'reportit'), 'description' => __('Returns the number of valid measured values per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'int f_num', 'examples' => 'f_num' - ), - 'f_grd' => array( + ], + 'f_grd' => [ 'title' => __('f_grd - Gradient', 'reportit'), 'description' => __('Returns the gradient of a straight line by using linear regression per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_grd', 'examples' => 'f_grd' - ), - 'f_last' => array( + ], + 'f_last' => [ 'title' => __('f_last - Last Value', 'reportit'), 'description' => __('Returns the last valid measured value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_last', 'examples' => 'f_last*16/2' - ), - 'f_1st' => array( + ], + 'f_1st' => [ 'title' => __('f_1st - First Value', 'reportit'), 'description' => __('Returns the first valid measured value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_1st', 'examples' => 'f_1st*2*(5.5-1.5)' - ), - 'f_nan' => array( + ], + 'f_nan' => [ 'title' => __('f_nan - Number of NaNs', 'reportit'), 'description' => __('Returns the number of NaNs stored per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'int f_nan', 'examples' => 'f_num+f_nan' - ), - 'f_median' => array( + ], + 'f_median' => [ 'title' => __('f_median - Median', 'reportit'), 'description' => __('Returns that value that separates the higher half from the lower half per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_median', 'examples' => 'f_median' - ), - 'f_range' => array( + ], + 'f_range' => [ 'title' => __('f_range - Range', 'reportit'), 'description' => __('Returns the difference between the largest and the smallest value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_range', 'examples' => 'f_range' - ), - 'f_iqr' => array( + ], + 'f_iqr' => [ 'title' => __('f_iqr - Interquartile Range', 'reportit'), 'description' => __('Returns the distance of the middle50% around the median per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_iqr', 'examples' => 'f_iqr' - ), - 'f_sd' => array( + ], + 'f_sd' => [ 'title' => __('f_sd - Standard Deviation', 'reportit'), 'description' => __('Returns the square root per data source variance', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_sd', 'examples' => 'f_sd' - ), - 'f_var' => array( + ], + 'f_var' => [ 'title' => __('f_var - Variance', 'reportit'), 'description' => __('Returns the variance per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_mode', 'examples' => 'f_var' - ), - ), - 1 => array( - 'f_xth' => array( + ], + ], + 1 => [ + 'f_xth' => [ 'title' => __('f_xth - Xth Percentile', 'reportit'), 'description' => __('Returns the xth percentitle.', 'reportit'), 'params' => __('$var: threshold in percent. Range: [0< $var ≤100]', 'reportit'), 'syntax' => 'float f_xth (float $var)', 'examples' => 'f_xth(95.7), f_xth(c1v)', 'parentheses' => true - ), - 'f_dot' => array( + ], + 'f_dot' => [ 'title' => __('f_dot - Duration Over Threshold', 'reportit'), 'description' => __('Returns the duration over a defined threshold in percent.', 'reportit'), 'params' => __('$var: threshold (absolute)', 'reportit'), 'syntax' => 'float f_dot (float $var)', 'examples' => 'f_dot(10000000), f_dot(maxValue*c1v/100)', 'parentheses' => true - ), - 'f_sot' => array( + ], + 'f_sot' => [ 'title' => __('f_sot - Sum Over Threshold', 'reportit'), 'description' => __('Returns the sum of values over a defined threshold.', 'reportit'), 'params' => __('$var: threshold (absolute)', 'reportit'), 'syntax' => 'float f_sot (float $var)', 'examples' => 'f_sot(75000000), f_sot(maxValue*c4v/100)', 'parentheses' => true - ), - 'f_floor' => array( + ], + 'f_floor' => [ 'title' => __('f_floor - Round Fractions Down', 'reportit'), 'description' => __('Returns the next lowest integer value by rounding down value if necessary.', 'reportit'), 'params' => __('$var: float', 'reportit'), 'syntax' => 'integer f_floor (float $var)', 'examples' => 'f_floor(69.19) = 69', 'parentheses' => true - ), - 'f_ceil' => array( + ], + 'f_ceil' => [ 'title' => __('f_ceil - Round Fractions Up', 'reportit'), 'description' => __('Returns the next highest integer value by rounding up value if necessary.', 'reportit'), 'params' => __('$var: float', 'reportit'), 'syntax' => 'integer f_ceil (float $var)', 'examples' => 'f_ceil(69.19) = 70', 'parentheses' => true - ), - 'f_round' => array( + ], + 'f_round' => [ 'title' => __('f_round - Round A Float', 'reportit'), 'description' => __('Returns the rounded integer value of any given float.', 'reportit'), 'params' => __('$var: float or string value', 'reportit'), 'syntax' => 'integer f_round (float $var)', 'examples' => 'f_round(69.50) = 70, f_round(69,49) = 69', 'parentheses' => true - ), - 'f_high' => array( + ], + 'f_high' => [ 'title' => __('f_high - Find Highest Value', 'reportit'), 'description' => __('Returns the highest value of a given list of parameters', 'reportit'), 'params' => __('$var1, $var2, $var3 ...: values to be compared', 'reportit'), 'syntax' => 'float f_high (float $var1, float $var2)', 'examples' => 'f_high(27,70) = 70', 'parentheses' => true - ), - 'f_low' => array( + ], + 'f_low' => [ 'title' => __('f_high - Find Lowest Value', 'reportit'), 'description' => __('Returns the lowest value of a given list of parameters', 'reportit'), 'params' => __('$var1, $var2, $var3 ...: values to be compared', 'reportit'), 'syntax' => 'float f_low (float $var1, float $var2)', 'examples' => 'f_low(27,70) = 27', 'parentheses' => true - ), - 'f_if' => array( + ], + 'f_if' => [ 'title' => __('f_if - Conditional Operation - IF-THEN-ELSE Logic', 'reportit'), 'description' => __('Returns B if A is true or C if A is false', 'reportit'), 'params' => '$A, $B, $C', 'syntax' => 'bool f_if (float $A, float $B, float $C)', 'examples' => 'f_if (0,1,2) = 2, f_if(1,1,2) = 1, f_if(f_low(0,1),f_1st, f_last) = f_last', 'parentheses' => true - ), - 'f_isNaN' => array( + ], + 'f_isNaN' => [ 'title' => __('f_isNaN - Find whether a value is not a number', 'reportit'), 'description' => __('Returns 1 (or B) if A === NaN or 0 (or C) if not. Parameters B and C are optional.', 'reportit'), 'params' => '$A [, $B, $C]', 'syntax' => 'bool f_isNaN (float $A [, float $B, float $C])', 'examples' => 'f_isNaN(5) = 0, f_isNaN(f_min) = 1 or 0, f_isNaN(f_min,5) = 5 or 0, f_isNaN(f_min,5,10) = 5 or 10', 'parentheses' => true - ), - 'f_cmp' => array( + ], + 'f_cmp' => [ 'title' => __('f_cmp - Complex Comparison', 'reportit'), 'description' => __('Returns 1 (or B) if A === NaN or 0 (or C) if not. Parameters B and C are optional.', 'reportit'), 'params' => '$A [, $B, $C]', 'syntax' => 'bool f_nan (float $A [, float $B, float $C])', 'examples' => 'f_nan(5) = 0, f_nan(f_min()) = 1 or 0, f_nan(f_min(),5) = 5 or 0, f_nan(f_min(),5,10) = 5 or 10', 'parentheses' => true - ) - ), - 2 => array( - 'f_int' => array( + ] + ], + 2 => [ + 'f_int' => [ 'title' => __('f_int - Alias of f_floor', 'reportit'), 'description' => __('Returns the next lowest integer value by rounding down value if necessary.', 'reportit'), 'params' => __('$var: float', 'reportit'), 'syntax' => 'integer f_int (float $var)', 'examples' => 'f_int(69.19) = 69', 'parentheses' => true - ), - 'f_rnd' => array( + ], + 'f_rnd' => [ 'title' => __('f_rnd - Alias of f_round', 'reportit'), 'description' => __('Returns the rounded integer value of any given float.', 'reportit'), 'params' => __('$var: float or string value', 'reportit'), 'syntax' => 'integer f_rnd (float $var)', 'examples' => 'f_rnd(69.50) = 70, f_rnd(69,49) = 69', 'parentheses' => true - ), - 'f_eq' => array( + ], + 'f_eq' => [ 'title' => __('f_eq - Alias of f_cmp - IS EQUAL', 'reportit'), 'description' => __('Returns 1 (or C) if A == B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_eq (float $A, float $B [, float $C, float $D])', 'examples' => 'f_eq(5,6) = 0, f_eq(6,6) = 1, f_eq(f_min,6) = 1 or 0, f_eq(6,6,f_min) = f_min, f_eq(6,5,f_min,f_max) = f_max', 'parentheses' => true - ), - 'f_uq' => array( - 'title' => __('f_uq - Alias of f_cmp - IS UNEQUAL', 'reportit'), - 'description' => __('Returns 1 (or C) if A != B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), - 'params' => '$A, $B [, $C, $D]', - 'syntax' => 'bool f_uq (float $A, float $B [, float $C, float $D])', + ], + 'f_uq' => [ + 'title' => __('f_uq - Alias of f_cmp - IS UNEQUAL', 'reportit'), + 'description' => __('Returns 1 (or C) if A != B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), + 'params' => '$A, $B [, $C, $D]', + 'syntax' => 'bool f_uq (float $A, float $B [, float $C, float $D])', 'examples' => 'f_uq(5,6) = 1, f_uq(6,6) = 0, f_uq(f_min,6) = 1 or 0, f_uq(6,6,f_min) = 0, f_uq(6,5,f_min,f_max) = f_min', - 'parentheses' => true - ), - 'f_gt' => array( - 'title' => __('f_gt - Alias of f_cmp - IS GREATER THAN', 'reportit'), - 'description' => __('Returns 1 (or C) if A > B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), - 'params' => '$A, $B [, $C, $D]', - 'syntax' => 'bool f_gt (float $A, float $B [, float $C, float $D])', + 'parentheses' => true + ], + 'f_gt' => [ + 'title' => __('f_gt - Alias of f_cmp - IS GREATER THAN', 'reportit'), + 'description' => __('Returns 1 (or C) if A > B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), + 'params' => '$A, $B [, $C, $D]', + 'syntax' => 'bool f_gt (float $A, float $B [, float $C, float $D])', 'examples' => 'f_gt(5,6) = 0, f_gt(6,6) = 0, f_gt(f_min,6) = 1 or 0, f_gt(6,6,f_min) = 0, f_gt(6,5,f_min,f_max) = f_min', - 'parentheses' => true - ), - 'f_lt' => array( + 'parentheses' => true + ], + 'f_lt' => [ 'title' => __('f_lt - Alias of f_cmp - IS LOWER THAN', 'reportit'), 'description' => __('Returns 1 (or C) if A < B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_lt (float $A, float $B [, float $C, float $D])', 'examples' => 'f_lt(5,6) = 1, f_lt(6,6) = 0, f_lt(f_min,6) = 1 or 0, f_lt(6,6,f_min) = 0, f_lt(6,5,f_min,f_max) = f_max()', 'parentheses' => true - ), - 'f_ge' => array( + ], + 'f_ge' => [ 'title' => __('f_ge - Alias of f_cmp - IS GREATER OR EQUAL', 'reportit'), 'description' => __('Returns 1 (or C) if A >= B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_ge (float $A, float $B [, float $C, float $D])', 'examples' => 'f_ge(5,6) = 0, f_ge(6,6) = 1, f_ge(f_min,6) = 1 or 0, f_ge(6,6,f_min) = f_min, f_ge(6,5,f_min,f_max) = f_min', 'parentheses' => true - ), - 'f_le' => array( + ], + 'f_le' => [ 'title' => __('f_le - Alias of f_cmp - IS LOWER OR EQUAL', 'reportit'), 'description' => __('Returns 1 (or C) if A <= B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_le (float $A, float $B [, float $C, float $D])', 'examples' => 'f_le(5,6) = 1, f_le(6,6) = 1, f_le(f_min,6) = 1 or 0, f_le(6,6,f_min) = f_min, f_le(6,5,f_min,f_max) = f_max', 'parentheses' => true - ) - ), - 3 => array( - '+' => array( + ] + ], + 3 => [ + '+' => [ 'title' => __('Addition', 'reportit'), 'description' => __('Mathematical Operation to return the sum of two or more summands', 'reportit'), 'params' => 'none', 'syntax' => '$A + $B', 'examples' => '10 + 2 = 12' - ), - '-' => array( + ], + '-' => [ 'title' => __('Subtraction', 'reportit'), 'description' => __('Mathematical Operation to return the difference of minuend and subtrahend', 'reportit'), 'params' => 'none', 'syntax' => '$A - $B', 'examples' => '10 - 2 = 8' - ), - '*' => array( + ], + '*' => [ 'title' => __('Multiplication', 'reportit'), 'description' => __('Mathematical Operation to return the product of multiplier and multiplicant', 'reportit'), 'params' => 'none', 'syntax' => '$A * $B', 'examples' => '10 * 2 = 20' - ), - '/' => array( + ], + '/' => [ 'title' => __('Division', 'reportit'), 'description' => __('Mathematical Operation to return the fraction of divident and divisor', 'reportit'), 'params' => 'none', 'syntax' => '$A / $B', 'examples' => '10 / 2 = 5' - ), - '%' => array( + ], + '%' => [ 'title' => __('Modulus', 'reportit'), 'description' => __('Mathematical Operation to return the remainder of a division of two integers', 'reportit'), 'params' => 'none', 'syntax' => '$A % $B', 'examples' => '10 % 2 = 0' - ), - '**' => array( + ], + '**' => [ 'title' => __('Exponentiation - PHP5.6 or above required', 'reportit'), 'description' => __('Mathematical Operation to return the repeated multiplication (or division) of a base by its exponent.', 'reportit'), 'params' => 'none', 'syntax' => '$A ** $B', 'examples' => '10 ** 2 = 10 * 10 = 100' - ) - ), - 4 => array('1' => '', '2' => '', '3' => '', '4' => '', '5' => '', '6' => '', '7' => '', '8' => '', '9' => '', '0' => '', - '.' => array( + ] + ], + 4 => ['1' => '', '2' => '', '3' => '', '4' => '', '5' => '', '6' => '', '7' => '', '8' => '', '9' => '', '0' => '', + '.' => [ 'title' => __('Decimal Mark', 'reportit'), 'description' => __('Decimal Mark used to separate the integer part from the fractional part', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '10.2+14.8', - ), - ), - 5 => array( - '( )' => array( + ], + ], + 5 => [ + '( )' => [ 'title' => __('Round Bracket', 'reportit'), 'description' => __('Used to override normal precedence or to mark the first level of nesting', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '(10 + 2) * (10 + 2) = 144', 'parentheses' => true - ), - '[ ]' => array( + ], + '[ ]' => [ 'title' => __('Square Bracket', 'reportit'), 'description' => __('Used to override normal precedence or to mark the second level of nesting', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '[(10 - 2) * (10 - 2)] - 4 = 60', 'parentheses' => true - ), - ',' => array( + ], + ',' => [ 'title' => __('Punctuation mark', 'reportit'), 'description' => __('Used to separate arguments forwarded to a function', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => 'f_fhigh(fmin,fmax, ... )', - ), - ), - 6 => array( - 'minRRDValue' => array( + ], + ], + 6 => [ + 'minRRDValue' => [ 'title' => 'minRRDValue', 'description' => __('The minimum value of data that is allowed to be collected.', 'reportit') . "
\t" . __('WARNING! This variable can be set to zero or unlimited', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '-', - ), - 'maxRRDValue' => array( + ], + 'maxRRDValue' => [ 'title' => 'maxRRDValue', 'description' => __('The maximum value of data that is allowed to be collected.', 'reportit') . "
\t" . __('WARNING! This variable can be set to zero or unlimited', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '-', - ), - 'step' => array( + ], + 'step' => [ 'title' => 'step', 'description' => __('Contains the number of seconds between two measured values.', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '-', - ) - ) -); + ] + ] +]; -$measurands_rubrics = array( +$measurands_rubrics = [ 0 => __('Functions w/o parameters', 'reportit'), 1 => __('Functions with parameters', 'reportit'), 2 => __('Aliases', 'reportit'), @@ -532,9 +530,9 @@ 6 => __('Variables', 'reportit'), 7 => __('Data Query Variables', 'reportit'), 8 => __('Interim Results', 'reportit') -); +]; -$settings_max_record_per_report = array( +$settings_max_record_per_report = [ '0' => __('Unlimited', 'reportit'), '500' => __('500 Data Items', 'reportit'), '1000' => __('1,000 Data Items', 'reportit'), @@ -545,14 +543,13 @@ '15000' => __('15,000 Data Source Items', 'reportit'), '25000' => __('25,000 Data Source Items', 'reportit'), '30000' => __('25,000 Data Source Items', 'reportit') -); +]; -$settings_max_cache_life_time = array( +$settings_max_cache_life_time = [ 60 => __('1 Minute', 'reportit'), 120 => __('%d Minutes', 2, 'reportit'), 300 => __('%d Minutes', 5, 'reportit'), 600 => __('%d Minutes', 10, 'reportit'), 1200 => __('%d Minutes', 20, 'reportit'), 1800 => __('%d Minutes', 30, 'reportit'), -); - +]; diff --git a/include/global_forms.php b/include/global_forms.php index 472ef67..fd4eeac 100644 --- a/include/global_forms.php +++ b/include/global_forms.php @@ -22,156 +22,155 @@ +-------------------------------------------------------------------------+ */ -$fields_template_edit = array( - 'id' => array( +$fields_template_edit = [ + 'id' => [ 'method' => 'hidden_zero', - 'value' => '|arg1:id|' - ), - 'data_template_id' => array( + 'value' => '|arg1:id|' + ], + 'data_template_id' => [ 'method' => 'hidden_zero', - 'value' => '|arg1:data_template_id|' - ), - 'save_component_template' => array( + 'value' => '|arg1:data_template_id|' + ], + 'save_component_template' => [ 'method' => 'hidden_zero', - 'value' => 1 - ), - 'ds_enabled__0' => array( + 'value' => 1 + ], + 'ds_enabled__0' => [ 'method' => 'hidden_zero', - 'value' => 'on' - ), - 'template_header' => array( + 'value' => 'on' + ], + 'template_header' => [ 'friendly_name' => __('General', 'reportit'), - 'method' => 'spacer', - 'collapsible' => 'true' - ), - 'template_name' => array( + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'template_name' => [ 'friendly_name' => __('Name'), - 'method' => 'textbox', - 'max_length' => '100', - 'description' => __('The unique name given to this Report Template.', 'reportit'), - 'value' => '|arg1:name|' - ), - 'template_description' => array( + 'method' => 'textbox', + 'max_length' => '100', + 'description' => __('The unique name given to this Report Template.', 'reportit'), + 'value' => '|arg1:name|' + ], + 'template_description' => [ 'friendly_name' => __('Description', 'reportit'), - 'method' => 'textarea', - 'max_length' => '255', + 'method' => 'textarea', + 'max_length' => '255', 'textarea_cols' => '80', 'textarea_rows' => '5', - 'description' => __('A longer description of this Report Template.', 'reportit'), - 'value' => '|arg1:description|' - ), - 'template_version' => array( + 'description' => __('A longer description of this Report Template.', 'reportit'), + 'value' => '|arg1:description|' + ], + 'template_version' => [ 'friendly_name' => __('Version', 'reportit'), - 'method' => 'textbox', - 'max_length' => '100', - 'description' => __('A version number for this template', 'reportit'), - 'default' => '1.0', - 'value' => '|arg1:version|' - ), - 'template_author' => array( + 'method' => 'textbox', + 'max_length' => '100', + 'description' => __('A version number for this template', 'reportit'), + 'default' => '1.0', + 'value' => '|arg1:version|' + ], + 'template_author' => [ 'friendly_name' => __('Author', 'reportit'), - 'method' => 'textbox', - 'max_length' => '100', - 'description' => __('The author of this template', 'reportit'), - 'default' => get_username($_SESSION['sess_user_id']), - 'value' => '|arg1:author|' - ), - 'template_enabled' => array( - 'method' => 'checkbox', + 'method' => 'textbox', + 'max_length' => '100', + 'description' => __('The author of this template', 'reportit'), + 'default' => get_username($_SESSION['sess_user_id']), + 'value' => '|arg1:author|' + ], + 'template_enabled' => [ + 'method' => 'checkbox', 'friendly_name' => __('Publish', 'reportit'), - 'description' => __('Should this report template be published for users to access? For testing purposes of new templates or modifications you should uncheck this box.', 'reportit'), - 'value' => '|arg1:enabled|', - ), - 'template_locked' => array( + 'description' => __('Should this report template be published for users to access? For testing purposes of new templates or modifications you should uncheck this box.', 'reportit'), + 'value' => '|arg1:enabled|', + ], + 'template_locked' => [ 'friendly_name' => __('Locked', 'reportit'), - 'method' => 'checkbox', - 'description' => __('The status "locked" avoids any kind of modification to your report template as well as assigned measurands and variable definitions', 'reportit'), - 'value' => '|arg1:locked|', - ), - 'template_filter' => array( + 'method' => 'checkbox', + 'description' => __('The status "locked" avoids any kind of modification to your report template as well as assigned measurands and variable definitions', 'reportit'), + 'value' => '|arg1:locked|', + ], + 'template_filter' => [ 'friendly_name' => __('Additional Pre-filter', 'reportit'), - 'method' => 'textbox', - 'max_length' => '100', - 'description' => __('Optional: The syntax to filter the available list of data items by their description. Use SQL wildcards like % and/or _. No regular Expressions!', 'reportit'), - 'value' => '|arg1:pre_filter|', - 'default' => '' - ), - 'template_export_folder' => array( + 'method' => 'textbox', + 'max_length' => '100', + 'description' => __('Optional: The syntax to filter the available list of data items by their description. Use SQL wildcards like % and/or _. No regular Expressions!', 'reportit'), + 'value' => '|arg1:pre_filter|', + 'default' => '' + ], + 'template_export_folder' => [ 'friendly_name' => __('Export Path', 'reportit'), - 'description' => __('Optional: The path to an folder for saving the exports. If it does not exist ReportIt automatically tries to create it during the first scheduled calculation, else it will try to create a new subfolder within the main export folder using the template id.', 'reportit'), - 'method' => 'dirpath', - 'max_length' => '255', - 'value' => '|arg1:export_folder|', - 'default' => '' - ), - 'template_header2' => array( + 'description' => __('Optional: The path to an folder for saving the exports. If it does not exist ReportIt automatically tries to create it during the first scheduled calculation, else it will try to create a new subfolder within the main export folder using the template id.', 'reportit'), + 'method' => 'dirpath', + 'max_length' => '255', + 'value' => '|arg1:export_folder|', + 'default' => '' + ], + 'template_header2' => [ 'friendly_name' => __('Data Template', 'reportit'), - 'method' => 'spacer', - 'collapsible' => 'true' - ), - 'template_data_template_label' => array( + 'method' => 'spacer', + 'collapsible' => 'true' + ], + 'template_data_template_label' => [ 'friendly_name' => __('Data Template', 'reportit'), - 'method' => 'label', - 'max_length' => '100', - 'description' => __('The name of the data template this Report Template depends on.', 'reportit'), - 'value' => '|arg1:data_template_name|' - ), - 'template_data_template' => array( + 'method' => 'label', + 'max_length' => '100', + 'description' => __('The name of the data template this Report Template depends on.', 'reportit'), + 'value' => '|arg1:data_template_name|' + ], + 'template_data_template' => [ 'friendly_name' => __('Data Template', 'reportit'), - 'method' => 'hidden', - 'max_length' => '100', - 'description' => __('The name of the data template this Report Template depends on.', 'reportit'), - 'value' => '|arg1:data_template_id|' - ) -); + 'method' => 'hidden', + 'max_length' => '100', + 'description' => __('The name of the data template this Report Template depends on.', 'reportit'), + 'value' => '|arg1:data_template_id|' + ] +]; -$fields_template_export = array( - 'action' => array( +$fields_template_export = [ + 'action' => [ 'method' => 'hidden_zero', - 'value' => 'template_export' - ), - 'template_id' => array( + 'value' => 'template_export' + ], + 'template_id' => [ 'friendly_name' => __('Report Template', 'reportit'), - 'description' => __('Choose one of your Report Templates to export to XML.', 'reportit'), - 'method' => 'drop_sql', - 'sql' => 'SELECT id, description as name FROM plugin_reportit_templates WHERE locked = 0 ORDER BY description', - 'default' => 0, - 'none_value' => 'None', - 'value' => '', - ), - 'template_description' => array( - 'method' => 'textarea', + 'description' => __('Choose one of your Report Templates to export to XML.', 'reportit'), + 'method' => 'drop_sql', + 'sql' => 'SELECT id, description as name FROM plugin_reportit_templates WHERE locked = 0 ORDER BY description', + 'default' => 0, + 'none_value' => 'None', + 'value' => '', + ], + 'template_description' => [ + 'method' => 'textarea', 'friendly_name' => __('[Optional] Description', 'reportit'), - 'description' => __('Describe the characteristics of your report template', 'reportit'), - 'value' => '', - 'default' => '', + 'description' => __('Describe the characteristics of your report template', 'reportit'), + 'value' => '', + 'default' => '', 'textarea_rows' => '10', 'textarea_cols' => '50', - 'class' => 'textAreaNotes' - ), - 'template_author' => array( - 'method' => 'textbox', + 'class' => 'textAreaNotes' + ], + 'template_author' => [ + 'method' => 'textbox', 'friendly_name' => __('[Optional] Author', 'reportit'), - 'description' => __('Add your name or nick here.', 'reportit'), - 'value' => '', - 'max_length' => '250', - 'size' => 50 - ), - 'template_version' => array( - 'method' => 'textbox', + 'description' => __('Add your name or nick here.', 'reportit'), + 'value' => '', + 'max_length' => '250', + 'size' => 50 + ], + 'template_version' => [ + 'method' => 'textbox', 'friendly_name' => __('[Optional] Version', 'reportit'), - 'description' => __('Add your name or nick here.', 'reportit'), - 'value' => '', - 'max_length' => '250', - 'size' => 50 - ), - 'template_contact' => array( - 'method' => 'textbox', + 'description' => __('Add your name or nick here.', 'reportit'), + 'value' => '', + 'max_length' => '250', + 'size' => 50 + ], + 'template_contact' => [ + 'method' => 'textbox', 'friendly_name' => __('[Optional] Contact', 'reportit'), - 'description' => __('Add your name or nick here.', 'reportit'), - 'value' => '', - 'max_length' => '250', - 'size' => 50 - ), -); - + 'description' => __('Add your name or nick here.', 'reportit'), + 'value' => '', + 'max_length' => '250', + 'size' => 50 + ], +]; diff --git a/lib/const_graphs.php b/lib/const_graphs.php index 4c213c1..1430072 100644 --- a/lib/const_graphs.php +++ b/lib/const_graphs.php @@ -28,12 +28,12 @@ $affix = ''; $exponent = ''; $prefix = ''; -$results = array(); -$prefixes = array(); -$x_values = array(); -$report_ds_alias = array(); +$results = []; +$prefixes = []; +$x_values = []; +$report_ds_alias = []; -$prefixes[1] = array( +$prefixes[1] = [ 0 => '', 1 => 'Ki', 2 => 'Mi', @@ -43,9 +43,9 @@ 6 => 'Ei', 7 => 'Zi', 8 => 'Yi' -); +]; -$prefixes[2] = array( +$prefixes[2] = [ 0 => '', 1 => 'k', 2 => 'M', @@ -55,42 +55,41 @@ 6 => 'E', 7 => 'Z', 8 => 'Y' -); +]; -$types = array( - '-10' => array ( +$types = [ + '-10' => [ 'description' => __('Bar (vertical)', 'reportit'), 'name' => 'b', 'x_axis' => 'Position', 'y_axis' => 1 - ), - '10' => array ( + ], + '10' => [ 'description' => __('Bar (horizontal)', 'reportit'), 'name' => 'hb', 'x_axis' => 1, 'y_axis' => 'Position' - ), - '20' => array ( + ], + '20' => [ 'description' => __('Line', 'reportit'), 'name' => 'l', 'x_axis' => 'Position', 'y_axis' => 1 - ), - '21' => array ( + ], + '21' => [ 'description' => __('Area', 'reportit'), 'name' => 'l', 'x_axis' => 'Position', 'y_axis' => 1, 'filled' => 1 - ), - '30' => array ( + ], + '30' => [ 'description' => __('Pie chart 3D', 'reportit'), 'name' => 'p' - ), - '40' => array ( + ], + '40' => [ 'description' => __('Spider', 'reportit'), 'name' => 's', 'x_value' => '1' - ), -); - + ], +]; diff --git a/lib/const_items.php b/lib/const_items.php index cf06cc4..e2c322b 100644 --- a/lib/const_items.php +++ b/lib/const_items.php @@ -22,7 +22,6 @@ +-------------------------------------------------------------------------+ */ -//----- CONSTANTS FOR: items.php ----- - -$link_array = array('name_cache', ''); +// ----- CONSTANTS FOR: items.php ----- +$link_array = ['name_cache', '']; diff --git a/lib/const_measurands.php b/lib/const_measurands.php index 3a2d311..d4e1dc4 100644 --- a/lib/const_measurands.php +++ b/lib/const_measurands.php @@ -22,331 +22,331 @@ +-------------------------------------------------------------------------+ */ -$calc_functions = array( - 'f_avg' => array( +$calc_functions = [ + 'f_avg' => [ 'title' => __('f_avg - Arithmetic Average', 'reportit'), 'description' => __('Returns the average value of all measured values per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_avg', 'examples' => 'f_avg*8' - ), - 'f_max' => array( + ], + 'f_max' => [ 'title' => __('f_max - Maximum Value', 'reportit'), 'description' => __('Returns the highest measured value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_max', 'examples' => '(f_max-f_min)*8' - ), - 'f_min' => array( + ], + 'f_min' => [ 'title' => __('f_min - Minimum Value', 'reportit'), 'description' => __('Returns the lowest measured value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_min', 'examples' => 'f_min*8' - ), - 'f_sum' => array( + ], + 'f_sum' => [ 'title' => __('f_sum - Sum', 'reportit'), 'description' => __('Returns the sum of all measured values per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_sum', 'examples' => 'f_sum*8' - ), - 'f_num' => array( + ], + 'f_num' => [ 'title' => __('f_num - Number of Values (Not NaN)', 'reportit'), 'description' => __('Returns the number of valid measured values per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'int f_num', 'examples' => 'f_num' - ), - 'f_grd' => array( + ], + 'f_grd' => [ 'title' => __('f_grd - Gradient', 'reportit'), 'description' => __('Returns the gradient of a straight line by using linear regression per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_grd', 'examples' => 'f_grd' - ), - 'f_last' => array( + ], + 'f_last' => [ 'title' => __('f_last - Last Value', 'reportit'), 'description' => __('Returns the last valid measured value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_last', 'examples' => 'f_last*16/2' - ), - 'f_1st' => array( + ], + 'f_1st' => [ 'title' => __('f_1st - First Value', 'reportit'), 'description' => __('Returns the first valid measured value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_1st', 'examples' => 'f_1st*2*(5.5-1.5)' - ), - 'f_nan' => array( + ], + 'f_nan' => [ 'title' => __('f_nan - Number of NaNs', 'reportit'), 'description' => __('Returns the number of NaNs stored per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'int f_nan', 'examples' => 'f_num+f_nan' - ), - 'f_median' => array( + ], + 'f_median' => [ 'title' => __('f_median - Median', 'reportit'), 'description' => __('Returns that value that separates the higher half from the lower half per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_median', 'examples' => 'f_median' - ), - 'f_mode' => array( + ], + 'f_mode' => [ 'title' => __('f_mode - Mode', 'reportit'), 'description' => __('Returns the value that appears most often per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_mode', 'examples' => 'f_mode' - ), - 'f_range' => array( + ], + 'f_range' => [ 'title' => __('f_range - Range', 'reportit'), 'description' => __('Returns the difference between the largest and the smallest value per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_range', 'examples' => 'f_range' - ), - 'f_iqr' => array( + ], + 'f_iqr' => [ 'title' => __('f_iqr - Interquartile Range', 'reportit'), 'description' => __('Returns the distance of the middle50% around the median per DS', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_iqr', 'examples' => 'f_iqr' - ), - 'f_sd' => array( + ], + 'f_sd' => [ 'title' => __('f_sd - Standard Deviation', 'reportit'), 'description' => __('Returns the square root per data source variance', 'reportit'), 'params' => __('none', 'reportit'), 'syntax' => 'float f_sd', 'examples' => 'f_sd' - ), -); + ], +]; $calc_fct_names = array_keys($calc_functions); -$calc_functions_aliases = array( - 'f_int' => array( +$calc_functions_aliases = [ + 'f_int' => [ 'title' => __('f_int - Alias of f_floor', 'reportit'), 'description' => __('Returns the next lowest integer value by rounding down value if necessary.', 'reportit'), 'params' => __('$var: float', 'reportit'), 'syntax' => 'integer f_int (float $var)', 'examples' => 'f_int(69.19) = 69' - ), - 'f_rnd' => array( + ], + 'f_rnd' => [ 'title' => __('f_rnd - Alias of f_round', 'reportit'), 'description' => __('Returns the rounded integer value of any given float.', 'reportit'), 'params' => __('$var: float or string value', 'reportit'), 'syntax' => 'integer f_rnd (float $var)', 'examples' => 'f_rnd(69.50) = 70, f_rnd(69,49) = 69' - ), -); + ], +]; $calc_fct_aliases = array_keys($calc_functions_aliases); -$calc_functions_params = array( - 'f_xth' => array( +$calc_functions_params = [ + 'f_xth' => [ 'title' => __('f_xth - Xth Percentile', 'reportit'), 'description' => __('Returns the xth percentitle.', 'reportit'), 'params' => __('$var: threshold in percent. Range: [0< $var ≤100]', 'reportit'), 'syntax' => 'float f_xth (float $var)', 'examples' => 'f_xth(95.7), f_xth(c1v)' - ), - 'f_dot' => array( + ], + 'f_dot' => [ 'title' => __('f_dot - Duration Over Threshold', 'reportit'), 'description' => __('Returns the duration over a defined threshold in percent.', 'reportit'), 'params' => __('$var: threshold (absolute)', 'reportit'), 'syntax' => 'float f_dot (float $var)', 'examples' => 'f_dot(10000000), f_dot(maxValue*c1v/100)' - ), - 'f_sot' => array( + ], + 'f_sot' => [ 'title' => __('f_sot - Sum Over Threshold', 'reportit'), 'description' => __('Returns the sum of values over a defined threshold.', 'reportit'), 'params' => __('$var: threshold (absolute)', 'reportit'), 'syntax' => 'float f_sot (float $var)', 'examples' => 'f_sot(75000000), f_sot(maxValue*c4v/100)' - ), - 'f_floor' => array( + ], + 'f_floor' => [ 'title' => __('f_floor - Round Fractions Down', 'reportit'), 'description' => __('Returns the next lowest integer value by rounding down value if necessary.', 'reportit'), 'params' => __('$var: float', 'reportit'), 'syntax' => 'integer f_floor (float $var)', 'examples' => 'f_floor(69.19) = 69' - ), - 'f_ceil' => array( + ], + 'f_ceil' => [ 'title' => __('f_ceil - Round Fractions Up', 'reportit'), 'description' => __('Returns the next highest integer value by rounding up value if necessary.', 'reportit'), 'params' => __('$var: float', 'reportit'), 'syntax' => 'integer f_ceil (float $var)', 'examples' => 'f_ceil(69.19) = 70' - ), - 'f_round' => array( + ], + 'f_round' => [ 'title' => __('f_round - Round A Float', 'reportit'), 'description' => __('Returns the rounded integer value of any given float.', 'reportit'), 'params' => __('$var: float or string value', 'reportit'), 'syntax' => 'integer f_round (float $var)', 'examples' => 'f_round(69.50) = 70, f_round(69,49) = 69' - ), - 'f_high' => array( + ], + 'f_high' => [ 'title' => __('f_high - Find Highest Value', 'reportit'), 'description' => __('Returns the highest value of a given list of parameters', 'reportit'), 'params' => __('$var1, $var2, $var3 ...: values to be compared', 'reportit'), 'syntax' => 'float f_high (float $var1, float $var2)', 'examples' => 'f_high(27,70) = 70' - ), - 'f_low' => array( + ], + 'f_low' => [ 'title' => __('f_high - Find Lowest Value', 'reportit'), 'description' => __('Returns the lowest value of a given list of parameters', 'reportit'), 'params' => __('$var1, $var2, $var3 ...: values to be compared', 'reportit'), 'syntax' => 'float f_low (float $var1, float $var2)', 'examples' => 'f_low(27,70) = 27' - ), - 'f_if' => array( + ], + 'f_if' => [ 'title' => __('f_if - Conditional Operation - IF-THEN-ELSE Logic', 'reportit'), 'description' => __('Returns B if A is true or C if A is false', 'reportit'), 'params' => '$A, $B, $C', 'syntax' => 'bool f_if (float $A, float $B, float $C)', 'examples' => 'f_if (0,1,2) = 2, f_if(1,1,2) = 1, f_if(f_low(0,1),f_1st, f_last) = f_last' - ), - 'f_isNaN' => array( + ], + 'f_isNaN' => [ 'title' => __('f_isNaN - Find whether a value is not a number', 'reportit'), 'description' => __('Returns 1 (or B) if A === NaN or 0 (or C) if not. Parameters B and C are optional.', 'reportit'), 'params' => '$A [, $B, $C]', 'syntax' => 'bool f_isNaN (float $A [, float $B, float $C])', 'examples' => 'f_isNaN(5) = 0, f_isNaN(f_min) = 1 or 0, f_isNaN(f_min,5) = 5 or 0, f_isNaN(f_min,5,10) = 5 or 10' - ), - 'f_eq' => array( + ], + 'f_eq' => [ 'title' => __('f_eq - Alias of f_cmp - IS EQUAL', 'reportit'), 'description' => __('Returns 1 (or C) if A == B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_eq (float $A, float $B [, float $C, float $D])', 'examples' => 'f_eq(5,6) = 0, f_eq(6,6) = 1, f_eq(f_min,6) = 1 or 0, f_eq(6,6,f_min) = f_min, f_eq(6,5,f_min,f_max) = f_max' - ), - 'f_uq' => array( + ], + 'f_uq' => [ 'title' => __('f_uq - Alias of f_cmp - IS UNEQUAL', 'reportit'), 'description' => __('Returns 1 (or C) if A != B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_uq (float $A, float $B [, float $C, float $D])', 'examples' => 'f_uq(5,6) = 1, f_uq(6,6) = 0, f_uq(f_min,6) = 1 or 0, f_uq(6,6,f_min) = 0, f_uq(6,5,f_min,f_max) = f_min' - ), - 'f_gt' => array( + ], + 'f_gt' => [ 'title' => __('f_gt - Alias of f_cmp - IS GREATER THAN', 'reportit'), 'description' => __('Returns 1 (or C) if A > B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_gt (float $A, float $B [, float $C, float $D])', 'examples' => 'f_gt(5,6) = 0, f_gt(6,6) = 0, f_gt(f_min,6) = 1 or 0, f_gt(6,6,f_min) = 0, f_gt(6,5,f_min,f_max) = f_min' - ), - 'f_lt' => array( + ], + 'f_lt' => [ 'title' => __('f_lt - Alias of f_cmp - IS LOWER THAN', 'reportit'), 'description' => __('Returns 1 (or C) if A < B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_lt (float $A, float $B [, float $C, float $D])', 'examples' => 'f_lt(5,6) = 1, f_lt(6,6) = 0, f_lt(f_min,6) = 1 or 0, f_lt(6,6,f_min) = 0, f_lt(6,5,f_min,f_max) = f_max()' - ), - 'f_ge' => array( + ], + 'f_ge' => [ 'title' => __('f_ge - Alias of f_cmp - IS GREATER OR EQUAL', 'reportit'), 'description' => __('Returns 1 (or C) if A >= B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_ge (float $A, float $B [, float $C, float $D])', 'examples' => 'f_ge(5,6) = 0, f_ge(6,6) = 1, f_ge(f_min,6) = 1 or 0, f_ge(6,6,f_min) = f_min, f_ge(6,5,f_min,f_max) = f_min' - ), - 'f_le' => array( + ], + 'f_le' => [ 'title' => __('f_le - Alias of f_cmp - IS LOWER OR EQUAL', 'reportit'), 'description' => __('Returns 1 (or C) if A <= B or 0 (or D) if not. Parameters C and D are optional.', 'reportit'), 'params' => '$A, $B [, $C, $D]', 'syntax' => 'bool f_le (float $A, float $B [, float $C, float $D])', 'examples' => 'f_le(5,6) = 1, f_le(6,6) = 1, f_le(f_min,6) = 1 or 0, f_le(6,6,f_min) = f_min, f_le(6,5,f_min,f_max) = f_max' - ), -); + ], +]; -$calc_fct_names_params = array_keys($calc_functions_params); +$calc_fct_names_params = array_keys($calc_functions_params); -$calc_operators = array( - '+' => array( +$calc_operators = [ + '+' => [ 'title' => __('Addition', 'reportit'), 'description' => __('Mathematical Operation to return the sum of two or more summands', 'reportit'), 'params' => 'none', 'syntax' => '$A + $B', 'examples' => '10 + 2 = 12' - ), - '-' => array( + ], + '-' => [ 'title' => __('Subtraction', 'reportit'), 'description' => __('Mathematical Operation to return the difference of minuend and subtrahend', 'reportit'), 'params' => 'none', 'syntax' => '$A - $B', 'examples' => '10 - 2 = 8' - ), - '*' => array( + ], + '*' => [ 'title' => __('Multiplication', 'reportit'), 'description' => __('Mathematical Operation to return the product of multiplier and multiplicant', 'reportit'), 'params' => 'none', 'syntax' => '$A * $B', 'examples' => '10 * 2 = 20' - ), - '/' => array( + ], + '/' => [ 'title' => __('Division', 'reportit'), 'description' => __('Mathematical Operation to return the fraction of divident and divisor', 'reportit'), 'params' => 'none', 'syntax' => '$A / $B', 'examples' => '10 / 2 = 5' - ), - '%' => array( + ], + '%' => [ 'title' => __('Modulus', 'reportit'), 'description' => __('Mathematical Operation to return the remainder of a division of two integers', 'reportit'), 'params' => 'none', 'syntax' => '$A % $B', 'examples' => '10 % 2 = 0' - ), - '**' => array( + ], + '**' => [ 'title' => __('Exponentiation - PHP5.6 or above required', 'reportit'), 'description' => __('Mathematical Operation to return the repeated multiplication (or division) of a base by its exponent.', 'reportit'), 'params' => 'none', 'syntax' => '$A ** $B', 'examples' => '10 ** 2 = 10 * 10 = 100' - ) -); + ] +]; -$calc_parentheses = array( - '(' => array( +$calc_parentheses = [ + '(' => [ 'title' => __('Left (Opening) parenthesis', 'reportit'), 'description' => __('Used to override normal precedence or to mark the first level of nesting', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '(10 + 2) * (10 + 2) = 144' - ), - ')' => array( + ], + ')' => [ 'title' => __('Right (Closing) parenthesis', 'reportit'), 'description' => __('Used to override normal precedence or to mark the first level of nesting', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '(10 + 2) * (10 + 2) = 144' - ), - '[' => array( + ], + '[' => [ 'title' => __('Left (Opening) Square Bracket', 'reportit'), 'description' => __('Used to override normal precedence or to mark the second level of nesting', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '[(10 - 2) * (10 - 2)] - 4 = 60' - ), - ']' => array( + ], + ']' => [ 'title' => __('Right (Closing) Square Bracket', 'reportit'), 'description' => __('Used to override normal precedence or to mark the second level of nesting', 'reportit'), 'params' => 'none', 'syntax' => '-', 'examples' => '[(10 - 2) * (10 - 2)] - 4 = 60' - ), -); + ], +]; -$calc_variables = array( +$calc_variables = [ 'maxValue' => __('Contains the maximum bandwidth if \'ifspeed\' is available.', 'reportit'), 'maxRRDValue' => __('Contains the maximum value that has been defined for the specific data source item under \"Data Sources\".', 'reportit'), 'step' => __('Contains the number of seconds between two measured values.', 'reportit'), 'nan' => __('Contains the number of NAN\'s during the reporting period.', 'reportit') -); +]; $calc_var_names = array_keys($calc_variables); -$rubrics = array( +$rubrics = [ __('Functions w/o parameters', 'reportit') => $calc_functions, __('Functions with parameters', 'reportit') => $calc_functions_params, __('Aliases', 'reportit') => $calc_functions_aliases, @@ -355,15 +355,15 @@ __('Variables', 'reportit') => $calc_variables, __('Data Query Variables', 'reportit') => '', __('Interim Results', 'reportit') => '' -); +]; -$rounding = array( +$rounding = [ __('off', 'reportit'), __('Binary SI-Prefixes (Base 1024)', 'reportit'), __('Decimal SI-Prefixes (Base 1000)', 'reportit') -); +]; -$type_specifier = array( +$type_specifier = [ __('Binary', 'reportit'), __('Floating point', 'reportit'), __('Integer', 'reportit'), @@ -372,9 +372,9 @@ __('Hexadecimal (upper-case)', 'reportit'), __('Octal', 'reportit'), __('Scientific Notation', 'reportit') -); +]; -$precision = array( +$precision = [ 0 => __('None', 'reportit'), 1 => 1, 2 => 2, @@ -386,5 +386,4 @@ 8 => 8, 9 => 9, -1 => __('Unchanged', 'reportit') -); - +]; diff --git a/lib/const_reports.php b/lib/const_reports.php index c6ec577..7809e3b 100644 --- a/lib/const_reports.php +++ b/lib/const_reports.php @@ -22,23 +22,23 @@ +-------------------------------------------------------------------------+ */ -//----- CONSTANTS FOR: reports.php ----- +// ----- CONSTANTS FOR: reports.php ----- -$report_actions = array( +$report_actions = [ 2 => __('Delete', 'reportit'), 4 => __('Disable', 'reportit'), 3 => __('Duplicate', 'reportit'), 5 => __('Enable', 'reportit'), 1 => __('Run Now', 'reportit'), 6 => __('Take Ownership', 'reportit') -); +]; -$report_states = array( +$report_states = [ '-2' => __('CRASHED', 'reportit'), '-1' => __('FAILED', 'reportit'), '0' => __('Idle', 'reportit'), '1' => __('Running', 'reportit') -); +]; /** * $templates - array, for dropdown menu @@ -49,7 +49,7 @@ if (!$templates) { $templates['0'] = __('- No template available -', 'reportit'); } else { - foreach($templates as $key => $value) { + foreach ($templates as $key => $value) { $tmp[$templates[$key]['id']] = $templates[$key]['description']; } @@ -58,7 +58,7 @@ unset($tmp); } -$weekday = array( +$weekday = [ __('Monday', 'reportit'), __('Tuesday', 'reportit'), __('Wednesday', 'reportit'), @@ -66,13 +66,13 @@ __('Friday', 'reportit'), __('Saturday', 'reportit'), __('Sunday', 'reportit') -); +]; /** * $timespans - array, for dropdown menu * contains preset values for selecting the report timespan */ -$timespans = array( +$timespans = [ __('Today', 'reportit'), __('Last 1 Day', 'reportit'), __('Last 2 Days', 'reportit'), @@ -96,71 +96,72 @@ __('Current Year', 'reportit'), __('Last Year', 'reportit'), __('Last 2 Years', 'reportit') -); +]; // Timezones foreach ($timezones as $tmz => $value) { $timezone[] = $tmz; } -//Schedule frequency -$frequency = array( +// Schedule frequency +$frequency = [ 'daily' => __('Daily', 'reportit'), 'weekly' => __('Weekly', 'reportit'), 'monthly' => __('Monthly', 'reportit'), 'quarterly' => __('Quarterly', 'reportit'), 'yearly' => __('Yearly', 'reportit') -); +]; // Maximum number of files an archive can contain $archive[0] = 'off'; -for($i = 1; $i <= 1000; $i++) { - $archive[$i]= $i; + +for ($i = 1; $i <= 1000; $i++) { + $archive[$i] = $i; } // Tabs -$tabs = array( +$tabs = [ 'general' => __('General', 'reportit'), 'presets' => __('Data Source Presets', 'reportit'), 'email' => __('Email', 'reportit'), 'items' => __('Data Sources', 'reportit') -); +]; // $shifttime - array, for dropdown menu // - contains all possible timestamps of a day by using steps of 5 minutes -$shifttime = array(); +$shifttime = []; -for($i=0; $i<24; $i++) { - $hour=$i; +for ($i = 0; $i < 24; $i++) { + $hour = $i; - if ($hour<10) { + if ($hour < 10) { $hour = '0' . $hour; } - for($j=0; $j<60; $j+=5) { + for ($j = 0; $j < 60; $j += 5) { $minutes = $j; - if ($minutes<10) { + if ($minutes < 10) { $minutes = '0' . $minutes; } - $shifttime[]= "$hour:$minutes:00"; + $shifttime[] = "$hour:$minutes:00"; } } -$shifttime2 = $shifttime; -$shifttime2[]= "24:00:00"; +$shifttime2 = $shifttime; +$shifttime2[] = '24:00:00'; unset($i); unset($j); -$format = array( +$format = [ 'None' => __('None', 'reportit'), 'CSV' => __('Text CSV (.csv)', 'reportit'), 'SML' => __('MS Excel 2003 XML (.xml)', 'reportit'), 'XML' => __('Raw XML (.xml)', 'reportit'), 'JSON' => __('JSON Data (.json)', 'reportit') -); +]; if (function_exists('yaml_emit')) { $format['YAML'] = __('YAML Data (.yaml)', 'reportit'); @@ -175,23 +176,23 @@ 'id', 'name' ); } else { - $notify_lists = array(); + $notify_lists = []; } -$form_array_email = array( - 'header_1' => array( +$form_array_email = [ + 'header_1' => [ 'friendly_name' => __('General', 'reportit'), 'method' => 'spacer', - ), - 'id' => array( + ], + 'id' => [ 'method' => 'hidden_zero', 'value' => '|arg1:id|', - ), - 'tab' => array( + ], + 'tab' => [ 'method' => 'hidden_zero', 'value' => 'email', - ), - 'email_subject' => array( + ], + 'email_subject' => [ 'friendly_name' => __('Subject', 'reportit'), 'description' => __('Enter the subject of your email.
Following variables will be supported (without quotes): \'|title|\' and \'|period|\'', 'reportit'), 'size' => '60', @@ -199,8 +200,8 @@ 'method' => 'textbox', 'default' => __('Scheduled report - |title| - |period|', 'reportit'), 'value' => '|arg1:email_subject|', - ), - 'email_body' => array( + ], + 'email_body' => [ 'friendly_name' => __('Body (optional)', 'reportit'), 'description' => __('Enter a message which will be displayed in the body of your email', 'reportit'), 'method' => 'textarea', @@ -208,20 +209,20 @@ 'textarea_cols' => '45', 'default' => __('This is a scheduled report generated from Cacti.', 'reportit'), 'value' => '|arg1:email_body|', - ), - 'email_format' => array( + ], + 'email_format' => [ 'friendly_name' => __('Attachment', 'reportit'), 'method' => 'drop_array', 'description' => __('Only to receive an email as a notification that a new report is available choose \'None\'.
Otherwise select the format the report should be attached as.', 'reportit'), 'value' => '|arg1:email_format|', 'array' => $format, 'default' => '1', - ), - 'header_2' => array( + ], + 'header_2' => [ 'friendly_name' => __('Email Recipients', 'reportit'), 'method' => 'spacer', - ), - 'notify_list' => array( + ], + 'notify_list' => [ 'friendly_name' => __('Notification List Recipients', 'reportit'), 'description' => __('To add a Recipients based upon an valid Notification List.', 'reportit'), 'method' => 'drop_array', @@ -229,8 +230,8 @@ 'default' => '', 'none_value' => __('None', 'reportit'), 'value' => '|arg1:notify_list|', - ), - 'email' => array( + ], + 'email' => [ 'friendly_name' => __('To Email Address(es)'), 'method' => 'textarea', 'textarea_rows' => '5', @@ -240,8 +241,8 @@ 'description' => __('Please separate multiple addresses by comma (,)'), 'max_length' => 255, 'value' => '|arg1:email|' - ), - 'bcc' => array( + ], + 'bcc' => [ 'friendly_name' => __('BCC Address(es)'), 'method' => 'textarea', 'textarea_rows' => '5', @@ -251,8 +252,8 @@ 'description' => __('Blind carbon copy. Please separate multiple addresses by comma (,)'), 'max_length' => 255, 'value' => '|arg1:bcc|' - ), - 'email_recipient' => array( + ], + 'email_recipient' => [ 'friendly_name' => __('New Email Recipients', 'reportit'), 'description' => __('To add a new recipient enter a valid email address (required) and a name (optional).
For a faster setup use a list of adresses/names where the names/addresses are separated with one of the following delemiters: \';\' or \',\'', 'reportit'), 'method' => 'custom', @@ -266,19 +267,19 @@ ", - ) -); + ] +]; if (!cacti_sizeof($notify_lists)) { unset($form_array_email['notify_list']); } -$form_array_presets = array( - 'header_1' => array( +$form_array_presets = [ + 'header_1' => [ 'friendly_name' => __('General', 'reportit'), 'method' => 'spacer', - ), - 'subhead' => array( + ], + 'subhead' => [ 'friendly_name' => __('Optional Sub-heading', 'reportit'), 'description' => __('Define an additional subhead that should be on display under the interface description.
Following variables will be supported (without quotes): \'|t1|\' \'|t2|\' \'|tmz|\' \'|d1|\' \'|d2|\'', 'reportit'), 'method' => 'textarea', @@ -286,105 +287,105 @@ 'textarea_cols' => '45', 'value' => '|arg1:subhead|', 'default' => '', - ), -); + ], +]; if (read_config_option('reportit_use_tmz') == 'on') { - $form_array_presets['timezone'] = array( + $form_array_presets['timezone'] = [ 'friendly_name' => __('Time Zone', 'reportit'), 'description' => __('Select the time zone your following shifttime informations will be based on.', 'reportit'), 'method' => 'drop_array', 'value' => '|arg1:timezone|', 'default' => '17', 'array' => array_keys($timezones) - ); + ]; } -$form_array_presets_2 = array( - 'data_source_header' => array( +$form_array_presets_2 = [ + 'data_source_header' => [ 'friendly_name' => __('Optional Data Source Pre-Filters', 'reportit'), 'method' => 'spacer', - ), - 'site_id' => array( + ], + 'site_id' => [ 'friendly_name' => __('Site Filter', 'reportit'), 'description' => __('Use this Sites matching Data Sources only.
Select \'None\' (default) to deactivate this filter setting.', 'reportit'), 'method' => 'drop_sql', 'sql' => 'SELECT id, name FROM sites ORDER BY name', 'none_value' => __('None', 'reportit'), 'value' => '|arg2:site_id|', - ), - 'host_template_id' => array( + ], + 'host_template_id' => [ 'friendly_name' => __('Device Template Filter', 'reportit'), 'description' => __('Use this Device Templates Data Sources only.
Select \'None\' (default) to deactivate this filter setting.', 'reportit'), 'method' => 'drop_sql', 'sql' => 'SELECT id, name FROM host_template ORDER BY name', 'none_value' => __('None', 'reportit'), 'value' => '|arg2:host_template_id|', - ), - 'data_source_filter' => array( + ], + 'data_source_filter' => [ 'friendly_name' => __('Data Source Name Filter', 'reportit'), 'description' => __('Use Data Sources whose names match this filter.
Use SQL wildcards like % and/or _. No regular Expressions!', 'reportit'), 'method' => 'textbox', 'size' => 50, 'max_length' => '100', 'value' => '|arg2:data_source_filter|', - ), - 'autorrdlist' => array( + ], + 'autorrdlist' => [ 'friendly_name' => __('Auto Generated Data Items', 'reportit'), 'description' => __('Enable/disable automatic creation of all data items based on given filters.This will be called before report execution. Obsolete RRDs will be deleted and all RRDs matching the filter settings will be added.', 'reportit'), 'method' => 'checkbox', 'value' => '|arg1:autorrdlist|', 'default' => '', - ), - 'header_2' => array( + ], + 'header_2' => [ 'friendly_name' => __('Working Time', 'reportit'), 'method' => 'spacer', - ), - 'id' => array( + ], + 'id' => [ 'method' => 'hidden_zero', 'value' => '|arg1:id|', - ), - 'tab' => array( + ], + 'tab' => [ 'method' => 'hidden_zero', 'value' => 'presets', - ), - 'start_time' => array( + ], + 'start_time' => [ 'friendly_name' => __('From', 'reportit'), 'description' => __('The startpoint of duration you want to analyse', 'reportit'), 'method' => 'drop_array', 'default' => '0', 'value' => '|arg1:start_time|', 'array' => $shifttime, - ), - 'end_time' => array( + ], + 'end_time' => [ 'friendly_name' => __('To', 'reportit'), 'description' => __('The end of analysing time.', 'reportit'), 'method' => 'drop_array', 'default' => '288', 'value' => '|arg1:end_time|', 'array' => $shifttime2, - ), - 'header_3' => array( + ], + 'header_3' => [ 'friendly_name' => __('Working Days', 'reportit'), 'method' => 'spacer', - ), - 'start_day' => array( + ], + 'start_day' => [ 'friendly_name' => __('From', 'reportit'), 'description' => __('Define the band of days where shift STARTS!', 'reportit'), 'method' => 'drop_array', 'value' => '|arg1:start_day|', 'default' => '0', 'array' => $weekday - ), - 'end_day' => array( + ], + 'end_day' => [ 'friendly_name' => __('To', 'reportit'), 'method' => 'drop_array', 'description' => __('Example: For a nightshift from Mo(22:30) till Sat(06:30) define Monday to Friday', 'reportit'), 'value' => '|arg1:end_day|', 'default' => '6', 'array' => $weekday - ), -); + ], +]; $form_array_presets = array_merge($form_array_presets, $form_array_presets_2); @@ -406,113 +407,112 @@ ON group_member.user_id = user_auth.id WHERE group_member.user_id IS NOT NULL OR user_realm.user_id IS NOT NULL'; -$form_array_general = array( - 'id' => array( +$form_array_general = [ + 'id' => [ 'method' => 'hidden_zero', 'value' => '|arg1:id|', - ), - 'tab' => array( + ], + 'tab' => [ 'method' => 'hidden_zero', 'value' => 'general', - ), - 'template_id' => array( + ], + 'template_id' => [ 'method' => 'hidden_zero', 'value' => '|arg1:template_id|', - ), - 'header_1' => array( + ], + 'header_1' => [ 'friendly_name' => __('General', 'reportit'), 'method' => 'spacer', - ), - 'name' => array( + ], + 'name' => [ 'friendly_name' => __('Name', 'reportit'), 'description' => __('The name given to this report', 'reportit'), 'method' => 'textbox', 'max_length' => '100', 'value' => '|arg1:name|', - ), - 'template' => array( + ], + 'template' => [ 'friendly_name' => __('Template', 'reportit'), 'description' => __('The template your configuration depends on', 'reportit'), 'method' => 'custom', 'max_length' => '100', 'value' => '|arg1:template|', 'default' => '', - ), - 'owner' => array( + ], + 'owner' => [ 'friendly_name' => __('Owner', 'reportit'), 'description' => __('Change the owner of this report. Only users with the permission "view" or above can be chosen.', 'reportit'), - 'method' => (user_auth_realm(REPORTIT_USER_ADMIN, my_id()) ? 'drop_sql':'hidden_zero'), + 'method' => (user_auth_realm(REPORTIT_USER_ADMIN, my_id()) ? 'drop_sql' : 'hidden_zero'), 'sql' => $owner_sql, 'value' => '|arg1:user_id|', - ), - 'enabled' => array( + ], + 'enabled' => [ 'friendly_name' => __('Enabled', 'reportit'), 'description' => __('Enable/disable scheduled reporting. Sliding time frame should be enabled.', 'reportit'), 'method' => 'checkbox', 'value' => '|arg1:enabled|', 'default' => '', - ), - 'public' => array( + ], + 'public' => [ 'friendly_name' => __('Public', 'reportit'), 'description' => __('If enabled everyone can see your report under tab \'reports\'', 'reportit'), 'method' => 'checkbox', 'value' => '|arg1:public|', 'default' => '', - ), - 'graph_permission' => array( + ], + 'graph_permission' => [ 'friendly_name' => __('Enable Use of Graph Permissions', 'reportit'), 'description' => __('If enabled (default) the list of available data items will be filtered automatically by owner\'s graph permission: \'by device\'.', 'reportit'), 'method' => 'checkbox', 'value' => '|arg1:graph_permission|', 'default' => 'on', - ), - 'auto_email' => array( + ], + 'auto_email' => [ 'friendly_name' => __('Auto Generated Email', 'reportit'), 'description' => __('If enabled tab \'Email\' will be activated and all recipients defined under that section will receive automatically an email containing this scheduled report.', 'reportit'), 'method' => 'checkbox', 'value' => '|arg1:auto_email|', 'default' => '' - ), - 'header_2' => array( + ], + 'header_2' => [ 'friendly_name' => __('Reporting Period', 'reportit'), 'method' => 'spacer', - ), - 'sliding' => array( + ], + 'sliding' => [ 'friendly_name' => __('Sliding Time Frame', 'reportit'), 'description' => __('If checked the reporting period will be configured automatically in relation to the point of time the calculation starts.', 'reportit'), 'method' => 'checkbox', 'value' => '|arg1:sliding|', 'default' => 'off', - ), - 'preset_timespan' => array( + ], + 'preset_timespan' => [ 'friendly_name' => __('Time Frames', 'reportit'), 'description' => __('The time frame you want to analyse in relation to the point of time the calculation starts.
This means calendar days, calendar months and calendar years.', 'reportit'), 'method' => 'drop_array', 'value' => '|arg1:preset_timespan|', 'array' => $timespans, - ), - 'present' => array( + ], + 'present' => [ 'friendly_name' => __('Up To The Day of Calculation', 'reportit'), 'description' => __('Extend the sliding time frame up to the day the calculation runs.', 'reportit'), 'method' => 'checkbox', 'value' => '|arg1:present|', 'default' => '', - ), - 'start_date' => array( + ], + 'start_date' => [ 'friendly_name' => __('Fixed Time Frame - Start Date (From)', 'reportit'), 'description' => __('To define the start date use the following format: yyyy-mm-dd', 'reportit'), 'method' => 'textbox', 'max_length' => '10', 'value' => '|arg1:start_date|', - ), - 'end_date' => array( + ], + 'end_date' => [ 'friendly_name' => __('Fixed Time Frame - End Date (To)', 'reportit'), 'description' => __('To define the end date use the following format: yyyy-mm-dd', 'reportit'), 'method' => 'textbox', 'max_length' => '10', 'value' => '|arg1:end_date|', - ) -); + ] +]; $form_array_general += api_scheduler_form(); - diff --git a/lib/const_rrdlist.php b/lib/const_rrdlist.php index 0d87a72..88e45ef 100644 --- a/lib/const_rrdlist.php +++ b/lib/const_rrdlist.php @@ -22,26 +22,26 @@ +-------------------------------------------------------------------------+ */ -//----- CONSTANTS FOR: rrdlist.php ----- +// ----- CONSTANTS FOR: rrdlist.php ----- -$rrdlist_actions = array( +$rrdlist_actions = [ 3 => __('Add to Report', 'reportit'), 1 => __('Remove from Report', 'reportit'), 2 => __('Copy Settings to All', 'reportit') -); +]; -$rrdadd_actions = array( +$rrdadd_actions = [ 1 => __('Add', 'reportit') -); +]; -$link_array = array( +$link_array = [ 'name_cache', 'description', '', '', 'timezone', '' -); +]; // $timezone - array, for dropdown menu // - contains the $keys from $timezones array. @@ -51,7 +51,7 @@ // $weekday - array, for dropdown menu // - contains the names of all weekdays -$weekday = array( +$weekday = [ __('Monday', 'reportit'), __('Tuesday', 'reportit'), __('Wednesday', 'reportit'), @@ -59,20 +59,20 @@ __('Friday', 'reportit'), __('Saturday', 'reportit'), __('Sunday', 'reportit') -); +]; // $shifttime - array, for dropdown menu // - contains all possible timestamps of a day by using steps of 5 minutes -$shifttime = array(); +$shifttime = []; -for($i = 0; $i < 24; $i++) { - $hour=$i; +for ($i = 0; $i < 24; $i++) { + $hour = $i; if ($hour < 10) { $hour = '0' . $hour; } - for($j = 0; $j < 60; $j += 5) { + for ($j = 0; $j < 60; $j += 5) { $minutes = $j; if ($minutes < 10) { @@ -83,9 +83,8 @@ } } -$shifttime2 = $shifttime; -$shifttime2[]= '24:00:00'; +$shifttime2 = $shifttime; +$shifttime2[] = '24:00:00'; unset($i); unset($j); - diff --git a/lib/const_runtime.php b/lib/const_runtime.php index 1849b2f..05ecd03 100644 --- a/lib/const_runtime.php +++ b/lib/const_runtime.php @@ -25,53 +25,60 @@ // ----- CONSTANTS FOR: runtime.php ----- define('REPORTIT_NAN', sqrt(-1)); -if (!defined('REPORTIT_TMP_FD')) define('REPORTIT_TMP_FD', CACTI_PATH_BASE . '/plugins/reportit/tmp/'); -if (!defined('REPORTIT_ARC_FD')) define('REPORTIT_ARC_FD', CACTI_PATH_BASE . '/plugins/reportit/archive/'); -if (!defined('REPORTIT_EXP_FD')) define('REPORTIT_EXP_FD', CACTI_PATH_BASE . '/plugins/reportit/exports/'); +if (!defined('REPORTIT_TMP_FD')) { + define('REPORTIT_TMP_FD', CACTI_PATH_BASE . '/plugins/reportit/tmp/'); +} -$timezones = array( - 'AEDT (GMT+11 )' => array('hour' => 11, 'min' => 0), - 'ACDT (GMT+10.5)' => array('hour' => 10, 'min' => 30), - 'AEST (GMT+10 )' => array('hour' => 10, 'min' => 0), - 'ACST (GMT+09.5)' => array('hour' => 9, 'min' => 30), - 'JST (GMT+09 )' => array('hour' => 9, 'min' => 0), - 'ROK (GMT+09 )' => array('hour' => 9, 'min' => 0), - 'SST (GMT+08 )' => array('hour' => 8, 'min' => 0), - 'THA (GMT+07 )' => array('hour' => 7, 'min' => 0), - 'IST (GMT+05.5)' => array('hour' => 5, 'min' => 30), - 'EEST (GMT+03)' => array('hour' => 3, 'min' => 0), - 'MEST (GMT+02)' => array('hour' => 2, 'min' => 0), - 'EET (GMT+02)' => array('hour' => 2, 'min' => 0), - 'CEST (GMT+02)' => array('hour' => 2, 'min' => 0), - 'BST (GMT+01)' => array('hour' => 1, 'min' => 0), - 'CET (GMT+01)' => array('hour' => 1, 'min' => 0), - 'MET (GMT+01)' => array('hour' => 1, 'min' => 0), - 'WEST (GMT+01)' => array('hour' => 1, 'min' => 0), - 'GMT' => array('hour' => 0, 'min' => 0), - 'WET (GMT)' => array('hour' => 0, 'min' => 0), - 'BDT (GMT-02)' => array('hour' => -2, 'min' => 0), - 'BT (GMT-03)' => array('hour' => -2, 'min' => 0), - 'EDT (GMT-04)' => array('hour' => -4, 'min' => 0), - 'EST (GMT-05)' => array('hour' => -5, 'min' => 0), - 'CDT (GMT-05)' => array('hour' => -5, 'min' => 0), - 'CST (GMT-06)' => array('hour' => -6, 'min' => 0), - 'MDT (GMT-06)' => array('hour' => -6, 'min' => 0), - 'MST (GMT-07)' => array('hour' => -7, 'min' => 0), - 'PDT (GMT-07)' => array('hour' => -7, 'min' => 0), - 'PST (GMT-08)' => array('hour' => -8, 'min' => 0) -); +if (!defined('REPORTIT_ARC_FD')) { + define('REPORTIT_ARC_FD', CACTI_PATH_BASE . '/plugins/reportit/archive/'); +} +if (!defined('REPORTIT_EXP_FD')) { + define('REPORTIT_EXP_FD', CACTI_PATH_BASE . '/plugins/reportit/exports/'); +} -$runtime_messages = array( - 1 => 'ERROR: PHP module for RRDtool is not available.', - 2 => 'ERROR: No data items defined. RIReport[]', - 3 => 'ERROR: Startpoint is a part of future. RIReport[] RIDataItem[]', - 4 => 'ERROR: No valid data found. Check your configuration. RIReport[]', - 5 => 'WARNING: RRDfetch: RIReport[] RIDataItem[]', - 6 => 'WARNING: End of working time is a part of future. Can only calculate data till now. RIReport[] RIDataItem[]', - 7 => 'WARNING: No startpoints available. Check your working days! RIReport[] RIDataItem[]', - 8 => 'WARNING: No values available. RIReport[] RIDataItem[]', - 9 => 'ERROR: Unable to connect to RRDtool server.', +$timezones = [ + 'AEDT (GMT+11 )' => ['hour' => 11, 'min' => 0], + 'ACDT (GMT+10.5)' => ['hour' => 10, 'min' => 30], + 'AEST (GMT+10 )' => ['hour' => 10, 'min' => 0], + 'ACST (GMT+09.5)' => ['hour' => 9, 'min' => 30], + 'JST (GMT+09 )' => ['hour' => 9, 'min' => 0], + 'ROK (GMT+09 )' => ['hour' => 9, 'min' => 0], + 'SST (GMT+08 )' => ['hour' => 8, 'min' => 0], + 'THA (GMT+07 )' => ['hour' => 7, 'min' => 0], + 'IST (GMT+05.5)' => ['hour' => 5, 'min' => 30], + 'EEST (GMT+03)' => ['hour' => 3, 'min' => 0], + 'MEST (GMT+02)' => ['hour' => 2, 'min' => 0], + 'EET (GMT+02)' => ['hour' => 2, 'min' => 0], + 'CEST (GMT+02)' => ['hour' => 2, 'min' => 0], + 'BST (GMT+01)' => ['hour' => 1, 'min' => 0], + 'CET (GMT+01)' => ['hour' => 1, 'min' => 0], + 'MET (GMT+01)' => ['hour' => 1, 'min' => 0], + 'WEST (GMT+01)' => ['hour' => 1, 'min' => 0], + 'GMT' => ['hour' => 0, 'min' => 0], + 'WET (GMT)' => ['hour' => 0, 'min' => 0], + 'BDT (GMT-02)' => ['hour' => -2, 'min' => 0], + 'BT (GMT-03)' => ['hour' => -2, 'min' => 0], + 'EDT (GMT-04)' => ['hour' => -4, 'min' => 0], + 'EST (GMT-05)' => ['hour' => -5, 'min' => 0], + 'CDT (GMT-05)' => ['hour' => -5, 'min' => 0], + 'CST (GMT-06)' => ['hour' => -6, 'min' => 0], + 'MDT (GMT-06)' => ['hour' => -6, 'min' => 0], + 'MST (GMT-07)' => ['hour' => -7, 'min' => 0], + 'PDT (GMT-07)' => ['hour' => -7, 'min' => 0], + 'PST (GMT-08)' => ['hour' => -8, 'min' => 0] +]; + +$runtime_messages = [ + 1 => 'ERROR: PHP module for RRDtool is not available.', + 2 => 'ERROR: No data items defined. RIReport[]', + 3 => 'ERROR: Startpoint is a part of future. RIReport[] RIDataItem[]', + 4 => 'ERROR: No valid data found. Check your configuration. RIReport[]', + 5 => 'WARNING: RRDfetch: RIReport[] RIDataItem[]', + 6 => 'WARNING: End of working time is a part of future. Can only calculate data till now. RIReport[] RIDataItem[]', + 7 => 'WARNING: No startpoints available. Check your working days! RIReport[] RIDataItem[]', + 8 => 'WARNING: No values available. RIReport[] RIDataItem[]', + 9 => 'ERROR: Unable to connect to RRDtool server.', 10 => 'ERROR: Data Template for RIReport[] has been locked during the scheduled task', 11 => 'WARNING: Unknown timezone: . Please update configuration of Report [] RIDataItem[]', 12 => 'ERROR: RIReport[]', @@ -80,5 +87,4 @@ 15 => 'WARNING: ', 16 => 'NOTICE: ', 17 => 'ERROR: ' -); - +]; diff --git a/lib/const_templates.php b/lib/const_templates.php index 154111d..cfced95 100644 --- a/lib/const_templates.php +++ b/lib/const_templates.php @@ -24,31 +24,31 @@ // ----- CONSTANTS FOR: templates.php ----- -$template_actions = array( +$template_actions = [ 1 => 'Delete', 2 => 'Duplicate', 3 => 'Export', -); +]; -$desc_array = array( +$desc_array = [ 'Template Name', 'Data Template', 'Pre-filter', 'Locked', 'Metrics', 'Variables' -); +]; -$link_array = array( +$link_array = [ 'description', 'data_template_id', 'pre_filter', 'locked', 'measurands', 'variables' -); +]; -$order_array = array('ASC', 'DESC'); +$order_array = ['ASC', 'DESC']; $sql = 'SELECT DISTINCT b.id, b.name FROM data_template_rrd AS a INNER JOIN data_template as b @@ -56,33 +56,32 @@ WHERE a.local_data_id != 0 ORDER BY b.name'; -$data_templates = array(); -$list_of_data_templates = array(); +$data_templates = []; +$list_of_data_templates = []; $data_templates = db_fetch_assoc($sql); -foreach($data_templates as $data_template) { + +foreach ($data_templates as $data_template) { $list_of_data_templates[$data_template['id']] = $data_template['name']; } $sql = 'SELECT DISTINCT b.id, b.name FROM data_template AS b ORDER BY b.name'; - global $known_data_templates; -$known_data_templates = array(); +$known_data_templates = []; $data_templates = db_fetch_assoc($sql); -foreach($data_templates as $data_template) { + +foreach ($data_templates as $data_template) { $known_data_templates[$data_template['id']] = $data_template['name']; } - -$hashes = array( - '1' => array( +$hashes = [ + '1' => [ 'reportit' => 'c0788d60041d96616d05b87892942948', 'general' => 'b993b55029680216764b47d1da5c18d', 'settings' => 'd446e8da603362e98b7d868e99e144fd', 'measurand'=> 'd52041e0e00f5daac84f1cd15532732c', 'variable' => 'fa1e95ba13fc87fa80da64758628d68f' - ) -); - + ] +]; diff --git a/lib/const_variables.php b/lib/const_variables.php index 19a59f8..a1ca9ed 100644 --- a/lib/const_variables.php +++ b/lib/const_variables.php @@ -22,37 +22,36 @@ +-------------------------------------------------------------------------+ */ -//----- CONSTANTS FOR: variables.php ----- +// ----- CONSTANTS FOR: variables.php ----- -$variable_actions = array( +$variable_actions = [ 1 => __('Delete', 'reportit') -); +]; -$var_types = array( +$var_types = [ 1 => __('Dropdown', 'reportit'), 2 => __('Input field', 'reportit') -); +]; -$link_array = array( +$link_array = [ 'name', 'abbreviation', 'max_value', 'min_value', 'default_value', 'input_type' -); +]; -$list_of_modes = array( +$list_of_modes = [ 'ASC', 'DESC' -); - -$desc_array = array( - 'description' => array('display' => __('Name', 'reportit'), 'align' => 'left', 'sort' => 'ASC'), - 'nosort' => array('display' => __('Internal Name', 'reportit'), 'align' => 'left'), - 'pre_filter' => array('display' => __('Maximum', 'reportit'), 'align' => 'left'), - 'nosort1' => array('display' => __('Minimum', 'reportit'), 'align' => 'left'), - 'nosort2' => array('display' => __('Default', 'reportit'), 'align' => 'left', 'sort' => 'ASC'), - 'nosort3' => array('display' => __('Input Type', 'reportit'), 'align' => 'left', 'sort' => 'ASC'), -); +]; +$desc_array = [ + 'description' => ['display' => __('Name', 'reportit'), 'align' => 'left', 'sort' => 'ASC'], + 'nosort' => ['display' => __('Internal Name', 'reportit'), 'align' => 'left'], + 'pre_filter' => ['display' => __('Maximum', 'reportit'), 'align' => 'left'], + 'nosort1' => ['display' => __('Minimum', 'reportit'), 'align' => 'left'], + 'nosort2' => ['display' => __('Default', 'reportit'), 'align' => 'left', 'sort' => 'ASC'], + 'nosort3' => ['display' => __('Input Type', 'reportit'), 'align' => 'left', 'sort' => 'ASC'], +]; diff --git a/lib/const_view.php b/lib/const_view.php index fab12c4..1e2ad69 100644 --- a/lib/const_view.php +++ b/lib/const_view.php @@ -22,26 +22,31 @@ +-------------------------------------------------------------------------+ */ -if (!defined('REPORTIT_TMP_FD')) define('REPORTIT_TMP_FD', CACTI_BASE_PATH . '/plugins/reportit/tmp/'); -if (!defined('REPORTIT_ARC_FD')) define('REPORTIT_ARC_FD', CACTI_BASE_PATH . '/plugins/reportit/archive/'); +if (!defined('REPORTIT_TMP_FD')) { + define('REPORTIT_TMP_FD', CACTI_BASE_PATH . '/plugins/reportit/tmp/'); +} -$search = array( +if (!defined('REPORTIT_ARC_FD')) { + define('REPORTIT_ARC_FD', CACTI_BASE_PATH . '/plugins/reportit/archive/'); +} + +$search = [ '|t1|', '|t2|', '|tmz|', '|d1|', '|d2|' -); +]; -$export_formats = array( +$export_formats = [ 'CSV' => __('Text CSV (.csv)', 'reportit'), 'XML' => __('Raw XML (.xml)', 'reportit'), 'SML' => __('MS Excel 2003 XML (.xml)', 'reportit') -); +]; -$threshold = 0.5; +$threshold = 0.5; -$decimal = array( +$decimal = [ 'Y' => pow(1000,8), 'Z' => pow(1000,7), 'E' => pow(1000,6), @@ -50,9 +55,9 @@ 'G' => pow(1000,3), 'M' => pow(1000,2), 'K' => 1000 -); +]; -$binary = array( +$binary = [ 'Y' => pow(1024,8), 'Z' => pow(1024,7), 'E' => pow(1024,6), @@ -61,20 +66,20 @@ 'G' => pow(1024,3), 'M' => pow(1024,2), 'K' => 1024 -); +]; $IEC = read_config_option('reportit_use_IEC'); -$graphs = array( +$graphs = [ '-10' => __('Bar chart: vertical', 'reportit'), '10' => __('Bar chart: horizontal', 'reportit'), '20' => __('Line chart', 'reportit'), '21' => __('Area chart', 'reportit'), '30' => __('Pie chart: 3D', 'reportit'), '40' => __('Spider', 'reportit') -); +]; -$limit = array( +$limit = [ '-4' => __('%s Hi', 20, 'reportit'), '-3' => __('%s Hi', 15, 'reportit'), '-2' => __('%s Hi', 10, 'reportit'), @@ -83,22 +88,21 @@ '2' => __('%s Lo', 10, 'reportit'), '3' => __('%s Lo', 15, 'reportit'), '4' => __('%s Lo', 20, 'reportit') -); +]; -$t_limit = array( +$t_limit = [ '0' => __('Any', 'reportit'), '-4' => '20', '-3' => '15', '-2' => '10', '-1' => '05' -); - -$add_info = array( - '-2' => array(__('None', 'reportit'),''), - '-1' => array(__('All', 'reportit'), ''), - '1' => array(__('Sum', 'reportit'), 'array_sum'), - '2' => array(__('Minimum', 'reportit'), 'min'), - '3' => array(__('Maximum', 'reportit'), 'max'), - '4' => array(__('Average', 'reportit'), 'average') -); +]; +$add_info = [ + '-2' => [__('None', 'reportit'), ''], + '-1' => [__('All', 'reportit'), ''], + '1' => [__('Sum', 'reportit'), 'array_sum'], + '2' => [__('Minimum', 'reportit'), 'min'], + '3' => [__('Maximum', 'reportit'), 'max'], + '4' => [__('Average', 'reportit'), 'average'] +]; diff --git a/lib/funct_calculate.php b/lib/funct_calculate.php index 46522f6..7d01b35 100644 --- a/lib/funct_calculate.php +++ b/lib/funct_calculate.php @@ -22,61 +22,62 @@ +-------------------------------------------------------------------------+ */ -/* ----- Functions without external parameters ----- */ +// ----- Functions without external parameters ----- -//Count the number of available measuring points +// Count the number of available measuring points function f_num(&$array, &$f_cache) { $f_cache['f_count'] = count($array); return $f_cache['f_count']; } -//Sum +// Sum function f_sum(&$array, &$f_cache) { $f_cache['f_sum'] = empty($array) ? REPORTIT_NAN : array_sum($array); return $f_cache['f_sum']; } -//Average +// Average function f_avg(&$array, &$f_cache) { - $f_cache['f_avg'] = empty($array) ? REPORTIT_NAN : array_sum($array)/count($array); + $f_cache['f_avg'] = empty($array) ? REPORTIT_NAN : array_sum($array) / count($array); return $f_cache['f_avg']; } -//Maximum +// Maximum function f_max(&$array, &$f_cache) { $f_cache['f_max'] = empty($array) ? REPORTIT_NAN : max($array); return $f_cache['f_max']; } -//Minimum +// Minimum function f_min(&$array, &$f_cache) { $f_cache['f_min'] = empty($array) ? REPORTIT_NAN : min($array); return $f_cache['f_min']; } -//First measured value +// First measured value function f_1st(&$array, &$f_cache) { $f_cache['f_1st'] = empty($array) ? REPORTIT_NAN : reset($array); return $f_cache['f_1st']; } -//Last measured value +// Last measured value function f_last(&$array, &$f_cache) { $f_cache['f_last'] = empty($array) ? REPORTIT_NAN : end($array); return $f_cache['f_last']; } -//Gradient +// Gradient function f_grd(&$array, &$f_cache) { if (empty($array)) { $f_cache['f_grd'] = REPORTIT_NAN; + return $f_cache['f_grd']; } @@ -85,101 +86,111 @@ function f_grd(&$array, &$f_cache) { $y_array = array_values($array); $x_array = array_keys($array); - $y_i = array_sum($y_array)/$cnt; - $x_i = array_sum($x_array)/$cnt; + $y_i = array_sum($y_array) / $cnt; + $x_i = array_sum($x_array) / $cnt; $num = 0; $denum = 0; - for ($i=0; $i<$cnt; $i++) { - $num += ($x_array[$i]-$x_i)*($y_array[$i]-$y_i); - $denum += pow(($x_array[$i]-$x_i),2); + for ($i = 0; $i < $cnt; $i++) { + $num += ($x_array[$i] - $x_i) * ($y_array[$i] - $y_i); + $denum += pow(($x_array[$i] - $x_i),2); } - $f_cache['f_grd'] = $num/$denum; + $f_cache['f_grd'] = $num / $denum; + return $f_cache['f_grd']; } -//returns the median +// returns the median function f_median(&$array, &$f_cache) { if ($f_cache['f_median'] === false) { if (empty($array)) { $f_cache['f_median'] = REPORTIT_NAN; } else { - $cnt = f_num($array, $f_cache); + $cnt = f_num($array, $f_cache); $values = $array; sort($values); + if ($cnt % 2 == 1) { - $index = (($cnt + 1) / 2 ) - 1; + $index = (($cnt + 1) / 2) - 1; $f_cache['f_median'] = $values[$index]; } else { - $index = (($cnt) / 2 ) -1; - $f_cache['f_median'] = 0.5*($values[$index]+$values[$index+1]); + $index = (($cnt) / 2) - 1; + $f_cache['f_median'] = 0.5 * ($values[$index] + $values[$index + 1]); } } } + return $f_cache['f_median']; } -//returns the distance between the highest and lowest measured value +// returns the distance between the highest and lowest measured value function f_range(&$array, &$f_cache) { if ($f_cache['f_range'] === false) { - $f_cache['f_range'] = empty($array) ? REPORTIT_NAN : f_max($array, $f_cache)-f_min($array, $f_cache); + $f_cache['f_range'] = empty($array) ? REPORTIT_NAN : f_max($array, $f_cache) - f_min($array, $f_cache); } + return $f_cache['f_range']; } -//returns the interquartile range -function f_iqr(&$array, &$f_cache){ +// returns the interquartile range +function f_iqr(&$array, &$f_cache) { if ($f_cache['f_iqr'] === false) { if (empty($array)) { $f_cache['f_iqr'] = REPORTIT_NAN; } else { - $cnt = f_num($array, $f_cache); - $first_quartile = ((0.25*$cnt)%1 == 0) ? 0.5*(0.25*$cnt+(0.25*$cnt+1)) : intval(0.25*$cnt+1); - $fourth_quartile = ((0.25*$cnt)%1 == 0) ? 0.5*(0.75*$cnt+(0.75*$cnt+1)) : intval(0.75*$cnt+1); - $f_cache['f_iqr'] = $array[$fourth_quartile-1] - $array[$first_quartile-1]; + $cnt = f_num($array, $f_cache); + $first_quartile = ((0.25 * $cnt) % 1 == 0) ? 0.5 * (0.25 * $cnt + (0.25 * $cnt + 1)) : intval(0.25 * $cnt + 1); + $fourth_quartile = ((0.25 * $cnt) % 1 == 0) ? 0.5 * (0.75 * $cnt + (0.75 * $cnt + 1)) : intval(0.75 * $cnt + 1); + $f_cache['f_iqr'] = $array[$fourth_quartile - 1] - $array[$first_quartile - 1]; } } + return $f_cache['f_iqr']; } -//returns the variance -function f_var(&$array, &$f_cache){ +// returns the variance +function f_var(&$array, &$f_cache) { if ($f_cache['f_var'] === false) { if (empty($array)) { $f_cache['f_var'] = REPORTIT_NAN; } else { - $avg = f_avg($array, $f_cache); - $num = f_num($array, $f_cache); + $avg = f_avg($array, $f_cache); + $num = f_num($array, $f_cache); $numerator = 0; - foreach($array as $value) { - $numerator += sqrt($value-$avg); + + foreach ($array as $value) { + $numerator += sqrt($value - $avg); } - $f_cache['f_sd'] = $numerator/$num; + $f_cache['f_sd'] = $numerator / $num; } } + return $f_cache['f_var']; } -//returns the standard deviation +// returns the standard deviation function f_sd(&$array, &$f_cache) { if ($f_cache['f_sd'] === false) { if (empty($array)) { $f_cache['f_sd'] = REPORTIT_NAN; } else { - $variance = f_var($array, $f_cache); - $f_cache['f_sd'] = ($variance !== REPORTIT_NAN ) ? sqrt($variance) : REPORTIT_NAN; + $variance = f_var($array, $f_cache); + $f_cache['f_sd'] = ($variance !== REPORTIT_NAN) ? sqrt($variance) : REPORTIT_NAN; } } + return $f_cache['f_sd']; } -/* ----- Functions with external variables ----- */ +// ----- Functions with external variables ----- -//Xth percentitle +// Xth percentitle function f_xth(&$array, &$p_cache, $value) { - if ($value > 100 || $value <= 0) return REPORTIT_NAN; + if ($value > 100 || $value <= 0) { + return REPORTIT_NAN; + } if (empty($array)) { $p_cache['f_xth'] = REPORTIT_NAN; @@ -189,13 +200,13 @@ function f_xth(&$array, &$p_cache, $value) { sort($array); - $x = intval(count($array)*($value/100)); + $x = intval(count($array) * ($value / 100)); $p_cache['f_xth'] = $array[$x]; return $p_cache['f_xth']; } -//Sum Over Threshold +// Sum Over Threshold function f_sot(&$array, &$p_cache, $threshold) { if (empty($array)) { $p_cache['f_sot'] = REPORTIT_NAN; @@ -208,7 +219,10 @@ function f_sot(&$array, &$p_cache, $threshold) { foreach ($array as $value) { if ($value != 0) { $value -= $threshold; - if ($value > 0) $over_threshold += $value; + + if ($value > 0) { + $over_threshold += $value; + } } } @@ -217,61 +231,70 @@ function f_sot(&$array, &$p_cache, $threshold) { return $p_cache['f_sot']; } -//Duration Over Threshold +// Duration Over Threshold function f_dot(&$array, &$p_cache, $threshold) { - if (empty($array)) { $p_cache['f_dot'] = REPORTIT_NAN; + return $p_cache['f_dot']; } $i = 0; + foreach ($array as $value) { if ($value != 0) { $value -= $threshold; - if ($value > 0) $i++; + + if ($value > 0) { + $i++; } } - $p_cache['f_dot'] = ($i/count($array))*100; + } + $p_cache['f_dot'] = ($i / count($array)) * 100; return $p_cache['f_dot']; } -//Get the integer value <-- should become an alias of 'f_floor' +// Get the integer value <-- should become an alias of 'f_floor' function f_int(&$array, &$p_cache, $value) { - $p_cache['f_int'] = empty($array) ? REPORTIT_NAN : floor($value); + $p_cache['f_int'] = empty($array) ? REPORTIT_NAN : floor($value); $p_cache['f_floor'] = $p_cache['f_int']; - return $p_cache['f_int']; - } -//Round fractions down + return $p_cache['f_int']; +} + +// Round fractions down function f_floor(&$array, &$p_cache, $value) { $p_cache['f_floor'] = empty($array) ? REPORTIT_NAN : floor($value); - $p_cache['f_int'] = $p_cache['f_floor']; + $p_cache['f_int'] = $p_cache['f_floor']; + return $p_cache['f_floor']; } -//Round fractions up +// Round fractions up function f_ceil(&$array, &$p_cache, $value) { $p_cache['f_ceil'] = empty($array) ? REPORTIT_NAN : ceil($value); + return $p_cache['f_ceil']; } -//Get the rounded integer value <--- should become an alias of 'f_round' +// Get the rounded integer value <--- should become an alias of 'f_round' function f_rnd(&$array, &$p_cache, $value) { - $p_cache['f_rnd'] = empty($array) ? REPORTIT_NAN : round($value); + $p_cache['f_rnd'] = empty($array) ? REPORTIT_NAN : round($value); $p_cache['f_round'] = $p_cache['f_rnd']; - return $p_cache['f_rnd']; - } -//Get the rounded integer value + return $p_cache['f_rnd']; +} + +// Get the rounded integer value function f_round(&$array, &$p_cache, $value) { $p_cache['f_round'] = empty($array) ? REPORTIT_NAN : round($value); - $p_cache['f_rnd'] = $p_cache['f_round']; + $p_cache['f_rnd'] = $p_cache['f_round']; + return $p_cache['f_round']; } -//Get the highest value of a list of given numbers +// Get the highest value of a list of given numbers function f_high(&$array, &$p_cache) { if (func_num_args() < 3 || empty($array)) { $p_cache['f_high'] = REPORTIT_NAN; @@ -284,26 +307,28 @@ function f_high(&$array, &$p_cache) { return $p_cache['f_high']; } -//Get the lowest values of a list of given numbers +// Get the lowest values of a list of given numbers function f_low(&$array, &$p_cache) { if (func_num_args() < 3 || empty($array)) { $p_cache['f_low'] = REPORTIT_NAN; + return $p_cache['f_low']; } $p_cache['f_low'] = min(array_slice(func_get_args(), 2)); - return $p_cache['f_low']; - } -//If then else logic .. If arg1 is true then return arg2 else arg3 -function f_if (&$array, &$p_cache) { + return $p_cache['f_low']; +} +// If then else logic .. If arg1 is true then return arg2 else arg3 +function f_if(&$array, &$p_cache) { if (func_num_args() != 5 || empty($array)) { $p_cache['f_if'] = REPORTIT_NAN; } else { - $args = array_slice(func_get_args(), 2); + $args = array_slice(func_get_args(), 2); $p_cache['f_if'] = ($args[0]) ? $args[1] : $args[2]; } + return $p_cache['f_if']; } @@ -313,78 +338,85 @@ function f_gt(&$array, &$p_cache) { $p_cache['f_gt'] = REPORTIT_NAN; } else { $args = array_slice(func_get_args(), 2); + return f_cmp($array, $p_cache, 'gt', $args); } } -/* Alias for f_cmp - 'Lower than' logic */ +// Alias for f_cmp - 'Lower than' logic function f_lt(&$array, &$p_cache) { if (func_num_args() < 4 || func_num_args() > 6 || empty($array)) { $p_cache['f_lt'] = REPORTIT_NAN; } else { $args = array_slice(func_get_args(), 2); + return f_cmp($array, $p_cache, 'lt', $args); } } -/* Alias for f_cmp - 'Greater than or equal' logic */ +// Alias for f_cmp - 'Greater than or equal' logic function f_ge(&$array, &$p_cache) { if (func_num_args() < 4 || func_num_args() > 6 || empty($array)) { $p_cache['f_ge'] = REPORTIT_NAN; } else { $args = array_slice(func_get_args(), 2); + return f_cmp($array, $p_cache, 'ge', $args); } } -/* Alias for f_cmp - 'Lower than or equal ' logic */ +// Alias for f_cmp - 'Lower than or equal ' logic function f_le(&$array, &$p_cache) { if (func_num_args() < 4 || func_num_args() > 6 || empty($array)) { $p_cache['f_le'] = REPORTIT_NAN; } else { $args = array_slice(func_get_args(), 2); + return f_cmp($array, $p_cache, 'le', $args); } } -/* Alias for f_cmp - 'Equal' logic */ +// Alias for f_cmp - 'Equal' logic function f_eq(&$array, &$p_cache) { if (func_num_args() < 4 || func_num_args() > 6 || empty($array)) { $p_cache['f_eq'] = REPORTIT_NAN; } else { $args = array_slice(func_get_args(), 2); + return f_cmp($array, $p_cache, 'eq', $args); } } -/* Alias for f_cmp - 'Equal' logic */ +// Alias for f_cmp - 'Equal' logic function f_uq(&$array, &$p_cache) { if (func_num_args() < 4 || func_num_args() > 6 || empty($array)) { $p_cache['f_uq'] = REPORTIT_NAN; } else { $args = array_slice(func_get_args(), 2); + return f_cmp($array, $p_cache, 'uq', $args); } } -/* compare function */ +// compare function function f_cmp(&$array, &$p_cache, $function, $args) { - $operators = array('eq' => '==', 'lt' => '<', 'gt' => '>', 'le' => '<=', 'ge' => '>=', 'uq' => '!='); + $operators = ['eq' => '==', 'lt' => '<', 'gt' => '>', 'le' => '<=', 'ge' => '>=', 'uq' => '!=']; - $condition = 'return (' . $args[0] . $operators[$function] . $args[1] . ') ? true : false;'; + $condition = 'return (' . $args[0] . $operators[$function] . $args[1] . ') ? true : false;'; if (cacti_sizeof($args) == 2) { - /* no return value given - return 1 or 0 if true or false */ - $p_cache['f_'.$function] = eval($condition) ? 1 : 0; - } else if (cacti_sizeof($args) == 3) { - /* pos. return value given - return third argument if true or 0 if false */ - $p_cache['f_'.$function] = eval($condition) ? $args[2] : 0; + // no return value given - return 1 or 0 if true or false + $p_cache['f_' . $function] = eval($condition) ? 1 : 0; + } elseif (cacti_sizeof($args) == 3) { + // pos. return value given - return third argument if true or 0 if false + $p_cache['f_' . $function] = eval($condition) ? $args[2] : 0; } else { /* pos. return value given - return third argument if true neg. return value given - return fourth argument if false */ - $p_cache['f_'.$function] = eval($condition) ? $args[2] : $args[3]; + $p_cache['f_' . $function] = eval($condition) ? $args[2] : $args[3]; } - return $p_cache['f_'.$function]; + + return $p_cache['f_' . $function]; } function f_isNaN(&$array, &$p_cache) { @@ -392,11 +424,12 @@ function f_isNaN(&$array, &$p_cache) { $p_cache['f_nan'] = REPORTIT_NAN; } else { $args = array_slice(func_get_args(), 2); + if (cacti_sizeof($args) == 2) { - /* no return value given - return 1 or 0 if true or false */ + // no return value given - return 1 or 0 if true or false $p_cache['f_nan'] = (is_nan($args[0]) || is_null($args[0])) ? 1 : 0; - } else if (cacti_sizeof($args) == 3) { - /* pos. return value given - return third argument if true or 0 if false */ + } elseif (cacti_sizeof($args) == 3) { + // pos. return value given - return third argument if true or 0 if false $p_cache['f_nan'] = (is_nan($args[0]) || is_null($args[0])) ? $args[2] : 0; } else { /* pos. return value given - return third argument if true @@ -404,41 +437,43 @@ function f_isNaN(&$array, &$p_cache) { $p_cache['f_nan'] = (is_nan($args[0]) || is_null($args[0])) ? $args[2] : $args[3]; } } + return $p_cache['f_nan']; } function calculate_handler() { global $calculate_last_formula; + if (!empty($calculate_last_formula)) { cacti_log('ERROR: Bad Formula: ' . $calculate_last_formula, false, 'REPORTIT'); } } -/* ----- Main function for calculating ----- */ +// ----- Main function for calculating ----- global $calculate_handler_set, $calculate_last_formula; -//Normal way of calculation +// Normal way of calculation function calculate(&$data, &$params, &$variables, &$df_cache, &$dm_cache, &$dr_cache, &$dp_cache, &$ds_cache) { - $results = array(); + $results = []; - $f_cache = $df_cache; //Functions - $m_cache = $dm_cache; //Metrics - $r_cache = $dr_cache; //Interim results - $p_cache = $dp_cache; //Functions with parameters - $s_cache = $ds_cache; //Metrics with flag 'spanned' + $f_cache = $df_cache; // Functions + $m_cache = $dm_cache; // Metrics + $r_cache = $dr_cache; // Interim results + $p_cache = $dp_cache; // Functions with parameters + $s_cache = $ds_cache; // Metrics with flag 'spanned' $n_rra = $params['rrd_ds_cnt']; $ds_namv = $params['rras']; - $specific_variables = array('maxValue', 'maxRRDValue'); + $specific_variables = ['maxValue', 'maxRRDValue']; - //Create a cache for every Round Robin Archive + // Create a cache for every Round Robin Archive foreach ($ds_namv as $key => $ds_name) { - $cache[$key] = array($f_cache, $m_cache, $p_cache); + $cache[$key] = [$f_cache, $m_cache, $p_cache]; } - //Use reportit's error handler. + // Use reportit's error handler. set_error_handler('last_error'); global $calculate_handler_set, $calculate_last_formula; @@ -448,7 +483,7 @@ function calculate(&$data, &$params, &$variables, &$df_cache, &$dm_cache, &$dr_c $calculate_handler_set = true; } - //Build the calculation command and execute it + // Build the calculation command and execute it foreach ($m_cache as $k => $m) { debug($cache, 'Main Cache Status: f,m,p'); @@ -459,50 +494,52 @@ function calculate(&$data, &$params, &$variables, &$df_cache, &$dm_cache, &$dr_c debug($cache, 'Main Cache Status: f,m,p'); // Debug - $debug = array(); + $debug = []; - //Formula - $formula = str_replace(array(' ',"\r\n","\n"), '', $m); - $debug[]= $formula; + // Formula + $formula = str_replace([' ', "\r\n", "\n"], '', $m); + $debug[] = $formula; // transform RRA specific variables (maxValue, maxRRDValue) used in that formula - foreach ($specific_variables as $specific_variable){ + foreach ($specific_variables as $specific_variable) { $formula = str_replace($specific_variable, $specific_variable . ':' . $ds_name, $formula); } - $debug[]= $formula; + $debug[] = $formula; - //Replace our variables + // Replace our variables foreach ($variables as $key => $value) { $formula = str_replace($key, $value, $formula); } - $debug[]= $formula; + $debug[] = $formula; - //Replace measurands (spanned) + // Replace measurands (spanned) foreach ($s_cache as $key => $value) { - $pattern = '/(^|[+|\-|*|\/|\(|\)|,| ])'.$key.'([+|\-|*|\/|\(|\)|,| ]|$)/'; + $pattern = '/(^|[+|\-|*|\/|\(|\)|,| ])' . $key . '([+|\-|*|\/|\(|\)|,| ]|$)/'; $formula = preg_replace($pattern, "\${1}$value\${2}", $formula); } - $debug[]= $formula; + $debug[] = $formula; - //Replace interim results first: + // Replace interim results first: foreach ($r_cache as $key => $value) { - if ($value !== false) $formula = str_replace($key, $value, $formula); + if ($value !== false) { + $formula = str_replace($key, $value, $formula); + } } - $debug[]= $formula; + $debug[] = $formula; - //Replace measurands with an existing result if we have one + // Replace measurands with an existing result if we have one foreach ($cache[$i][1] as $key => $value) { - $pattern = '/(^|[+|\-|*|\/|\(|\)|,| ])'.$key.'([+|\-|*|\/|\(|\)|,| ]|$)/'; + $pattern = '/(^|[+|\-|*|\/|\(|\)|,| ])' . $key . '([+|\-|*|\/|\(|\)|,| ]|$)/'; $formula = preg_replace($pattern, "\${1}$value\${2}", $formula); } - $debug[]= $formula; + $debug[] = $formula; - //Replace formula calls + // Replace formula calls foreach ($cache[$i][0][$rra_index] as $key => $value) { if ($value === false) { $formula = str_replace($key, $key . '($data[$rra_index][$i], $cache[$i][0][$rra_index])', $formula); @@ -511,17 +548,17 @@ function calculate(&$data, &$params, &$variables, &$df_cache, &$dm_cache, &$dr_c } } - $debug[]= $formula; + $debug[] = $formula; - //Replace formula calls with parameters + // Replace formula calls with parameters foreach ($cache[$i][2][$rra_index] as $key => $value) { $formula = str_replace($key, $key . '( $data[$rra_index][$i], $cache[$i][2][$rra_index]||', $formula); $formula = str_replace('||(', ', ', $formula); } - $debug[]= $formula; + $debug[] = $formula; - //calculate + // calculate $result = false; $completed = false; @@ -539,45 +576,45 @@ function calculate(&$data, &$params, &$variables, &$df_cache, &$dm_cache, &$dr_c $result = 'NULL'; } - $debug = array(); + $debug = []; $debug[] = $result; debug($debug, 'Result'); - //If its flagged as 'spanned' then update the s_cache, update the main cache - //and jump to the next measurand + // If its flagged as 'spanned' then update the s_cache, update the main cache + // and jump to the next measurand if (array_key_exists($k, $s_cache)) { $s_cache[$k] = $result; - for ($i=0; $i<$n_rra; $i++) { + for ($i = 0; $i < $n_rra; $i++) { unset($cache[$i][1][$k]); } continue 2; } else { - //Update r_cache with the result of our measurand - $name = $k . ':' . $params['rras'][$i]; + // Update r_cache with the result of our measurand + $name = $k . ':' . $params['rras'][$i]; $r_cache[$name] = $result; - //Update main cache with the result of our measurand + // Update main cache with the result of our measurand $cache[$i][1][$k] = $result; } } } - //Clear up and return to main function - $result = array(); + // Clear up and return to main function + $result = []; + foreach ($ds_namv as $i => $ds_name) { $result[$ds_name] = $cache[$i][1]; } - //Add s_cache + // Add s_cache $result['_spanned_'] = $s_cache; - //Fall back to normal error handler + // Fall back to normal error handler restore_error_handler(); debug($cache, 'Main Cache Status: f,m,p'); return $result; } - diff --git a/lib/funct_export.php b/lib/funct_export.php index afd1524..10c422d 100644 --- a/lib/funct_export.php +++ b/lib/funct_export.php @@ -23,7 +23,6 @@ */ function export_to_PDF(&$data) { - } function export_to_CSV(&$data) { @@ -35,12 +34,12 @@ function export_to_CSV(&$data) { $info_line = ''; $tab_head_1 = ''; $tab_head_2 = ''; - $data_sources = array(); + $data_sources = []; - $csv_c_sep = array(',', ';', "\t", ' '); - $csv_d_sep = array(',', '.'); + $csv_c_sep = [',', ';', "\t", ' ']; + $csv_d_sep = [',', '.']; - $measurands = isset_request_var('measurand') ? get_request_var('measurand') : '-1'; + $measurands = isset_request_var('measurand') ? get_request_var('measurand') : '-1'; $datasources = isset_request_var('data_source') ? get_request_var('data_source') : '-1'; $report_ds_alias = $data['report_ds_alias']; @@ -52,55 +51,56 @@ function export_to_CSV(&$data) { $csv_column_s = read_config_option('reportit_csv_column_s'); $csv_decimal_s = read_config_option('reportit_csv_decimal_s'); - /* load user settings */ + // load user settings if ($run_scheduled !== true) { - /* request via web */ + // request via web $no_formatting = 0; - $c_sep = $csv_c_sep[$csv_column_s]; - $d_sep = $csv_d_sep[$csv_decimal_s]; + $c_sep = $csv_c_sep[$csv_column_s]; + $d_sep = $csv_d_sep[$csv_decimal_s]; } else { - /* request via cli */ + // request via cli $no_formatting = 0; - $c_sep = $csv_c_sep[$csv_column_s]; - $d_sep = $csv_d_sep[$csv_decimal_s]; + $c_sep = $csv_c_sep[$csv_column_s]; + $d_sep = $csv_d_sep[$csv_decimal_s]; } - /* plugin version */ + // plugin version $info = plugin_reportit_version(); - /* form the export header */ + // form the export header $header = read_config_option('reportit_exp_header'); - $header = str_replace("", "$eol# Cacti: " . CACTI_VERSION, $header); + $header = str_replace('', "$eol# Cacti: " . CACTI_VERSION, $header); - $header = str_replace("", " ReportIt: " . $info['version'] , $header); + $header = str_replace('', ' ReportIt: ' . $info['version'] , $header); - /* compose additional informations */ - $report_settings = array( + // compose additional informations + $report_settings = [ __('Report title', 'reportit') => "{$report_data['name']}", __('Owner', 'reportit') => "{$report_data['owner']}", __('Template', 'reportit') => "{$report_data['template_name']}", __('Start', 'reportit') => "{$report_data['start_date']}", __('End', 'reportit') => "{$report_data['end_date']}", __('Last Run', 'reportit') => "{$report_data['last_started']}" - ); + ]; $ds_description = explode('|', $report_data['ds_description']); - /* read out data sources */ + // read out data sources if ($datasources > -1) { - $ds_description = array($ds_description[$datasources]); + $ds_description = [$ds_description[$datasources]]; } elseif ($datasources < -1) { - $ds_description = array('overall'); + $ds_description = ['overall']; } - /* read out the result ids */ - list($rs_ids, $rs_cnt) = explode('-', $report_data['rs_def']); - $rs_ids = ($rs_ids == '') ? false : explode('|', $rs_ids); + // read out the result ids + [$rs_ids, $rs_cnt] = explode('-', $report_data['rs_def']); + $rs_ids = ($rs_ids == '') ? false : explode('|', $rs_ids); + if ($measurands != '-1' && $rs_ids !== false) { - $rs_ids = array(get_request_var('measurand')); + $rs_ids = [get_request_var('measurand')]; $rs_cnt = 1; } - /* sort out all measurands which shouldn't be visible */ - if ($rs_ids !== false && cacti_sizeof($rs_ids)>0) { + // sort out all measurands which shouldn't be visible + if ($rs_ids !== false && cacti_sizeof($rs_ids) > 0) { foreach ($rs_ids as $key => $id) { if (!isset($data['report_measurands'][$id]['visible']) || $data['report_measurands'][$id]['visible'] == '') { $rs_cnt--; @@ -110,17 +110,18 @@ function export_to_CSV(&$data) { } if ($datasources < 0) { - /* read out the 'spanned' ids */ - list($ov_ids, $ov_cnt) = explode('-', $report_data['sp_def']); + // read out the 'spanned' ids + [$ov_ids, $ov_cnt] = explode('-', $report_data['sp_def']); $ov_ids = ($ov_ids == '') ? false : explode('|', $ov_ids); + if ($measurands != '-1' && $ov_ids !== false) { - $ov_ids = array(get_request_var('measurand')); + $ov_ids = [get_request_var('measurand')]; $ov_cnt = 1; } - /* sort out all measurands which shouldn't be visible */ - if ($ov_ids !== false && cacti_sizeof($ov_ids)>0) { + // sort out all measurands which shouldn't be visible + if ($ov_ids !== false && cacti_sizeof($ov_ids) > 0) { foreach ($ov_ids as $key => $id) { if (!isset($data['report_measurands'][$id]['visible']) || $data['report_measurands'][$id]['visible'] == '') { $ov_cnt--; @@ -129,49 +130,52 @@ function export_to_CSV(&$data) { } } - if ($measurands == -1 ) { - if ($ov_cnt >0 && !in_array('overall', $ds_description)) { - $ds_description[]= 'overall'; + if ($measurands == -1) { + if ($ov_cnt > 0 && !in_array('overall', $ds_description, true)) { + $ds_description[] = 'overall'; } - } elseif (in_array($measurands, $ov_ids)) { - if ($ov_cnt >0 && !in_array('overall', $ds_description)) { - $ds_description = array('overall'); + } elseif (in_array($measurands, $ov_ids, true)) { + if ($ov_cnt > 0 && !in_array('overall', $ds_description, true)) { + $ds_description = ['overall']; } } } - /* create puffered CSV output */ + // create puffered CSV output ob_start(); - /* report header */ + // report header print "$header $eol"; - /* report settings */ + // report settings print "$eol"; + foreach ($report_settings as $key => $value) { print "# $key: $value $eol"; } - /* defined variables */ + // defined variables print $eol . "# Variables: $eol"; + foreach ($report_variables as $var) { print "# {$var['name']}: {$var['value']} $eol"; } - /* build a legend to explain the abbreviations of measurands */ + // build a legend to explain the abbreviations of measurands print $eol . "# Legend: $eol"; + foreach ($report_measurands as $id) { print "# {$id['abbreviation']}: {$id['name']} $eol"; } - /* print table header */ - for($i = 1; $i < 8; $i++) { + // print table header + for ($i = 1; $i < 8; $i++) { $tab_head_1 .= "$c_sep"; } $tab_head_2 = $tab_head_1; - foreach ($ds_description as $datasource){ + foreach ($ds_description as $datasource) { $name = ($datasource != 'overall') ? $rs_ids : $ov_ids; if ($name !== false) { @@ -181,27 +185,27 @@ function export_to_CSV(&$data) { } else { $tab_head_1 .= $datasource . $c_sep; } - $var = ($datasource != 'overall') ? $datasource.'__'.$id : 'spanned__'.$id; - $tab_head_2 .= $report_measurands[$id]['abbreviation'] . "[" . $report_measurands[$id]['unit'] . "]" . $c_sep; + $var = ($datasource != 'overall') ? $datasource . '__' . $id : 'spanned__' . $id; + $tab_head_2 .= $report_measurands[$id]['abbreviation'] . '[' . $report_measurands[$id]['unit'] . ']' . $c_sep; } } } print $eol . "$tab_head_1 $eol $tab_head_2 $eol"; - /* print results */ - foreach ($report_results as $result){ - $replace = array ($result['start_time'], $result['end_time'], $result['timezone'], $result['start_day'], $result['end_day']); + // print results + foreach ($report_results as $result) { + $replace = [$result['start_time'], $result['end_time'], $result['timezone'], $result['start_day'], $result['end_day']]; $subhead = str_replace($search, $replace, $result['description']); print "\t\t\t$eol"; print '"' . $result['name_cache'] . '"' . $c_sep; - print '"' . $subhead . '"' . $c_sep; - print '"' . $result['start_day'] . '"' . $c_sep; - print '"' . $result['end_day'] . '"' . $c_sep; + print '"' . $subhead . '"' . $c_sep; + print '"' . $result['start_day'] . '"' . $c_sep; + print '"' . $result['end_day'] . '"' . $c_sep; print '"' . $result['start_time'] . '"' . $c_sep; - print '"' . $result['end_time'] . '"' . $c_sep; - print '"' . $result['timezone'] . '"' . $c_sep; + print '"' . $result['end_time'] . '"' . $c_sep; + print '"' . $result['timezone'] . '"' . $c_sep; foreach ($ds_description as $datasource) { $name = ($datasource != 'overall') ? $rs_ids : $ov_ids; @@ -212,11 +216,11 @@ function export_to_CSV(&$data) { $data_type = $report_measurands[$id]['data_type']; $data_precision = $report_measurands[$id]['data_precision']; - $var = ($datasource != 'overall') ? $datasource.'__'.$id : 'spanned__'.$id; + $var = ($datasource != 'overall') ? $datasource . '__' . $id : 'spanned__' . $id; - $value = ($result[$var] == NULL)? 'NA': str_replace(".", $d_sep, (($no_formatting) ? $result[$var] : get_unit($result[$var], $rounding, $data_type, $data_precision) )); + $value = ($result[$var] == null) ? 'NA' : str_replace('.', $d_sep, (($no_formatting) ? $result[$var] : get_unit($result[$var], $rounding, $data_type, $data_precision))); - print '"'. $value .'"' . $c_sep; + print '"' . $value . '"' . $c_sep; } } } @@ -235,7 +239,7 @@ function export_to_XML(&$data) { $output = ''; $header = ''; - $mea = array(); + $mea = []; transform_htmlspecialchars($data); @@ -246,35 +250,35 @@ function export_to_XML(&$data) { $ds_description = explode('|', $report_data['ds_description']); $no_formatting = 0; - /* form the export header */ + // form the export header $header = read_config_option('reportit_exp_header'); $header = str_replace('', "\r\nCacti: " . CACTI_VERSION, $header); - $info = plugin_reportit_version(); + $info = plugin_reportit_version(); $header = str_replace('', ' ReportIt: ' . $info['version'], $header); - /* compose additional informations */ - $report_settings = array( + // compose additional informations + $report_settings = [ 'title' => $report_data['description'], 'owner' => $report_data['owner'], 'template' => $report_data['template_name'], 'start' => $report_data['start_date'], 'end' => $report_data['end_date'], 'last_started' => $report_data['last_started'] - ); + ]; - /* read out the result ids */ - list($rs_ids, $rs_cnt) = explode('-', $report_data['rs_def']); - $rs_ids = ($rs_ids == '') ? false : explode('|', $rs_ids); + // read out the result ids + [$rs_ids, $rs_cnt] = explode('-', $report_data['rs_def']); + $rs_ids = ($rs_ids == '') ? false : explode('|', $rs_ids); - /* read out the 'spanned' ids */ - list($ov_ids, $ov_cnt) = explode('-', $report_data['sp_def']); - $ov_ids = ($ov_ids == '') ? false : explode('|', $ov_ids); + // read out the 'spanned' ids + [$ov_ids, $ov_cnt] = explode('-', $report_data['sp_def']); + $ov_ids = ($ov_ids == '') ? false : explode('|', $ov_ids); - if ($ov_cnt >0) { - $ds_description[]= 'overall'; + if ($ov_cnt > 0) { + $ds_description[] = 'overall'; } - /* create puffered xml output */ + // create puffered xml output ob_start(); print ""; @@ -298,7 +302,7 @@ function export_to_XML(&$data) { print "$eol$eol"; - foreach ($report_measurands as $measurand){ + foreach ($report_measurands as $measurand) { $id = $measurand['id']; $mea[$id]['abbreviation'] = $measurand['abbreviation']; @@ -316,13 +320,13 @@ function export_to_XML(&$data) { print "$eol$eol"; - foreach ($report_results as $result){ - $replace = array ($result['start_time'], $result['end_time'], $result['timezone'], $result['start_day'], $result['end_day']); + foreach ($report_results as $result) { + $replace = [$result['start_time'], $result['end_time'], $result['timezone'], $result['start_day'], $result['end_day']]; $subhead = str_replace($search, $replace, $result['description']); print "$eol"; print "{$result['name_cache']}$eol"; - print "". $subhead . "$eol"; + print '' . $subhead . "$eol"; print "{$result['start_day']}$eol"; print "{$result['end_day']}$eol"; print "{$result['start_time']}$eol"; @@ -344,7 +348,7 @@ function export_to_XML(&$data) { $data_type = $mea[$id]['data_type']; $data_precision = $mea[$id]['data_precision']; - $value = ($value == NULL)? 'NA' : (($no_formatting) ? $value : get_unit($value, $rounding, $data_type, $data_precision) ); + $value = ($value == null) ? 'NA' : (($no_formatting) ? $value : get_unit($value, $rounding, $data_type, $data_precision)); print "<$abbr measurand=\"{$mea[$id]['abbreviation']}\" unit=\"{$mea[$id]['unit']}\">$eol"; print "$value"; print "$eol"; @@ -354,7 +358,7 @@ function export_to_XML(&$data) { print "$eol"; } - print"$eol"; + print "$eol"; print "$eol"; } @@ -373,6 +377,7 @@ function export_to_YAML(&$data) { return yaml_emit(json_decode($report_data, true)); } else { cacti_log('WARNING: You attempted to use YAML as the export format, but PHP is not built using the yaml functions', false, 'REPORTIT'); + return false; } } @@ -380,19 +385,19 @@ function export_to_YAML(&$data) { function export_to_JSON(&$data) { global $search, $run_scheduled; - $json_data = array(); + $json_data = []; $info = plugin_reportit_version(); transform_htmlspecialchars($data); - /* add some header components */ - $json_data['header'] = str_replace(array('', ''), array('Cacti: ' . CACTI_VERSION, 'ReportIt: ' . $info['version']), read_config_option('reportit_exp_header')); + // add some header components + $json_data['header'] = str_replace(['', ''], ['Cacti: ' . CACTI_VERSION, 'ReportIt: ' . $info['version']], read_config_option('reportit_exp_header')); $json_data['version_cacti'] = CACTI_VERSION; $json_data['version_reporit'] = $info['version']; - $mea = array(); + $mea = []; $report_data = $data['report_data']; $report_results = $data['report_results']; @@ -401,26 +406,26 @@ function export_to_JSON(&$data) { $ds_description = explode('|', $report_data['ds_description']); $no_formatting = 0; - /* compose additional informations */ - $report_settings = array( + // compose additional informations + $report_settings = [ 'title' => $report_data['description'], 'owner' => $report_data['owner'], 'template' => $report_data['template_name'], 'start' => $report_data['start_date'], 'end' => $report_data['end_date'], 'last_started' => $report_data['last_started'] - ); + ]; - /* read out the result ids */ - list($rs_ids, $rs_cnt) = explode('-', $report_data['rs_def']); - $rs_ids = ($rs_ids == '') ? false : explode('|', $rs_ids); + // read out the result ids + [$rs_ids, $rs_cnt] = explode('-', $report_data['rs_def']); + $rs_ids = ($rs_ids == '') ? false : explode('|', $rs_ids); - /* read out the 'spanned' ids */ - list($ov_ids, $ov_cnt) = explode('-', $report_data['sp_def']); - $ov_ids = ($ov_ids == '') ? false : explode('|', $ov_ids); + // read out the 'spanned' ids + [$ov_ids, $ov_cnt] = explode('-', $report_data['sp_def']); + $ov_ids = ($ov_ids == '') ? false : explode('|', $ov_ids); if ($ov_cnt > 0) { - $ds_description[]= 'overall'; + $ds_description[] = 'overall'; } foreach ($report_settings as $key => $value) { @@ -428,6 +433,7 @@ function export_to_JSON(&$data) { } $i = 0; + foreach ($report_variables as $variable) { foreach ($variable as $key => $value) { $json_data['variables'][$i][$key] = $value; @@ -436,7 +442,7 @@ function export_to_JSON(&$data) { $i++; } - foreach ($report_measurands as $measurand){ + foreach ($report_measurands as $measurand) { $id = $measurand['id']; $mea[$id]['abbreviation'] = $measurand['abbreviation']; @@ -453,8 +459,8 @@ function export_to_JSON(&$data) { $i = 0; - foreach ($report_results as $result){ - $replace = array ($result['start_time'], $result['end_time'], $result['timezone'], $result['start_day'], $result['end_day']); + foreach ($report_results as $result) { + $replace = [$result['start_time'], $result['end_time'], $result['timezone'], $result['start_day'], $result['end_day']]; $subhead = str_replace($search, $replace, $result['description']); $json_data['data_items']['item'][$i]['description'] = $result['name_cache']; @@ -477,7 +483,7 @@ function export_to_JSON(&$data) { $data_type = $mea[$id]['data_type']; $data_precision = $mea[$id]['data_precision']; - $value = ($value == NULL)? 'NA' : (($no_formatting) ? $value : get_unit($value, $rounding, $data_type, $data_precision) ); + $value = ($value == null) ? 'NA' : (($no_formatting) ? $value : get_unit($value, $rounding, $data_type, $data_precision)); $json_data['data_items']['item'][$i]['results'][$datasource][$abbr]['measurand'] = $mea[$id]['abbreviation']; $json_data['data_items']['item'][$i]['results'][$datasource][$abbr]['unit'] = $mea[$id]['unit']; @@ -495,7 +501,7 @@ function export_to_JSON(&$data) { function export_to_SML(&$data) { $eol = PHP_EOL; - $sml_workbook = "$eol $eol"; - $footer = ""; + $footer = ''; - /* create puffered xml output */ + // create puffered xml output ob_start(); print ""; @@ -533,7 +539,7 @@ function export_to_SML(&$data) { return $output; } -function new_worksheet(&$data, &$styles){ +function new_worksheet(&$data, &$styles) { global $search, $run_scheduled; $eol = PHP_EOL; @@ -542,14 +548,14 @@ function new_worksheet(&$data, &$styles){ $info_line = ''; $tab_head_1 = ''; $tab_head_2 = ''; - $data_sources = array(); - $csv_c_sep = array(',', ';', "\t", ' '); - $csv_d_sep = array(',', '.'); + $data_sources = []; + $csv_c_sep = [',', ';', "\t", ' ']; + $csv_d_sep = [',', '.']; - $measurands = isset_request_var('measurand')? get_request_var('measurand') : '-1'; + $measurands = isset_request_var('measurand') ? get_request_var('measurand') : '-1'; $datasources = isset_request_var('data_source') ? get_request_var('data_source') : '-1'; - /* except serialized data */ + // except serialized data $report_ds_alias = $data['report_ds_alias']; $report_data = $data['report_data']; @@ -558,42 +564,42 @@ function new_worksheet(&$data, &$styles){ $report_variables = $data['report_variables']; $no_formatting = 0; - /* form the export header */ - $info = $info = plugin_reportit_version(); + // form the export header + $info = $info = plugin_reportit_version(); $header = read_config_option('reportit_exp_header'); $header = str_replace('', ' Cacti: ' . CACTI_VERSION, $header); $header = str_replace('', ' ReportIt: ' . $info['version'], $header); - /* compose additional informations */ - $report_settings = array( + // compose additional informations + $report_settings = [ __('Report title', 'reportit') => $report_data['description'], __('Owner', 'reportit') => $report_data['owner'], __('Template', 'reportit') => $report_data['template_name'], __('Start', 'reportit') => $report_data['start_date'], __('End', 'reportit') => $report_data['end_date'], __('Last Run', 'reportit') => $report_data['last_started'] - ); + ]; $ds_description = explode('|', $report_data['ds_description']); - /* read out data sources */ + // read out data sources if ($datasources > -1) { - $ds_description = array($ds_description[$datasources]); + $ds_description = [$ds_description[$datasources]]; } elseif ($datasources < -1) { - $ds_description = array('overall'); + $ds_description = ['overall']; } - /* read out the result ids */ - list($rs_ids, $rs_cnt) = explode('-', $report_data['rs_def']); - $rs_ids = ($rs_ids == '') ? false : explode('|', $rs_ids); + // read out the result ids + [$rs_ids, $rs_cnt] = explode('-', $report_data['rs_def']); + $rs_ids = ($rs_ids == '') ? false : explode('|', $rs_ids); if ($measurands != '-1' && $rs_ids !== false) { - $rs_ids = array(get_request_var('measurand')); + $rs_ids = [get_request_var('measurand')]; $rs_cnt = 1; } - /* sort out all measurands which shouldn't be visible */ - if ($rs_ids !== false && cacti_sizeof($rs_ids)>0) { + // sort out all measurands which shouldn't be visible + if ($rs_ids !== false && cacti_sizeof($rs_ids) > 0) { foreach ($rs_ids as $key => $id) { if (!isset($data['report_measurands'][$id]['visible']) || $data['report_measurands'][$id]['visible'] == '') { $rs_cnt--; @@ -603,17 +609,17 @@ function new_worksheet(&$data, &$styles){ } if ($datasources < 0) { - /* read out the 'spanned' ids */ - list($ov_ids, $ov_cnt) = explode('-', $report_data['sp_def']); - $ov_ids = ($ov_ids == '') ? false : explode('|', $ov_ids); + // read out the 'spanned' ids + [$ov_ids, $ov_cnt] = explode('-', $report_data['sp_def']); + $ov_ids = ($ov_ids == '') ? false : explode('|', $ov_ids); if ($measurands != '-1' && $ov_ids !== false) { - $ov_ids = array(get_request_var('measurand')); + $ov_ids = [get_request_var('measurand')]; $ov_cnt = 1; } - /* sort out all measurands which shouldn't be visible */ - if ($ov_ids !== false && cacti_sizeof($ov_ids)>0) { + // sort out all measurands which shouldn't be visible + if ($ov_ids !== false && cacti_sizeof($ov_ids) > 0) { foreach ($ov_ids as $key => $id) { if (!isset($data['report_measurands'][$id]['visible']) || $data['report_measurands'][$id]['visible'] == '') { $ov_cnt--; @@ -622,58 +628,61 @@ function new_worksheet(&$data, &$styles){ } } - if ($measurands == -1 ) { - if ($ov_cnt >0 && !in_array('overall', $ds_description)) { - $ds_description[]= 'overall'; + if ($measurands == -1) { + if ($ov_cnt > 0 && !in_array('overall', $ds_description, true)) { + $ds_description[] = 'overall'; } - } elseif (in_array($measurands, $ov_ids)) { - if ($ov_cnt >0 && !in_array('overall', $ds_description)) { - $ds_description = array('overall'); + } elseif (in_array($measurands, $ov_ids, true)) { + if ($ov_cnt > 0 && !in_array('overall', $ds_description, true)) { + $ds_description = ['overall']; } } } - /* create puffered CSV output */ + // create puffered CSV output ob_start(); - /* worksheet header */ + // worksheet header print "\t$eol"; print "\t\t$eol"; - /* report header */ + // report header print sml_cell($header, true); - /* report settings */ + // report settings print sml_cell('', true); + foreach ($report_settings as $key => $value) { print sml_cell("# $key: $value", true); } - /* defined variables */ + // defined variables print sml_cell('', true); print sml_cell('# Variables:', true); + foreach ($report_variables as $var) { print sml_cell("# {$var['name']}: {$var['value']}", true); } - /* build a legend to explain the abbreviations of measurands */ + // build a legend to explain the abbreviations of measurands print sml_cell('# Legend:', true); + foreach ($report_measurands as $id) { - print sml_cell ("# {$id['abbreviation']}: {$id['description']}", true); + print sml_cell("# {$id['abbreviation']}: {$id['description']}", true); } - /* print table header */ + // print table header print sml_cell('', true); print "\t\t\t$eol"; - for($i = 1; $i < 8; $i++) { + for ($i = 1; $i < 8; $i++) { $tab_head_1 .= sml_cell(''); } $tab_head_2 = $tab_head_1; - foreach ($ds_description as $datasource){ + foreach ($ds_description as $datasource) { $name = ($datasource != 'overall') ? $rs_ids : $ov_ids; if ($name !== false) { @@ -684,8 +693,8 @@ function new_worksheet(&$data, &$styles){ $tab_head_1 .= sml_cell($datasource); } - $var = ($datasource != 'overall') ? $datasource.'__'.$id : 'spanned__'.$id; - $tab_head_2 .= sml_cell($report_measurands[$id]['abbreviation'] . "[" . $report_measurands[$id]['unit'] . "]"); + $var = ($datasource != 'overall') ? $datasource . '__' . $id : 'spanned__' . $id; + $tab_head_2 .= sml_cell($report_measurands[$id]['abbreviation'] . '[' . $report_measurands[$id]['unit'] . ']'); } } } @@ -693,9 +702,9 @@ function new_worksheet(&$data, &$styles){ print "$eol $tab_head_1\t\t\t$eol\t\t\t$tab_head_2 $eol"; print "\t\t\t$eol"; - /* print results */ - foreach ($report_results as $result){ - $replace = array ($result['start_time'], $result['end_time'], $result['timezone'], $result['start_day'], $result['end_day']); + // print results + foreach ($report_results as $result) { + $replace = [$result['start_time'], $result['end_time'], $result['timezone'], $result['start_day'], $result['end_day']]; $subhead = str_replace($search, $replace, $result['description']); print "\t\t\t$eol"; @@ -712,13 +721,13 @@ function new_worksheet(&$data, &$styles){ if ($name !== false) { foreach ($name as $id) { - $var = ($datasource != 'overall') ? $datasource.'__'.$id : 'spanned__'.$id; - $rounding = $report_measurands[$id]['rounding']; - $data_type = $report_measurands[$id]['data_type']; + $var = ($datasource != 'overall') ? $datasource . '__' . $id : 'spanned__' . $id; + $rounding = $report_measurands[$id]['rounding']; + $data_type = $report_measurands[$id]['data_type']; $data_precision = $report_measurands[$id]['data_precision']; $value = $result[$var]; - $value = ($value == NULL)? 'NA' : (($no_formatting) ? $value : get_unit($value, $rounding, $data_type, $data_precision) ); + $value = ($value == null) ? 'NA' : (($no_formatting) ? $value : get_unit($value, $rounding, $data_type, $data_precision)); print sml_cell($value); } } @@ -727,28 +736,27 @@ function new_worksheet(&$data, &$styles){ print "\t\t\t$eol"; } - /* print worksheet footer */ + // print worksheet footer print "\t\t
$eol"; print "\t
$eol"; return ob_get_clean(); } -function sml_cell($data, $row=false, $styleID=false){ +function sml_cell($data, $row = false, $styleID = false) { $eol = PHP_EOL; $data_style = is_numeric($data) ? " ss:Type='Number'" : " ss:Type='String'"; - $cell_style = ($styleID == false) ? '' : " ss:StyleID='$styleID'"; + $cell_style = ($styleID == false) ? '' : " ss:StyleID='$styleID'"; - /* form cell output */ + // form cell output $cell = "\t\t\t\t$eol\t\t\t\t\t$data$eol\t\t\t\t$eol"; - /* add row tags if required */ - if ($row !==false) { + // add row tags if required + if ($row !== false) { $cell = "\t\t\t$eol" . "$cell" . "\t\t\t$eol"; } return $cell; } - diff --git a/lib/funct_html.php b/lib/funct_html.php index fc5810e..8b6d623 100644 --- a/lib/funct_html.php +++ b/lib/funct_html.php @@ -27,50 +27,51 @@ * generates the links for the measurand configurator to add variables and existing interim results * to the calculation formula * @param int $measurand_id contains the id of the current measurand - * @param int $template_id contains the id of the template which contains the measurand + * @param int $template_id contains the id of the template which contains the measurand */ function html_calc_syntax($measurand_id, $template_id) { global $rubrics; $rubrics[__('Variables', 'reportit')] = get_possible_variables($template_id); - $dq_variables = array_flip(get_possible_data_query_variables($template_id)); + $dq_variables = array_flip(get_possible_data_query_variables($template_id)); $rubrics[__('Data Query Variables', 'reportit')] = $dq_variables; - $interim_results = array_flip(get_interim_results($measurand_id, $template_id, false)); + $interim_results = array_flip(get_interim_results($measurand_id, $template_id, false)); $rubrics[__('Interim Results', 'reportit')] = $interim_results; $output = ''; + foreach ($rubrics as $key => $value) { $output .= "
$key:
"; $measurand = false; foreach ($value as $name => $properties) { - if ( $key == 'Interim Results') { + if ($key == 'Interim Results') { if ($measurand === false) { $measurand = $name; } else { $temp = str_replace($measurand, '', $name); - if (strpos($temp, ':') !== 0 && strlen($name) !== 0 ) { + if (strpos($temp, ':') !== 0 && strlen($name) !== 0) { $output .= '
'; $measurand = $name; } } } - $title = "
" . (isset($properties['title']) ? $properties['title'] : $name) . '
'; + $title = "
" . ($properties['title'] ?? $name) . '
'; if (isset($properties['description'])) { $title .= "

" - . __("Description: %s", $properties['description'], 'reportit') . "
" - . __("Syntax: %s", $properties['syntax'], 'reportit') . "
" - . __("Parameters: %s", $properties['params'], 'reportit') . "
" - . __("Examples: %s", $properties['examples'], 'reportit') . "
"; + . __('Description: %s', $properties['description'], 'reportit') . '
' + . __('Syntax: %s', $properties['syntax'], 'reportit') . '
' + . __('Parameters: %s', $properties['params'], 'reportit') . '
' + . __('Examples: %s', $properties['examples'], 'reportit') . '
'; } - $output .= '' . $name . "  "; + $output .= '' . $name . '  '; } $output .= ''; @@ -80,78 +81,78 @@ function html_calc_syntax($measurand_id, $template_id) { } function html_report_variables($report_id, $template_id) { - //Define some variables - $array = array(); - $form_array_vars = array(); - $input_types = array(1 => 'drop_array', 2 => 'textbox'); + // Define some variables + $array = []; + $form_array_vars = []; + $input_types = [1 => 'drop_array', 2 => 'textbox']; - //Load the possible variables + // Load the possible variables $variables = db_fetch_assoc_prepared('SELECT a.*, b.value FROM plugin_reportit_variables AS a LEFT JOIN plugin_reportit_rvars AS b ON a.id = b.variable_id AND report_id = ? WHERE a.template_id = ?', - array($report_id, $template_id)); + [$report_id, $template_id]); if (count($variables) == 0) { $variables = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_variables WHERE template_id = ?', - array($template_id)); + [$template_id]); } - //Exit if there are no variables necessary for using this template + // Exit if there are no variables necessary for using this template if (count($variables) == 0) { return false; } - //Put the headerline in - $header = array( + // Put the headerline in + $header = [ 'friendly_name' => __('Variables', 'reportit'), 'method' => 'spacer' - ); + ]; $form_array_vars['report_var_header'] = $header; - //Start with a transformation + // Start with a transformation foreach ($variables as $v) { - $value = (isset($v['value']) ? $v['value'] : $v['default_value']); - $method = $input_types[$v['input_type']]; - $index = 'var_' . $v['id']; + $value = ($v['value'] ?? $v['default_value']); + $method = $input_types[$v['input_type']]; + $index = 'var_' . $v['id']; if ($method == 'drop_array') { $i = 0; - $array = array(); + $array = []; $a = $v['min_value']; $b = $v['max_value']; $c = $v['stepping']; - for($i = $a; $i <= $b; $i+=$c) { + for ($i = $a; $i <= $b; $i += $c) { $array[] = strval($i); } - $var = array( + $var = [ 'friendly_name' => ($v['name']), 'method' => $method, 'description' => $v['description'], - 'value' => array_search($value, $array), + 'value' => array_search($value, $array, true), 'array' => $array - ); + ]; - $form_array_vars[$index] = $var; + $form_array_vars[$index] = $var; } else { - $var = array( + $var = [ 'friendly_name' => $v['name'], 'method' => $method, 'description' => $v['description'], 'max_length' => 10, 'value' => $value, 'default' => $v['default_value'] - ); + ]; - $form_array_vars[$index] = $var; + $form_array_vars[$index] = $var; } } @@ -162,15 +163,15 @@ function html_report_variables($report_id, $template_id) { * This function creates the necessary HTML output for several input boxes * displayed in the report template editor, which will be used to define * an alias for every internal data source item. - * @param int $template_id - report template id, if available (new template => 0) - * @param int $data_template_id - internal Cacti id of the used data template + * @param int $template_id - report template id, if available (new template => 0) + * @param int $data_template_id - internal Cacti id of the used data template */ function html_template_ds_alias($template_id, $data_template_id) { - $form_array_alias = array(); - $data_source_items = array(); + $form_array_alias = []; + $data_source_items = []; - /* load information about defined data sources of that data template */ - $data_source_items = db_fetch_assoc_prepared("SELECT a.id, a.data_source_name, + // load information about defined data sources of that data template + $data_source_items = db_fetch_assoc_prepared('SELECT a.id, a.data_source_name, b.data_source_alias, b.id AS enabled FROM data_template_rrd as a LEFT JOIN ( @@ -180,50 +181,50 @@ function html_template_ds_alias($template_id, $data_template_id) { ) AS b ON a.data_source_name = b.data_source_name WHERE a.local_data_id = 0 - AND a.data_template_id = ?", - array($template_id, $data_template_id)); + AND a.data_template_id = ?', + [$template_id, $data_template_id]); - /* create the necessary input field for defining the alias */ + // create the necessary input field for defining the alias if (cacti_sizeof($data_source_items)) { foreach ($data_source_items as $data_source_item) { - $item = array( + $item = [ 'friendly_name' => __('Enable [%s]', $data_source_item['data_source_name'], 'reportit'), 'description' => __('Activate data source item \'%s\' for the calculation process.', $data_source_item['data_source_name'], 'reportit'), 'method' => 'checkbox', 'default' => 'on', 'value' => ($data_source_item['enabled'] == true) ? 'on' : 'off' - ); + ]; $form_array_alias['ds_enabled__' . $data_source_item['id']] = $item; - $var = array( + $var = [ 'friendly_name' => __('Data Source Alias', 'reportit'), 'description' => __('Optional: You can define an alias which should be displayed instead of the internal data source name \'%s\' in the reports.', $data_source_item['data_source_name'], 'reportit'), 'method' => 'textbox', 'max_length' => '25', 'default' => '', - 'value' => ( $data_source_item['data_source_alias'] !== NULL ) ? stripslashes($data_source_item['data_source_alias']) : '', - ); + 'value' => ($data_source_item['data_source_alias'] !== null) ? stripslashes($data_source_item['data_source_alias']) : '', + ]; $form_array_alias['ds_alias__' . $data_source_item['id']] = $var; } } - /* add the alias for the group of separate measurands */ + // add the alias for the group of separate measurands $separate_group_alias = db_fetch_cell_prepared('SELECT data_source_alias FROM plugin_reportit_data_source_items WHERE id = 0 AND template_id = ?', - array($template_id)); + [$template_id]); - $var = array( + $var = [ 'friendly_name' => __('Separate Group Title [overall]', 'reportit'), 'description' => __('Optional: You can define an group name which should be displayed as the title for all separate measurands within the reports.', 'reportit'), 'method' => 'textbox', 'max_length' => '25', 'default' => '', - 'value' => ( $separate_group_alias !== NULL ) ? stripslashes($separate_group_alias) : '', - ); + 'value' => ($separate_group_alias !== null) ? stripslashes($separate_group_alias) : '', + ]; $form_array_alias['ds_alias__0'] = $var; @@ -249,9 +250,8 @@ function html_sources_icon($values, $title_on, $title_off) { $values = count($values); } - $value_text = ($values == NULL ? '' : ' (' . $values . ')'); - $value_on = ($values == NULL ? '' : 'on'); + $value_text = ($values == null ? '' : ' (' . $values . ')'); + $value_on = ($values == null ? '' : 'on'); return html_onoff_icon($values, 'fa-plus', $title_off, 'fa-wrench', $title_on) . $value_text; } - diff --git a/lib/funct_online.php b/lib/funct_online.php index b7a8125..2db7580 100644 --- a/lib/funct_online.php +++ b/lib/funct_online.php @@ -30,26 +30,33 @@ function my_name() { return db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', - array(my_id())); + [my_id()]); } -function my_report($report_id, $public = false){ +function my_report($report_id, $public = false) { if (is_numeric($report_id) && $report_id != 0) { $user_id = my_id(); - $user = db_fetch_row_prepared("SELECT user_id, public + $user = db_fetch_row_prepared('SELECT user_id, public FROM plugin_reportit_reports - WHERE id = ?", - array($report_id)); + WHERE id = ?', + [$report_id]); if ($user == false) { - if (!re_admin()) die_html_custom_error('Permission denied'); - die_html_custom_error('Not existing'); + if (!re_admin()) { + die_html_custom_error('Permission denied'); + } + die_html_custom_error('Not existing'); } if ($user_id !== $user['user_id']) { - if (re_admin()) return; - if ($public && $user['public'] == 'on') return; + if (re_admin()) { + return; + } + + if ($public && $user['public'] == 'on') { + return; + } die_html_custom_error('Permission denied'); } } @@ -59,14 +66,14 @@ function my_template($report_id) { return db_fetch_cell_prepared('SELECT template_id FROM plugin_reportit_reports WHERE id = ?', - array($report_id)); + [$report_id]); } -function locked($template_id, $header=true) { - $status = db_fetch_cell_prepared("SELECT locked +function locked($template_id, $header = true) { + $status = db_fetch_cell_prepared('SELECT locked FROM plugin_reportit_templates - WHERE id = ?", - array($template_id)); + WHERE id = ?', + [$template_id]); if ($status) { die_html_custom_error('Template has been locked', true); @@ -74,7 +81,7 @@ function locked($template_id, $header=true) { } function other_name($userid) { - return db_fetch_cell_prepared("SELECT username FROM user_auth WHERE id = ?", array($userid)); + return db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', [$userid]); } function only_viewer() { @@ -83,8 +90,8 @@ function only_viewer() { $report_viewer = db_fetch_cell("SELECT * FROM user_auth_realm WHERE user_id = $id - AND (realm_id = " . REPORTIT_USER_ADMIN . " - OR realm_id = " . REPORTIT_USER_OWNER . ")"); + AND (realm_id = " . REPORTIT_USER_ADMIN . ' + OR realm_id = ' . REPORTIT_USER_OWNER . ')'); if ($report_viewer == null || substr_count($_SERVER['REQUEST_URI'], 'view.php')) { return true; @@ -93,7 +100,7 @@ function only_viewer() { } } -function user_auth_realm($realm_id, $user_id){ +function user_auth_realm($realm_id, $user_id) { $verified = db_fetch_cell(' SELECT user_auth.id FROM user_auth LEFT JOIN ( @@ -107,10 +114,11 @@ function user_auth_realm($realm_id, $user_id){ ) AS group_member ON group_member.user_id = user_auth.id WHERE user_auth.id = ' . $user_id . ' AND (group_member.user_id IS NOT NULL OR user_realm.user_id IS NOT NULL)' ); + return ($verified) ? true : false; } -function re_owner(){ +function re_owner() { return user_auth_realm(REPORTIT_USER_OWNER, my_id()) ? true : false; } @@ -118,13 +126,11 @@ function re_admin() { return user_auth_realm(REPORTIT_USER_ADMIN, my_id()) ? true : false; } -function session_custom_error_message($field, $custom_message, $toplevel_message=2) { +function session_custom_error_message($field, $custom_message, $toplevel_message = 2) { $_SESSION['sess_error_fields'][$field] = $field; - //Do not overwrite the first message. - if (!isset($_SESSION['sess_custom_error'])) { - $_SESSION['sess_custom_error'] = $custom_message; - } + // Do not overwrite the first message. + $_SESSION['sess_custom_error'] ??= $custom_message; if (!isset($_SESSION['sess_messages']) && $toplevel_message !== false) { raise_message($toplevel_message); @@ -139,19 +145,18 @@ function session_custom_error_display() { } function is_error_message_field($field) { - if (isset($_SESSION['sess_error_fields'][$field])) { return true; } else { - return false; + return false; } } function stat_autolock_template($template_id) { - $count = db_fetch_cell_prepared("SELECT COUNT(*) + $count = db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_reportit_measurands - WHERE template_id = ?", - array($template_id)); + WHERE template_id = ?', + [$template_id]); if ($count != 0) { return false; @@ -164,15 +169,15 @@ function set_autolock_template($template_id) { db_execute_prepared('UPDATE plugin_reportit_templates SET locked=1 WHERE id = ?', - array($template_id)); + [$template_id]); } function update_formulas($array) { - foreach($array as $key => $value) { + foreach ($array as $key => $value) { db_execute_prepared('UPDATE plugin_reportit_measurands SET calc_formula = ? WHERE id = ?', - array($value['calc_formula'], $value['id'])); + [$value['calc_formula'], $value['id']]); } } @@ -181,17 +186,18 @@ function try_autolock_template($template_id) { FROM plugin_reportit_reports WHERE template_id = ? AND state = 1', - array($template_id)); + [$template_id]); if ($status == 0) { set_autolock_template($template_id); + return true; } else { return false; } } -function check_cacti_version($hash){ +function check_cacti_version($hash) { global $hash_version_codes; if ($hash_version_codes[CACTI_VERSION] < $hash) { @@ -201,27 +207,28 @@ function check_cacti_version($hash){ } } -function check_graph_support(){ - /* Check required PHP extensions: GD Library and Freetype support */ +function check_graph_support() { + // Check required PHP extensions: GD Library and Freetype support $loaded_extensions = get_loaded_extensions(); - if (!in_array('gd', $loaded_extensions)) { - die_html_custom_error("GD library not available - Check your systems configuration", true); + + if (!in_array('gd', $loaded_extensions, true)) { + die_html_custom_error('GD library not available - Check your systems configuration', true); } $gd_info = gd_info(); - if (!$gd_info["FreeType Support"]) { - die_html_custom_error("GD Freetype Support not available - Check your systems configuration", true); + + if (!$gd_info['FreeType Support']) { + die_html_custom_error('GD Freetype Support not available - Check your systems configuration', true); } } -function get_valid_max_rows(){ - /* return the default if a user defined an invalid value for maximum number of rows */ - $session_max_rows = read_graph_config_option("reportit_max_rows"); +function get_valid_max_rows() { + // return the default if a user defined an invalid value for maximum number of rows + $session_max_rows = read_graph_config_option('reportit_max_rows'); if (is_numeric($session_max_rows) && $session_max_rows > 0) { return $session_max_rows; } else { - return read_default_graph_config_option("reportit_max_rows"); + return read_default_graph_config_option('reportit_max_rows'); } } - diff --git a/lib/funct_reports.php b/lib/funct_reports.php index 2e1f682..091605d 100644 --- a/lib/funct_reports.php +++ b/lib/funct_reports.php @@ -26,76 +26,76 @@ function api_reportit_disable_report($id) { db_execute_prepared('UPDATE plugin_reportit_reports SET enabled = "" WHERE id = ?', - array($id)); + [$id]); } function api_reportit_enable_report($id) { db_execute_prepared('UPDATE plugin_reportit_reports SET enabled = "on" WHERE id = ?', - array($id)); + [$id]); } function api_reportit_delete_report($id) { $counter_data_items += db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_reportit_data_items WHERE report_id = ?', - array($id)); + [$id]); - db_execute_prepared('DELETE FROM plugin_reportit_reports WHERE id = ?', array($id)); - db_execute_prepared('DELETE FROM plugin_reportit_presets WHERE id = ?', array($id)); - db_execute_prepared('DELETE FROM plugin_reportit_rvars WHERE report_id = ?', array($id)); - db_execute_prepared('DELETE FROM plugin_reportit_recipients WHERE report_id = ?', array($id)); - db_execute_prepared('DELETE FROM plugin_reportit_data_items WHERE report_id = ?', array($id)); + db_execute_prepared('DELETE FROM plugin_reportit_reports WHERE id = ?', [$id]); + db_execute_prepared('DELETE FROM plugin_reportit_presets WHERE id = ?', [$id]); + db_execute_prepared('DELETE FROM plugin_reportit_rvars WHERE report_id = ?', [$id]); + db_execute_prepared('DELETE FROM plugin_reportit_recipients WHERE report_id = ?', [$id]); + db_execute_prepared('DELETE FROM plugin_reportit_data_items WHERE report_id = ?', [$id]); db_execute('DROP TABLE IF EXISTS plugin_reportit_results_' . $id); } function api_reportit_duplicate_report($id, $addition) { - /* ================= input validation ================= */ + // ================= input validation ================= input_validate_input_number($id); - /* ==================================================== */ + // ==================================================== $report_data = db_fetch_row_prepared('SELECT * FROM plugin_reportit_reports - WHERE id = ?', array($id)); + WHERE id = ?', [$id]); $report_data['id'] = 0; - $report_data['name'] = str_replace("", $report_data['name'], $addition); + $report_data['name'] = str_replace('', $report_data['name'], $addition); $new_id = sql_save($report_data, 'plugin_reportit_reports'); - //Copy original rrdlist table to new rrdlist table + // Copy original rrdlist table to new rrdlist table $data_items = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_data_items WHERE report_id = ?', - array($id)); + [$id]); if (cacti_sizeof($data_items)) { - foreach($data_items as $data_item) { + foreach ($data_items as $data_item) { $data_item['report_id'] = $new_id; - sql_save($data_item, 'plugin_reportit_data_items', array('id', 'report_id'), false); + sql_save($data_item, 'plugin_reportit_data_items', ['id', 'report_id'], false); } } - /* duplicate the presets settings */ + // duplicate the presets settings $report_presets = db_fetch_row_prepared('SELECT * FROM plugin_reportit_presets WHERE id = ?', - array($id)); + [$id]); $report_presets['id'] = $new_id; sql_save($report_presets, 'plugin_reportit_presets', 'id', false); - /* duplicate list of recipients */ + // duplicate list of recipients $report_recipients = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_recipients WHERE report_id = ?', - array($id)); + [$id]); if (cacti_sizeof($report_recipients)) { - foreach($report_recipients as $recipient) { - $recipient['id'] = 0; + foreach ($report_recipients as $recipient) { + $recipient['id'] = 0; $recipient['report_id'] = $new_id; sql_save($recipient, 'plugin_reportit_recipients'); @@ -106,9 +106,9 @@ function api_reportit_duplicate_report($id, $addition) { function api_reportit_run_report($id) { $php_binary = read_config_option('path_php_binary'); - /* ================= input validation ================= */ + // ================= input validation ================= input_validate_input_number($id); - /* ==================================================== */ + // ==================================================== if ($id > 0) { exec_background($php_binary, CACTI_PATH_BASE . '/plugins/reportit/poller_reportit.php --report-id=' . $id); @@ -116,7 +116,7 @@ function api_reportit_run_report($id) { } function api_reportit_take_ownership($id, $user) { - db_execute_prepared('UPDATE plugin_reportit_reports SET user_id = ? WHERE id = ?', array($user, $id)); + db_execute_prepared('UPDATE plugin_reportit_reports SET user_id = ? WHERE id = ?', [$user, $id]); } function api_reportit_remove_data_sources($id, $items) { @@ -124,35 +124,35 @@ function api_reportit_remove_data_sources($id, $items) { FROM plugin_reportit_data_items WHERE report_id = ? AND ' . array_to_sql_or($items, 'id'), - array($id)); + [$id]); if (cacti_sizeof($rrdlist_datas)) { foreach ($rrdlist_datas as $rrdlist_data) { db_execute_prepared('DELETE FROM plugin_reportit_data_items WHERE report_id = ? AND id = ?', - array($id, $rrdlist_data['id'])); + [$id, $rrdlist_data['id']]); } } } function api_reportit_add_data_source($id) { - $enable_tmz = read_config_option('reportit_use_tmz'); - $tmz = ($enable_tmz) ? "'GMT'" : "'".date('T')."'"; - $columns = ''; - $values = ''; - $rrd = ''; + $enable_tmz = read_config_option('reportit_use_tmz'); + $tmz = ($enable_tmz) ? "'GMT'" : "'" . date('T') . "'"; + $columns = ''; + $values = ''; + $rrd = ''; - /* load data item presets */ + // load data item presets $presets = db_fetch_row_prepared('SELECT * FROM plugin_reportit_presets WHERE id = ?', - array($id)); + [$id]); if (cacti_sizeof($presets)) { $presets['report_id'] = $id; - foreach($presets as $key => $value) { + foreach ($presets as $key => $value) { $columns .= ', ' . $key; if ($key != 'id') { @@ -164,31 +164,30 @@ function api_reportit_add_data_source($id) { $values .= ', ' . db_qstr($id); } - foreach($selected_items as $rd) { + foreach ($selected_items as $rd) { $rrd .= "($rd $values),"; } - $rrd = substr($rrd, 0, strlen($rrd)-1); + $rrd = substr($rrd, 0, strlen($rrd) - 1); $columns = substr($columns, 1); - /* save */ + // save db_execute("REPLACE INTO plugin_reportit_data_items ($columns) VALUES $rrd"); } function api_reportit_update_data_source($id, $reference_items) { - $reference_items = unserialize(stripslashes($reference_items), array('allowed_classes' => false)); + $reference_items = unserialize(stripslashes($reference_items), ['allowed_classes' => false]); - db_execute_prepared("UPDATE plugin_reportit_data_items + db_execute_prepared('UPDATE plugin_reportit_data_items SET start_day = ?, end_day = ?, start_time = ?, end_time = ?, timezone = ? - WHERE report_id = ?", - array( + WHERE report_id = ?', + [ $reference_items[0]['start_day'], $reference_items[0]['end_day'], $reference_items[0]['start_time'], $reference_items[0]['end_time'], $reference_items[0]['timezone'], $id - ) + ] ); } - diff --git a/lib/funct_runtime.php b/lib/funct_runtime.php index 1a0369d..04faa7c 100644 --- a/lib/funct_runtime.php +++ b/lib/funct_runtime.php @@ -34,19 +34,19 @@ function create_result_table($report_id) { SELECT `id` FROM plugin_reportit_data_items WHERE report_id = ?", - array($report_id)); + [$report_id]); } function get_report_definitions($report_id) { global $consolidation_functions; - $report_definition = array(); + $report_definition = []; // Fetch report's definition $report = db_fetch_row_prepared('SELECT * FROM plugin_reportit_reports WHERE id = ?', - array($report_id)); + [$report_id]); // Fetch all RRD definitions $data_items = db_fetch_assoc_prepared('SELECT @@ -62,7 +62,7 @@ function get_report_definitions($report_id) { WHERE a.report_id = ? GROUP BY a.id ORDER BY a.id', - array($report_id)); + [$report_id]); // Fetch all high counters $high_counters = db_fetch_assoc_prepared('SELECT c.field_value as maxHighValue, a.id @@ -76,13 +76,13 @@ function get_report_definitions($report_id) { AND c.field_name="ifHighSpeed" WHERE a.report_id = ? ORDER BY a.id', - array($report_id)); + [$report_id]); // Fetch all template informations $template = db_fetch_row_prepared('SELECT * FROM plugin_reportit_templates WHERE id = ?', - array($report['template_id'])); + [$report['template_id']]); // Fetch all all data source items $sql = 'SELECT data_source_name @@ -109,12 +109,12 @@ function get_report_definitions($report_id) { AND rdi.report_id = ? AND dtr.data_source_name = ? ORDER BY rdi.id', - array($template['data_template_id'], $report_id, $data_source_name)); + [$template['data_template_id'], $report_id, $data_source_name]); - $fin_results = array(); + $fin_results = []; if (cacti_sizeof($temp_results)) { - foreach($temp_results as $r) { + foreach ($temp_results as $r) { $pre = $r['maxRRDValue']; if (strpos($pre, '|') !== false) { @@ -123,7 +123,7 @@ function get_report_definitions($report_id) { $post = $pre; } - $fin_results[] = array('id' => $r['id'], 'maxRRDValue' => $post); + $fin_results[] = ['id' => $r['id'], 'maxRRDValue' => $post]; } } @@ -135,12 +135,13 @@ function get_report_definitions($report_id) { FROM plugin_reportit_measurands WHERE template_id = ? ORDER BY id', - array($report['template_id'])); + [$report['template_id']]); // filter out all used consolidation function - $cf = array(); + $cf = []; + if (cacti_sizeof($measurands)) { - foreach ($measurands as $measurand) { + foreach ($measurands as $measurand) { $cf[$measurand['cf']] = $consolidation_functions[$measurand['cf']]; } } @@ -149,14 +150,14 @@ function get_report_definitions($report_id) { $rvars = db_fetch_assoc_prepared('SELECT variable_id AS id, value FROM plugin_reportit_rvars WHERE report_id = ?', - array($report_id)); + [$report_id]); // Fetch the data_source_type $tmp = db_fetch_row_prepared('SELECT DISTINCT data_source_type_id AS ds_type, rrd_maximum AS maximum FROM data_template_rrd WHERE data_template_id = ? AND local_data_id = 0', - array($template['data_template_id'])); + [$template['data_template_id']]); $template['ds_type'] = $tmp['ds_type']; $template['maximum'] = $tmp['maximum']; @@ -166,7 +167,7 @@ function get_report_definitions($report_id) { FROM data_template_data WHERE data_template_id = ? AND local_data_id = 0', - array($template['data_template_id'])); + [$template['data_template_id']]); // Fetch RRA definitions $template['RRA'] = db_fetch_assoc('SELECT steps, timespan @@ -175,13 +176,14 @@ function get_report_definitions($report_id) { ORDER BY timespan'); // Rebuild the variables - $variables = array(); + $variables = []; + foreach ($rvars as $key => $value) { - $name = 'c' . $value['id'] .'v'; + $name = 'c' . $value['id'] . 'v'; $variables[$name] = $value['value']; } - //Construct the return-array 'report_definitions' + // Construct the return-array 'report_definitions' $report_definitions['report'] = $report; $report_definitions['data_items'] = $data_items; $report_definitions['high_counters'] = $high_counters; @@ -197,38 +199,44 @@ function get_report_definitions($report_id) { function day_to_number($day) { switch($day) { - case __('Monday', 'reportit'): - return 1; - break; - case __('Tuesday', 'reportit'): - return 2; - break; - case __('Wednesday', 'reportit'): - return 3; - break; - case __('Thursday', 'reportit'): - return 4; - break; - case __('Friday', 'reportit'): - return 5; - break; - case __('Saturday', 'reportit'): - return 6; - break; - case __('Sunday', 'reportit'): - return 7; - break; + case __('Monday', 'reportit'): + return 1; + + break; + case __('Tuesday', 'reportit'): + return 2; + + break; + case __('Wednesday', 'reportit'): + return 3; + + break; + case __('Thursday', 'reportit'): + return 4; + + break; + case __('Friday', 'reportit'): + return 5; + + break; + case __('Saturday', 'reportit'): + return 6; + + break; + case __('Sunday', 'reportit'): + return 7; + + break; } } function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_duration, $rrd_sp, $rrd_ep, $rrd_step, $rrd_ds_cnt, $dst_support) { - /** * ----------------------------------------------------------------------------------------------------------- * Calculate all included weekdays * For a great report duration it's more efficient to use time vectors instead of 'get weekday function' - + * * Variables: * $wdays => includes all ids of weekdays which are include * $dis => means the distance vector for all included days @@ -242,8 +250,8 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d switch ($startday) { case $startday == $endday: // e.g. 'Monday till Monday => includes only Monday!' $wdays[] = ($startday == 7) ? 0 : $startday; - $dis = 0; - $off = 7; + $dis = 0; + $off = 7; break; case $startday < $endday: // e.g. 'Monday till Friday => includes Mo, Tu, Wed, Thu and Fr @@ -280,13 +288,13 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d // boost the calculation if all weekdays are required and step or shift are covering the whole day if (($dis == 6 && $off == 1 && $shift_duration == 86400) || ($dis == 6 && $off == 1 && $rrd_step == 86400)) { - $rrd_ad_data['index'][0] = abs(($rrd_ep-($rrd_sp-$rrd_step))/$rrd_step); + $rrd_ad_data['index'][0] = abs(($rrd_ep - ($rrd_sp - $rrd_step)) / $rrd_step); return $rrd_ad_data; } // ----- Calculate number of rrd_steps for enclosing a 'normal' shift ----- - $rrd_ad_data['steps'] = abs(ceil($shift_duration/$rrd_step)); + $rrd_ad_data['steps'] = abs(ceil($shift_duration / $rrd_step)); // ------------------------------------------------------------------------ // ----- Calculate all starting points which will be included in report duration ----- @@ -297,7 +305,7 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d for ($f_sp; $f_sp <= $l_sp; $f_sp += 86400, $date = getdate($f_sp)) { // Number of steps - $steps = $rrd_ad_data['steps']; + $steps = $rrd_ad_data['steps']; $tmz_change = false; // If the timezone changes between the current and the following day than... @@ -305,7 +313,7 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d $nextday = getdate($f_sp + 86400); if ($date['hours'] != $nextday['hours']) { - $tmz_change = $date['hours']-$nextday['hours']; + $tmz_change = $date['hours'] - $nextday['hours']; if ($tmz_change < -1) { $tmz_change += 24; @@ -314,26 +322,27 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d // ...check if there is a change during the shift $shift_ep = $f_sp + $shift_duration; $shift_end = getdate($shift_ep); + if ($shift_end['hours'] != $e_hour) { // ...than modify its endpoint - $shift_ep += $tmz_change*3600; + $shift_ep += $tmz_change * 3600; } } } // Memorize the correct index number if the current wday matches and ... - if (in_array($date['wday'], $wdays)) { + if (in_array($date['wday'], $wdays, true)) { // ...calculate start point's index - $index = floor(($f_sp - $rrd_sp)/$rrd_step+1); + $index = floor(($f_sp - $rrd_sp) / $rrd_step + 1); // ...if the tmz has been changed calculate the new number of rrd_steps if ($tmz_change) { - $steps = floor(($shift_ep - $rrd_sp)/$rrd_step+1) - $index; + $steps = floor(($shift_ep - $rrd_sp) / $rrd_step + 1) - $index; } // ...check if the number of steps is to high (Option: "Down to present day") - if ($rrd_ep < $f_sp + $steps*$rrd_step) { - $steps = floor(($rrd_ep - $rrd_sp)/$rrd_step+1) - $index; + if ($rrd_ep < $f_sp + $steps * $rrd_step) { + $steps = floor(($rrd_ep - $rrd_sp) / $rrd_step + 1) - $index; } // ...save the index and the number of rrd_steps for enclosing the current shift @@ -347,7 +356,7 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d // ...correct the start point if we found one change of tmz if ($tmz_change) { - $f_sp += $tmz_change*3600; + $f_sp += $tmz_change * 3600; } } @@ -356,8 +365,8 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d // Using time vectors until end is reached. // Set preconditions - $offs = 0; - $ldis = 0; + $offs = 0; + $ldis = 0; $tmz_change = false; // Information about the last connection point @@ -374,7 +383,7 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d $offs++; // Distance: Start searching important timestamps - for ($f_sp, $i=$dis; $f_sp <= $l_sp AND $i>=0; $f_sp+=86400, $i--) { + for ($f_sp, $i = $dis; $f_sp <= $l_sp && $i >= 0; $f_sp += 86400, $i--) { $date = getdate($f_sp); // Number of steps @@ -386,7 +395,7 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d $nextday = getdate($f_sp + 86400); if ($date['hours'] != $nextday['hours']) { - $tmz_change = $date['hours']-$nextday['hours']; + $tmz_change = $date['hours'] - $nextday['hours']; if ($tmz_change < -1) { $tmz_change += 24; @@ -398,28 +407,28 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d if ($shift_end['hours'] != $e_hour) { // ...than modify its endpoint - $shift_ep += $tmz_change*3600; + $shift_ep += $tmz_change * 3600; } } } // Memorize the correct index number: // ...calculate start point's index - $index = floor(($f_sp - $rrd_sp)/$rrd_step+1); + $index = floor(($f_sp - $rrd_sp) / $rrd_step + 1); // ...if the tmz has been changed calculate the new number of rrd_steps if ($tmz_change) { - $steps = floor(($shift_ep - $rrd_sp)/$rrd_step+1) - $index; + $steps = floor(($shift_ep - $rrd_sp) / $rrd_step + 1) - $index; } // ...check if the number of steps is to high (Option: "Down to present day") - if ($rrd_ep < $f_sp + $steps*$rrd_step) { - $steps = floor(($rrd_ep - $rrd_sp)/$rrd_step+1) - $index; + if ($rrd_ep < $f_sp + $steps * $rrd_step) { + $steps = floor(($rrd_ep - $rrd_sp) / $rrd_step + 1) - $index; } // ...correct the start point if we found one change of tmz if ($tmz_change) { - $f_sp += $tmz_change*3600; + $f_sp += $tmz_change * 3600; } // ...update $date @@ -432,7 +441,7 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d $ldis++; // Break out if $l_sp has been exceeded - if ($f_sp > $l_sp){ + if ($f_sp > $l_sp) { if ($ldis == 0) { $offs--; } @@ -463,23 +472,23 @@ function get_type_of_request($startday, $endday, $f_sp, $l_sp, $e_hour, $shift_d } function get_prepared_data(&$rrd_data, &$rrd_ad_data, $rrd_ds_cnt, $ds_type, $corr_factor_start, $corr_factor_end, &$ds_namv, &$rrd_nan) { - for ($i = 0; $i<$rrd_ds_cnt; $i++) { + for ($i = 0; $i < $rrd_ds_cnt; $i++) { if (!array_key_exists($i, $ds_namv)) { continue; } - //Create the indexes and read the values of all startpoints + // Create the indexes and read the values of all startpoints foreach ($rrd_ad_data['index'] as $key => $steps) { $index = $key * $rrd_ds_cnt + $i; - //Correct the value automatically if it's needfully (Type 'Counter' only) + // Correct the value automatically if it's needfully (Type 'Counter' only) $data[$i][$index] = $rrd_data[$index]; $multi[$i][$index] = ($ds_type == 2 && !is_nan($rrd_data[$index])) ? $corr_factor_start : 1; - //If value stands for one day it has to be the last one, too - $number = $index; + // If value stands for one day it has to be the last one, too + $number = $index; - //Create the indizes of steps which defines the following shift + // Create the indizes of steps which defines the following shift for ($k = 1; $k < $steps; $k++) { $number = $index + $k * $rrd_ds_cnt; @@ -489,17 +498,17 @@ function get_prepared_data(&$rrd_data, &$rrd_ad_data, $rrd_ds_cnt, $ds_type, $co } } - //Correct the latest shift value if needfully (Type 'Counter' only) + // Correct the latest shift value if needfully (Type 'Counter' only) if ($ds_type == 2 && !is_nan($rrd_data[$index])) { - //are measured values for start and end the same one? - $x = ($index == $number)? $corr_factor_start + $corr_factor_end -1 : $corr_factor_end; - $multi[$i][$number] = $x; + // are measured values for start and end the same one? + $x = ($index == $number) ? $corr_factor_start + $corr_factor_end - 1 : $corr_factor_end; + $multi[$i][$number] = $x; } else { $multi[$i][$number] = 1; } } - //Remove all NAN's + // Remove all NAN's foreach ($data[$i] as $key => $value) { if (is_nan($value) || is_null($value)) { unset($data[$i][$key]); @@ -509,8 +518,8 @@ function get_prepared_data(&$rrd_data, &$rrd_ad_data, $rrd_ds_cnt, $ds_type, $co } } - /* add $multi to return data */ - //$data['x'] = $multi; + // add $multi to return data + // $data['x'] = $multi; return $data; } @@ -520,39 +529,40 @@ function strtoNaN(&$value) { } function transform(&$data, &$rrd_data, &$template) { - //Transform into the 'normal' form: + // Transform into the 'normal' form: $ds_names = substr($data, 0, strpos($data, PHP_EOL)); $ds_names = str_replace('timestamp', '', $ds_names); - debug($ds_names, "Data sources"); + debug($ds_names, 'Data sources'); $data = substr($data, strpos($data, PHP_EOL)); preg_match_all('/\S+/', $ds_names, $rrd_data); - debug($rrd_data, "Preg_match_all"); + debug($rrd_data, 'Preg_match_all'); $rrd_data['ds_namv'] = array_shift($rrd_data); $rrd_data['ds_cnt'] = count($rrd_data['ds_namv']); - debug($rrd_data, "Preg_match_all - Result"); + debug($rrd_data, 'Preg_match_all - Result'); preg_match_all('/\S+/', $data, $data); $zahl = count($data[0]); $last_timestamp = $zahl - $rrd_data['ds_cnt'] - 1; - /* catch a cases with a missing data source */ + // catch a cases with a missing data source if (!isset($data[0]) || !cacti_sizeof($data[0])) { return false; } - //cacti_log('Data Size:' . cacti_sizeof($data[0]) . ', RRD Size:' . cacti_sizeof($rrd_data)); + // cacti_log('Data Size:' . cacti_sizeof($data[0]) . ', RRD Size:' . cacti_sizeof($rrd_data)); $rrd_data['start'] = substr($data[0][0], 0, -1); $rrd_data['end'] = substr($data[0][$last_timestamp], 0, -1); - //The step is needed, so if we've only one timespan then do this: + // The step is needed, so if we've only one timespan then do this: if ($rrd_data['start'] == $rrd_data['end']) { - $diff = time()-$rrd_data['start']; + $diff = time() - $rrd_data['start']; $i = 0; + foreach ($template['RRA'] as $key => $array) { if ($diff > $array['timespan']) { $i++; @@ -570,10 +580,11 @@ function transform(&$data, &$rrd_data, &$template) { $a = 0; $step_value = 0; + if (isset($step)) { $step_value = $step; } else { - $step_value = $data[0][$b+1]; + $step_value = $data[0][$b + 1]; } if (!is_numeric($step_value)) { @@ -583,8 +594,8 @@ function transform(&$data, &$rrd_data, &$template) { $rrd_data['step'] = $step_value - $rrd_data['start']; $rrd_data['start'] -= $rrd_data['step']; - //Delete all timestamps - while($a < $zahl) { + // Delete all timestamps + while ($a < $zahl) { unset($data[0][$a]); $a += $b + 1; } @@ -596,37 +607,36 @@ function transform(&$data, &$rrd_data, &$template) { } function check_DST_support() { - $tmz = date('T'); + $tmz = date('T'); $return = ($tmz == 'UTC' || $tmz == 'GMT' || $tmz == 'UCT') ? false : true; return $return; } -function check_rra_header(&$rra_data){ - +function check_rra_header(&$rra_data) { } function reportit_prepare_store_report_results($report_id, $queue_id = 0, $start_time = false) { $report = db_fetch_row_prepared('SELECT * FROM plugin_reportit_reports WHERE id = ?', - array($report_id)); + [$report_id]); - $attachments = array(); + $attachments = []; $data = get_prepared_report_data($report_id, 'export'); - $search = array('|title|', '|period|'); - $replace = array($report['name'], $report['start_date'] . '-' . $report['end_date']); + $search = ['|title|', '|period|']; + $replace = [$report['name'], $report['start_date'] . '-' . $report['end_date']]; $subject = ($report['email_subject'] != '') ? $report['email_subject'] : 'Scheduled report - |title| - |period|'; $subject = str_replace($search, $replace, $subject); $filename = ''; - /* very simple Email body for now. */ - $body = ($report['email_body'] != '') ? $report['email_body'] : 'This is a scheduled report generated from Cacti.'; + // very simple Email body for now. + $body = ($report['email_body'] != '') ? $report['email_body'] : 'This is a scheduled report generated from Cacti.'; $format = ($report['email_format'] != '') ? $report['email_format'] : 'CSV'; $body_html = $body; - /* load list of recipients */ + // load list of recipients $file_type = ($format != 'SML') ? strtolower($format) : 'xml'; $mime_type = ($format != 'SML') ? 'application/' . strtolower($format) : 'application/vnd-ms-excel'; @@ -637,7 +647,7 @@ function reportit_prepare_store_report_results($report_id, $queue_id = 0, $start } if ($format != 'None') { - /* define additional attachment settings */ + // define additional attachment settings $filebase = read_config_option('reportit_exp_filename'); if (empty($filebase)) { @@ -645,6 +655,7 @@ function reportit_prepare_store_report_results($report_id, $queue_id = 0, $start } $dirbase = dirname($filebase); + if (empty($dirbase) || $dirbase == '.') { $dirbase = sys_get_temp_dir(); } @@ -655,15 +666,15 @@ function reportit_prepare_store_report_results($report_id, $queue_id = 0, $start print "Attachment: $filename\n"; - /* load export data and define the attachment file */ + // load export data and define the attachment file if (function_exists($export_function)) { $export_data = $export_function($data); - $attachments[] = array( + $attachments[] = [ 'attachment' => $filename, 'mime_type' => $mime_type, 'inline' => 'attachment', - ); + ]; file_put_contents($filename, $export_data); } else { @@ -687,33 +698,33 @@ function reportit_prepare_store_report_results($report_id, $queue_id = 0, $start function send_scheduled_email($id, $report_id) { $start_time = microtime(true); - /* load report based email settings */ + // load report based email settings $report_settings = db_fetch_row_prepared('SELECT * FROM plugin_reportit_reports WHERE id = ?', - array($report_id)); + [$report_id]); - $data = ''; - $search = array('|title|', '|period|'); - $replace = array($report_settings['description'], $report_settings['start_date'] . '-' . $report_settings['end_date']); + $data = ''; + $search = ['|title|', '|period|']; + $replace = [$report_settings['description'], $report_settings['start_date'] . '-' . $report_settings['end_date']]; $subject = ($report_settings['email_subject'] != '') ? $report_settings['email_subject'] : 'Scheduled report - |title| - |period|'; $subject = str_replace($search, $replace, $subject); - $body = ($report_settings['email_body'] != '') ? $report_settings['email_body'] : 'This is a scheduled report generated from Cacti.'; + $body = ($report_settings['email_body'] != '') ? $report_settings['email_body'] : 'This is a scheduled report generated from Cacti.'; $format = ($report_settings['email_format'] != '') ? $report_settings['email_format'] : 'CSV'; - /* load list of recipients */ + // load list of recipients $file_type = ($format != 'SML') ? strtolower($format) : 'xml'; $mime_type = ($format != 'SML') ? 'application/' . strtolower($format) : 'application/vnd-ms-excel'; - $from = array(); + $from = []; $from[] = read_config_option('settings_from_email'); $from[] = read_config_option('settings_from_name'); $to = db_fetch_assoc_prepared('SELECT email, name FROM plugin_reportit_recipients WHERE report_id = ?', - array($report_id)); + [$report_id]); if ($report_settings['email'] != '') { $emails = explode(',', $report_settings['email']); @@ -723,7 +734,7 @@ function send_scheduled_email($id, $report_id) { if ($report_settings['bcc'] != '') { $bcc = explode(',', $report_settings['bcc']); } else { - $bcc = array(); + $bcc = []; } if (api_plugin_installed('thold') && $report['notify_list'] > 0) { @@ -741,8 +752,7 @@ function send_scheduled_email($id, $report_id) { // function mailer($from, $to, $cc, $bcc, $replyto, $subject, $body, $body_text, $attachments, $headers, $html, $epandsIds); - $return = mailer($from, $to, '', $bcc, '', $subject, $body, '', array($attachment), '', true); + $return = mailer($from, $to, '', $bcc, '', $subject, $body, '', [$attachment], '', true); return $return; } - diff --git a/lib/funct_shared.php b/lib/funct_shared.php index ab7a1b3..8f22872 100644 --- a/lib/funct_shared.php +++ b/lib/funct_shared.php @@ -28,7 +28,7 @@ function owner($report_id) { INNER JOIN user_auth as b ON b.id = a.user_id WHERE a.id = ?' , - array($report_id)); + [$report_id]); if (cacti_sizeof($tmp)) { return $tmp['full_name'] . ' (' . $tmp['username'] . ')'; @@ -38,35 +38,35 @@ function owner($report_id) { } function get_prepared_report_data($report_id, $type, $sql_where = '') { - $report_measurands = array(); - $report_variables = array(); + $report_measurands = []; + $report_variables = []; - /* load report configuration + template description */ + // load report configuration + template description $report_data = db_fetch_row_prepared('SELECT a.*, b.description AS template_name FROM plugin_reportit_reports AS a INNER JOIN plugin_reportit_templates AS b ON a.template_id = b.id WHERE a.id = ?', - array($report_id)); + [$report_id]); if (!sizeof($report_data)) { return false; } - /* get the owner of this report */ + // get the owner of this report $report_data['owner'] = owner($report_id); - /* load measurand configurations */ + // load measurand configurations $tmps = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_measurands WHERE template_id = ?', - array($report_data['template_id'])); + [$report_data['template_id']]); foreach ($tmps as $tmp) { $report_measurands[$tmp['id']] = $tmp; } - /* load configurations of variables */ + // load configurations of variables $report_variables = db_fetch_assoc_prepared('SELECT a.id, a.name, a.description, b.value, a.min_value, a.max_value FROM plugin_reportit_variables AS a @@ -74,9 +74,9 @@ function get_prepared_report_data($report_id, $type, $sql_where = '') { ON a.id = b.variable_id AND b.report_id = ? WHERE a.template_id = ?', - array($report_id, $report_data['template_id'])); + [$report_id, $report_data['template_id']]); - /* load data source alias */ + // load data source alias $report_ds_alias = db_custom_fetch_assoc('SELECT data_source_name, data_source_alias FROM plugin_reportit_data_source_items WHERE template_id = ' . $report_data['template_id'], 'data_source_name', false, false); @@ -99,49 +99,49 @@ function get_prepared_report_data($report_id, $type, $sql_where = '') { break; case 'graph': - return array( + return [ 'report_data' => $report_data, 'report_measurands' => $report_measurands - ); + ]; break; } $report_results = db_fetch_assoc($sql); - /* build data package for return */ - $data = array( + // build data package for return + $data = [ 'report_data' => $report_data, 'report_results' => $report_results, 'report_measurands' => $report_measurands, 'report_variables' => $report_variables, 'report_ds_alias' => $report_ds_alias - ); + ]; return $data; } function get_prepared_archive_data($cache_id, $type, $sql_where = '') { - $report_measurands = array(); - $report_variables = array(); + $report_measurands = []; + $report_variables = []; - /* load report configuration */ + // load report configuration $report_data = db_fetch_row_prepared('SELECT * FROM plugin_reportit_cache_reports WHERE cache_id = ?', - array($cache_id)); + [$cache_id]); - /* save serialized data source alias separately */ + // save serialized data source alias separately if (isset($report_data['data_template_alias'])) { - $report_ds_alias = json_decode(base64_decode($report_data['data_template_alias']), true); + $report_ds_alias = json_decode(base64_decode($report_data['data_template_alias'], true), true); unset($report_data['data_template_alias']); } - /* load configured measurands */ + // load configured measurands $tmps = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_cache_measurands WHERE cache_id = ?', - array($cache_id)); + [$cache_id]); if (cacti_sizeof($tmps)) { foreach ($tmps as $tmp) { @@ -149,11 +149,11 @@ function get_prepared_archive_data($cache_id, $type, $sql_where = '') { } } - /* load configured variables */ + // load configured variables $report_variables = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_cache_variables WHERE cache_id = ?', - array($cache_id)); + [$cache_id]); switch ($type) { case 'export': @@ -165,10 +165,10 @@ function get_prepared_archive_data($cache_id, $type, $sql_where = '') { break; case 'graph': - return array( + return [ 'report_data' => $report_data, 'report_measurands' => $report_measurands - ); + ]; break; case 'view': @@ -179,14 +179,14 @@ function get_prepared_archive_data($cache_id, $type, $sql_where = '') { $report_results = db_fetch_assoc($sql); - /* build data package for return */ - $data = array( + // build data package for return + $data = [ 'report_data' => $report_data, 'report_results' => $report_results, 'report_measurands' => $report_measurands, 'report_variables' => $report_variables, 'report_ds_alias' => $report_ds_alias - ); + ]; return $data; } @@ -194,17 +194,17 @@ function get_prepared_archive_data($cache_id, $type, $sql_where = '') { /** * db_custom_fetch_assoc() * - * @param string $sql contains the SQL call - * @param string $index contains the name of the column which should be used as index - * if false (default) the index will numerical beginning from zero. - * @param binary $multi save the columns multidimensional. if false then you will get only one result per index - * @param binary $assoc if true (default) then save the $values associated ($key => $value) into the index array - * requires that $multi is true. - * @return binary returns an array or false if the SQL command failed + * @param string $sql contains the SQL call + * @param string $index contains the name of the column which should be used as index + * if false (default) the index will numerical beginning from zero. + * @param binary $multi save the columns multidimensional. if false then you will get only one result per index + * @param binary $assoc if true (default) then save the $values associated ($key => $value) into the index array + * requires that $multi is true. + * @return binary returns an array or false if the SQL command failed */ -function db_custom_fetch_assoc($sql, $index = false, $multi = true, $assoc = true){ - $raw_data = array(); - $srt_data = array(); +function db_custom_fetch_assoc($sql, $index = false, $multi = true, $assoc = true) { + $raw_data = []; + $srt_data = []; $raw_data = db_fetch_assoc($sql); @@ -216,8 +216,8 @@ function db_custom_fetch_assoc($sql, $index = false, $multi = true, $assoc = tru $index_key = ($index === false) ? $row_key : $row[$index]; - foreach ($row as $key => $value){ - if ($key != $index){ + foreach ($row as $key => $value) { + if ($key != $index) { if ($multi) { if ($assoc) { $srt_data[$index_key][$key] = $value; @@ -225,7 +225,7 @@ function db_custom_fetch_assoc($sql, $index = false, $multi = true, $assoc = tru $srt_data[$index_key][] = $value; } } else { - $srt_data[$index_key]=$value; + $srt_data[$index_key] = $value; } } } @@ -240,19 +240,19 @@ function db_custom_fetch_assoc($sql, $index = false, $multi = true, $assoc = tru /** * db_custom_fetch_flat() * returns an numerical array with only one dimension. Every row will be saved column for column. - * @param string $sql contains the SQL call + * @param string $sql contains the SQL call * @return */ -function db_custom_fetch_flat_array($sql){ - $raw_data = array(); - $srt_data = array(); +function db_custom_fetch_flat_array($sql) { + $raw_data = []; + $srt_data = []; $raw_data = db_fetch_assoc($sql); - if (cacti_sizeof($raw_data)> 0) { + if (cacti_sizeof($raw_data) > 0) { foreach ($raw_data as $row) { foreach ($row as $value) { - $srt_data[] = $value; + $srt_data[] = $value; } } @@ -265,12 +265,12 @@ function db_custom_fetch_flat_array($sql){ /** * db_custom_fetch_string() * returns an string. Every row will be saved column for column and separated by a given delimiter. - * @param string $sql contains the SQL call - * @param string $delimiter character for separating the columns. Default is "," + * @param string $sql contains the SQL call + * @param string $delimiter character for separating the columns. Default is "," * @return */ -function db_custom_fetch_flat_string($sql, $delimiter = ','){ - $raw_data = array(); +function db_custom_fetch_flat_string($sql, $delimiter = ',') { + $raw_data = []; $srt_data = ''; $raw_data = db_fetch_assoc($sql); @@ -289,113 +289,143 @@ function db_custom_fetch_flat_string($sql, $delimiter = ','){ } function rp_get_timespan($preset_timespan, $present, $enable_tmz = false) { - //Set preconditions - $today = ($enable_tmz) ? gmdate('Y-m-d') : date('Y-m-d'); - list($ys, $ms, $ds) = explode('-', $today); - list($ye, $me, $de) = explode('-', $today); - - //Set report start date - switch ($preset_timespan) { - case 'Today': - - break; - case 'Last 1 Day': - $ds-=1;$de-=1; + // Set preconditions + $today = ($enable_tmz) ? gmdate('Y-m-d') : date('Y-m-d'); + [$ys, $ms, $ds] = explode('-', $today); + [$ye, $me, $de] = explode('-', $today); + + // Set report start date + switch ($preset_timespan) { + case 'Today': + break; + case 'Last 1 Day': + $ds -= 1; + $de -= 1; - break; - case 'Last 2 Days': - $ds-=2;$de-=1; + break; + case 'Last 2 Days': + $ds -= 2; + $de -= 1; - break; - case 'Last 3 Days': - $ds-=3;$de-=1; + break; + case 'Last 3 Days': + $ds -= 3; + $de -= 1; - break; - case 'Last 4 Days': - $ds-=4;$de-=1; + break; + case 'Last 4 Days': + $ds -= 4; + $de -= 1; - break; - case 'Last 5 Days': - $ds-=5;$de-=1; + break; + case 'Last 5 Days': + $ds -= 5; + $de -= 1; - break; - case 'Last 6 Days': - $ds-=6;$de-=1; + break; + case 'Last 6 Days': + $ds -= 6; + $de -= 1; - break; - case 'Last 7 Days': - $ds-=7;$de-=1; + break; + case 'Last 7 Days': + $ds -= 7; + $de -= 1; - break; - case 'Last Week (Sun - Sat)': - $ds -= ($enable_tmz) ? 7 + gmdate('w') : 7 + date('w'); - $de = $ds + 6; + break; + case 'Last Week (Sun - Sat)': + $ds -= ($enable_tmz) ? 7 + gmdate('w') : 7 + date('w'); + $de = $ds + 6; - break; - case 'Last Week (Mon - Sun)': - $ds -= ($enable_tmz) ? 6 + gmdate('w') : 6 + date('w'); - $de = $ds + 6; + break; + case 'Last Week (Mon - Sun)': + $ds -= ($enable_tmz) ? 6 + gmdate('w') : 6 + date('w'); + $de = $ds + 6; - break; - case 'Last 14 Days': - $ds-=14;$de-=1; + break; + case 'Last 14 Days': + $ds -= 14; + $de -= 1; - break; - case 'Last 21 Days': - $ds-=21;$de-=1; + break; + case 'Last 21 Days': + $ds -= 21; + $de -= 1; - break; - case 'Last 28 Days': - $ds-=28;$de-=1; + break; + case 'Last 28 Days': + $ds -= 28; + $de -= 1; - break; - case 'Current Month': - $de = ($ds == 1)? $ds : $de-1; - $ds=1; + break; + case 'Current Month': + $de = ($ds == 1) ? $ds : $de - 1; + $ds = 1; - break; - case 'Last Month': - $ms-=1;$ds=1;$de=0; + break; + case 'Last Month': + $ms -= 1; + $ds = 1; + $de = 0; - break; - case 'Last 2 Months': - $ms-=2;$ds=1;$de=0; + break; + case 'Last 2 Months': + $ms -= 2; + $ds = 1; + $de = 0; - break; - case 'Last 3 Months': - $ms-=3;$ds=1;$de=0; + break; + case 'Last 3 Months': + $ms -= 3; + $ds = 1; + $de = 0; - break; - case 'Last 4 Months': - $ms-=4;$ds=1;$de=0; + break; + case 'Last 4 Months': + $ms -= 4; + $ds = 1; + $de = 0; - break; - case 'Last 5 Months': - $ms-=5;$ds=1;$de=0; + break; + case 'Last 5 Months': + $ms -= 5; + $ds = 1; + $de = 0; - break; - case 'Last 6 Months': - $ms-=6;$ds=1;$de=0; + break; + case 'Last 6 Months': + $ms -= 6; + $ds = 1; + $de = 0; - break; - case 'Current Year': - $de = ($ds == 1 && $ms ==1 )? $ds : $de-1; - $ms=1;$ds=1; + break; + case 'Current Year': + $de = ($ds == 1 && $ms == 1) ? $ds : $de - 1; + $ms = 1; + $ds = 1; - break; - case 'Last Year': - $ms=1;$ds=1;$ys-=1;$me=1;$de=0; + break; + case 'Last Year': + $ms = 1; + $ds = 1; + $ys -= 1; + $me = 1; + $de = 0; - break; - case 'Last 2 Years': - $ms=1;$ds=1;$ys-=2;$me=1;$de=0; + break; + case 'Last 2 Years': + $ms = 1; + $ds = 1; + $ys -= 2; + $me = 1; + $de = 0; - break; - default: - break; + break; + default: + break; } - $dates = array(); + $dates = []; $dates['start_date'] = ($enable_tmz) ? gmdate('Y-m-d', gmmktime(0,0,0, $ms, $ds, $ys)) : date('Y-m-d', mktime(0,0,0, $ms, $ds, $ys)); @@ -412,9 +442,9 @@ function get_unit($value, $prefixes, $data_type, $data_precision) { global $threshold, $binary, $decimal, $IEC; if (!$threshold) { - $threshold = 0.5; + $threshold = 0.5; - $decimal = array( + $decimal = [ 'Y' => pow(1000,8), 'Z' => pow(1000,7), 'E' => pow(1000,6), @@ -423,9 +453,9 @@ function get_unit($value, $prefixes, $data_type, $data_precision) { 'G' => pow(1000,3), 'M' => pow(1000,2), 'K' => 1000 - ); + ]; - $binary = array( + $binary = [ 'Y' => pow(1024,8), 'Z' => pow(1024,7), 'E' => pow(1024,6), @@ -434,17 +464,17 @@ function get_unit($value, $prefixes, $data_type, $data_precision) { 'G' => pow(1024,3), 'M' => pow(1024,2), 'K' => 1024 - ); + ]; $IEC = read_config_option('reportit_use_IEC'); } - $type_specifiers = array('b', 'f', 'd', 'u', 'x', 'X', 'o', 'e'); + $type_specifiers = ['b', 'f', 'd', 'u', 'x', 'X', 'o', 'e']; $data_type = $type_specifiers[$data_type]; - /* use precision for type FLOAT and SCIENTIFIC NOTIFICATION only*/ - if (is_numeric($data_precision) && in_array($data_type, array('f', 'e'))) { + // use precision for type FLOAT and SCIENTIFIC NOTIFICATION only + if (is_numeric($data_precision) && in_array($data_type, ['f', 'e'], true)) { $data_precision = '.' . $data_precision; } else { $data_precision = ''; @@ -452,11 +482,17 @@ function get_unit($value, $prefixes, $data_type, $data_precision) { if ($value === 0) { return 0; - } elseif ($value == NULL) { + } + + if ($value == null) { return 'NA'; - } elseif ($prefixes == 0) { + } + + if ($prefixes == 0) { return sprintf('%' . $data_precision . $data_type, $value); - } elseif ($prefixes == 0 || $value == 0) { + } + + if ($prefixes == 0 || $value == 0) { return $value; } @@ -473,90 +509,106 @@ function get_unit($value, $prefixes, $data_type, $data_precision) { $absolute = abs($value); switch($value) { - case ($absolute >= $pre['Y']): //YOTTA - $value /= $pre['Y']; - return (sprintf('%' . $data_precision . $data_type, $value) . " Y$i"); - - break; - case ($absolute >= $pre['Y']*$threshold): - $value /= $pre['Y']; - return (sprintf('%' . $data_precision . $data_type, $value) . " Y$i"); - - break; - case ($absolute >= $pre['Z']): //ZETTA - $value /= $pre['Z']; - return (sprintf('%' . $data_precision . $data_type, $value) . " Z$i"); - - break; - case ($absolute >= $pre['Z']*$threshold): - $value /= $pre['Z']; - return (sprintf('%' . $data_precision . $data_type, $value) . " Z$i"); - - break; - case ($absolute >= $pre['E']): //EXA - $value /= $pre['E']; - return (sprintf('%' . $data_precision . $data_type, $value) . " E$i"); - - break; - case ($absolute >= $pre['E']*$threshold): - $value /= $pre['E']; - return (sprintf('%' . $data_precision . $data_type, $value) . " E$i"); - - break; - case ($absolute >= $pre['P']): //PETA - $value /= $pre['P']; - return (sprintf('%' . $data_precision . $data_type, $value) . " P$i"); - - break; - case ($absolute >= $pre['P']*$threshold): - $value /= $pre['P']; - return (sprintf('%' . $data_precision . $data_type, $value) . " P$i"); - - break; - case ($absolute >= $pre['T']): //TERA - $value /= $pre['T']; - return (sprintf('%' . $data_precision . $data_type, $value) . " T$i"); - - break; - case ($absolute >= $pre['T']*$threshold): - $value /= $pre['T']; - return (sprintf('%' . $data_precision . $data_type, $value) . " T$i"); - - break; - case ($absolute >= $pre['G']): //GIGA - $value /= $pre['G']; - return (sprintf('%' . $data_precision . $data_type, $value) . " G$i"); - - break; - case ($absolute >= $pre['G']*$threshold): - $value /= $pre['G']; - return (sprintf('%' . $data_precision . $data_type, $value) . " G$i"); - - break; - case ($absolute >= $pre['M']): //MEGA - $value /= $pre['M']; - return (sprintf('%' . $data_precision . $data_type, $value) . " M$i"); - - break; - case ($absolute >= $pre['M']*$threshold): - $value /= $pre['M']; - return (sprintf('%' . $data_precision . $data_type, $value) . " M$i"); - - break; - case ($absolute >= $pre['K']): //KILO - $value /= $pre['K']; - return (sprintf('%' . $data_precision . $data_type, $value) . " $k$i"); - - break; - case ($absolute >= $pre['K']*$threshold): - $value /= $pre['K']; - return (sprintf('%' . $data_precision . $data_type, $value) . " $k$i"); - - break; - default: - return sprintf('%' . $data_precision . $data_type, $value); - - break; + case ($absolute >= $pre['Y']): // YOTTA + $value /= $pre['Y']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " Y$i"); + + break; + case ($absolute >= $pre['Y'] * $threshold): + $value /= $pre['Y']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " Y$i"); + + break; + case ($absolute >= $pre['Z']): // ZETTA + $value /= $pre['Z']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " Z$i"); + + break; + case ($absolute >= $pre['Z'] * $threshold): + $value /= $pre['Z']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " Z$i"); + + break; + case ($absolute >= $pre['E']): // EXA + $value /= $pre['E']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " E$i"); + + break; + case ($absolute >= $pre['E'] * $threshold): + $value /= $pre['E']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " E$i"); + + break; + case ($absolute >= $pre['P']): // PETA + $value /= $pre['P']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " P$i"); + + break; + case ($absolute >= $pre['P'] * $threshold): + $value /= $pre['P']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " P$i"); + + break; + case ($absolute >= $pre['T']): // TERA + $value /= $pre['T']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " T$i"); + + break; + case ($absolute >= $pre['T'] * $threshold): + $value /= $pre['T']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " T$i"); + + break; + case ($absolute >= $pre['G']): // GIGA + $value /= $pre['G']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " G$i"); + + break; + case ($absolute >= $pre['G'] * $threshold): + $value /= $pre['G']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " G$i"); + + break; + case ($absolute >= $pre['M']): // MEGA + $value /= $pre['M']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " M$i"); + + break; + case ($absolute >= $pre['M'] * $threshold): + $value /= $pre['M']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " M$i"); + + break; + case ($absolute >= $pre['K']): // KILO + $value /= $pre['K']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " $k$i"); + + break; + case ($absolute >= $pre['K'] * $threshold): + $value /= $pre['K']; + + return (sprintf('%' . $data_precision . $data_type, $value) . " $k$i"); + + break; + default: + return sprintf('%' . $data_precision . $data_type, $value); + + break; } } @@ -564,12 +616,12 @@ function create_rvars_entries($variable_id, $template_id, $default) { $ids = db_fetch_assoc_prepared('SELECT id FROM plugin_reportit_reports WHERE template_id = ?', - array($template_id)); + [$template_id]); if (cacti_sizeof($ids)) { $list = ''; - $params = array(); + $params = []; foreach ($ids as $id) { $list .= '(?, ?, ?, ?),'; @@ -580,7 +632,7 @@ function create_rvars_entries($variable_id, $template_id, $default) { $params[] = $default; } - //Remove last comma + // Remove last comma $list = rtrim($list, ','); db_execute_prepared("INSERT INTO plugin_reportit_rvars @@ -593,13 +645,13 @@ function create_rvars_entries($variable_id, $template_id, $default) { /** * get_possible_rra_names() * returns an array with all possible names of the Round Robbin Archives for this report template - * @param int $template_id contains the id of the current report template - * @return an array with all possible round robin archives + * @param int $template_id contains the id of the current report template + * @return an array with all possible round robin archives */ function get_possible_rra_names($template_id) { - //Get all possible names of the RRAs for this type of template - $names = array(); - $array = array(); + // Get all possible names of the RRAs for this type of template + $names = []; + $array = []; $names = db_fetch_assoc_prepared('SELECT b.data_source_name FROM plugin_reportit_data_source_items AS a @@ -607,7 +659,7 @@ function get_possible_rra_names($template_id) { ON a.id = b.id WHERE a.template_id = ? AND a.id != 0', - array($template_id)); + [$template_id]); foreach ($names as $name) { $array[] = $name['data_source_name']; @@ -619,18 +671,18 @@ function get_possible_rra_names($template_id) { /** * get_interim_results() * - * @param int $measurand_id contains the id of the current measurand - * @param int $template_id contains the id of the template the measurand belongs to - * @param boolean $ln returns a line break after every interim result - * @return array with the syntax of possible interim results + * @param int $measurand_id contains the id of the current measurand + * @param int $template_id contains the id of the template the measurand belongs to + * @param boolean $ln returns a line break after every interim result + * @return array with the syntax of possible interim results */ function get_interim_results($measurand_id, $template_id, $ln = false) { - $array = array(); - $names = array(); - $interim_results = array(); + $array = []; + $names = []; + $interim_results = []; $names = get_possible_rra_names($template_id); - $sql = 'SELECT abbreviation, spanned + $sql = 'SELECT abbreviation, spanned FROM plugin_reportit_measurands WHERE template_id = ?'; @@ -644,13 +696,16 @@ function get_interim_results($measurand_id, $template_id, $ln = false) { $array = db_fetch_assoc_prepared($sql, $params); if (cacti_sizeof($array)) { - foreach ($array as $interim_result) { + foreach ($array as $interim_result) { if ($interim_result['spanned'] == '') { foreach ($names as $name) { $interim_results[] = $interim_result['abbreviation'] . ':' . $name; } } - if ($ln) $interim_result['abbreviation'] .= '
'; + + if ($ln) { + $interim_result['abbreviation'] .= '
'; + } $interim_results[] = $interim_result['abbreviation']; } } @@ -662,8 +717,8 @@ function get_possible_variables($template_id) { global $calc_var_names; // Fetch all variables which has been defined for this template - $names = array(); - $array = array(); + $names = []; + $array = []; // Check whether maxValue is valid $maximum = db_fetch_cell_prepared('SELECT DISTINCT a.rrd_maximum @@ -672,7 +727,7 @@ function get_possible_variables($template_id) { ON a.data_template_id = b.data_template_id AND b.id = ? WHERE a.local_data_id = 0', - array($template_id)); + [$template_id]); if (!is_numeric($maximum) || $maximum == 0) { unset($calc_var_names[0]); @@ -681,7 +736,7 @@ function get_possible_variables($template_id) { $names = db_fetch_assoc_prepared('SELECT abbreviation FROM plugin_reportit_variables WHERE template_id = ?', - array($template_id)); + [$template_id]); foreach ($calc_var_names as $name) { $array[] = $name; @@ -696,8 +751,8 @@ function get_possible_variables($template_id) { /** * get all available data query variables for given data template id - * @param int $template_id - the data template id - * @return array - array of data query cache variables + * @param int $template_id - the data template id + * @return array - array of data query cache variables */ function get_possible_data_query_variables($template_id) { // any data query associated with this data template? @@ -706,15 +761,15 @@ function get_possible_data_query_variables($template_id) { INNER JOIN plugin_reportit_templates AS rt ON dl.data_template_id = rt.data_template_id WHERE rt.id = ?', - array($template_id)); + [$template_id]); // in case there is no data query, have $names initialized - $names = array(); + $names = []; if (cacti_sizeof($available_data_queries)) { $data_query_list = 'snmp_query_id IN ('; - foreach($available_data_queries as $data_queries) { + foreach ($available_data_queries as $data_queries) { $data_query_list .= $data_queries['snmp_query_id'] . ','; } @@ -726,7 +781,7 @@ function get_possible_data_query_variables($template_id) { WHERE $data_query_list"); } - $array = array(); + $array = []; if (cacti_sizeof($names)) { foreach ($names as $name) { @@ -740,11 +795,11 @@ function get_possible_data_query_variables($template_id) { } function get_template_status($template_id) { - //Returns '1' if the template has been locked. + // Returns '1' if the template has been locked. $status = db_fetch_cell_prepared('SELECT locked FROM plugin_reportit_templates WHERE id = ?', - array($template_id)); + [$template_id]); return $status; } @@ -755,19 +810,22 @@ function in_process($report_id, $status = 1) { db_execute_prepared('UPDATE plugin_reportit_reports SET state = ?, last_state = ? WHERE id = ?', - array($status, $now, $report_id));; + [$status, $now, $report_id]); } function stat_process($report_id) { $sql = 'SELECT state FROM plugin_reportit_reports WHERE id = ?'; - return db_fetch_cell_prepared($sql, array($report_id)); + + return db_fetch_cell_prepared($sql, [$report_id]); } -function config_date_format($no_time=true) { +function config_date_format($no_time = true) { $date_fmt = read_graph_config_option('default_date_format'); $datechar = read_graph_config_option('default_datechar'); - if (!isset($date_fmt)) return('Y-m-d H:i:s'); + if (!isset($date_fmt)) { + return ('Y-m-d H:i:s'); + } if ($datechar == GDC_HYPHEN) { $datechar = '-'; @@ -778,33 +836,40 @@ function config_date_format($no_time=true) { switch ($date_fmt) { case GD_MO_D_Y: $dd = ('m' . $datechar . 'd' . $datechar . 'Y'); + break; case GD_MN_D_Y: $dd = ('M' . $datechar . 'd' . $datechar . 'Y'); + break; case GD_D_MO_Y: $dd = ('d' . $datechar . 'm' . $datechar . 'Y'); + break; case GD_D_MN_Y: $dd = ('d' . $datechar . 'M' . $datechar . 'Y'); + break; case GD_Y_MO_D: $dd = ('Y' . $datechar . 'm' . $datechar . 'd'); + break; case GD_Y_MN_D: $dd = ('Y' . $datechar . 'M' . $datechar . 'd'); + break; default: return ('Y-m-d H:i:s'); } - if (!$no_time) + if (!$no_time) { return ($dd . ' -- H:i:s'); - else + } else { return $dd; + } } -/* ********************* New functions ********************************* */ +// New functions function debug(&$value, $msg = '', $fmsg = '') { if (!defined('REPORTIT_DEBUG')) { return; @@ -819,7 +884,8 @@ function debug(&$value, $msg = '', $fmsg = '') { print_r($value); print "\n"; } else { - print "\t\t$fmsg: "; print_r($value); + print "\t\t$fmsg: "; + print_r($value); } } else { if ($fmsg != '') { @@ -830,51 +896,65 @@ function debug(&$value, $msg = '', $fmsg = '') { } } -function get_report_setting($report_id, $column){ +function get_report_setting($report_id, $column) { $sql = 'SELECT $column FROM plugin_reportit_reports WHERE id = ?'; - return db_fetch_cell_parepared($sql, array($report_id)); + return db_fetch_cell_parepared($sql, [$report_id]); } -function get_graph_config_option($config_name, $user_id){ +function get_graph_config_option($config_name, $user_id) { $sql = 'SELECT value FROM settings_graphs WHERE name = ? AND user_id = ?'; - $db_setting = db_fetch_row_parepared($sql, array($config_name, $user_id)); + $db_setting = db_fetch_row_parepared($sql, [$config_name, $user_id]); if (isset($db_setting['value'])) { return $db_setting['value']; - } else{ + } else { return read_default_graph_config_option($config_name); } } -function auto_rounding(&$values, $rounding, $order){ +function auto_rounding(&$values, $rounding, $order) { $threshold = 0.5; - $base = ($rounding == 2) ? 1000 : 1024; + $base = ($rounding == 2) ? 1000 : 1024; $highest = ($order == 'DESC') ? reset($values) : end($values); - if (reset($values) == 0 && end($values) == 0) return 0; - if ($highest < 0) $highest*=(-1); + + if (reset($values) == 0 && end($values) == 0) { + return 0; + } + + if ($highest < 0) { + $highest *= (-1); + } $x = 0; - for ($exp=1; $x<$highest; $exp++){ + + for ($exp = 1; $x < $highest; $exp++) { $x = pow($base, $exp); - if ($x*$threshold < $highest) continue; - else break; - } - /* workaround to avoid issues Graidle has with scaling the Y-Axis if highest values is under 1 */ - if ($highest/pow($base, $exp-1)<1) $exp--; + if ($x * $threshold < $highest) { + continue; + } else { + break; + } + } - $devisor = pow($base, $exp-1); - foreach ($values as $key => $value){ - $values[$key] = sprintf('%01.2f', ($value/=$devisor)); + // workaround to avoid issues Graidle has with scaling the Y-Axis if highest values is under 1 + if ($highest / pow($base, $exp - 1) < 1) { + $exp--; } - return $exp-1; + $devisor = pow($base, $exp - 1); + + foreach ($values as $key => $value) { + $values[$key] = sprintf('%01.2f', ($value /= $devisor)); + } + + return $exp - 1; } -function load_external_libs($name){ +function load_external_libs($name) { switch ($name) { case 'pclzip': if (!defined('PCLZIP_TEMPORARY_DIR')) { @@ -882,31 +962,31 @@ function load_external_libs($name){ } require_once(REPORTIT_BASE_PATH . '/include/vendor/pclzip/pclzip.lib.php'); - break; - case 'graidle': - break; + break; + case 'graidle': + break; case 'cleanXML': - - break; + break; } } -function clean_for_sql(&$str){ - $str = substr($str, 0, strlen($str)-1); +function clean_for_sql(&$str) { + $str = substr($str, 0, strlen($str) - 1); } -/* ********************* Archive Functions ***************************** */ +// Archive Functions function rename_xml_file($p_event, &$p_header) { $p_header['stored_filename'] = $p_header['mtime'] . '.xml'; + return 1; } function prepare_json_archive($report_id) { - /* load report data */ + // load report data $data = get_prepared_report_data($report_id, 'view'); - /* transform the data source aliases to the old style */ + // transform the data source aliases to the old style $data['report_data']['data_template_alias'] = $data['report_ds_alias']; return json_encode($data); @@ -918,40 +998,51 @@ function update_xml_archive($report_id) { $tmp_path = REPORTIT_TMP_FD; $arc_file = (($arc_path == '') ? REPORTIT_ARC_FD : $arc_path) . $report_id . '.zip'; - /* maximum number of files the archive should contain */ + // maximum number of files the archive should contain $max = get_report_setting($report_id, 'autoarchive'); - /* load report data */ + // load report data $data = get_prepared_report_data($report_id, 'view'); - /* transform the data source aliases to the old style */ + // transform the data source aliases to the old style $data['report_data']['data_template_alias'] = serialize($data['report_ds_alias']); - /* use an output puffer for flushing */ + // use an output puffer for flushing ob_start(); // print '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL; print '' . PHP_EOL . '' . PHP_EOL . '' . PHP_EOL; - foreach ($data['report_data'] as $key => $value) print "<$key>" . html_escape($value, ENT_NOQUOTES) . "" . PHP_EOL; + foreach ($data['report_data'] as $key => $value) { + print "<$key>" . html_escape($value, ENT_NOQUOTES) . "" . PHP_EOL; + } print '' . PHP_EOL . '' . PHP_EOL; - foreach ($data['report_measurands'] as $measurand){ + foreach ($data['report_measurands'] as $measurand) { print '' . PHP_EOL; - foreach ($measurand as $key => $value) print "<$key>" . html_escape($value, ENT_NOQUOTES) . "" . PHP_EOL; + + foreach ($measurand as $key => $value) { + print "<$key>" . html_escape($value, ENT_NOQUOTES) . "" . PHP_EOL; + } print '' . PHP_EOL; } print '' . PHP_EOL . '' . PHP_EOL; - foreach ($data['report_results'] as $results){ + foreach ($data['report_results'] as $results) { print '' . PHP_EOL; - foreach ($results as $key => $value) print "<_di__$key>" . html_escape($value, ENT_NOQUOTES) . "" . PHP_EOL; + + foreach ($results as $key => $value) { + print "<_di__$key>" . html_escape($value, ENT_NOQUOTES) . "" . PHP_EOL; + } print '' . PHP_EOL; } print '' . PHP_EOL . '' . PHP_EOL; foreach ($data['report_variables'] as $variable) { print '' . PHP_EOL; - foreach ($variable as $key => $value) print "<$key>" . html_escape($value, ENT_NOQUOTES) . "" . PHP_EOL; + + foreach ($variable as $key => $value) { + print "<$key>" . html_escape($value, ENT_NOQUOTES) . "" . PHP_EOL; + } print '' . PHP_EOL; } @@ -959,77 +1050,80 @@ function update_xml_archive($report_id) { $content = ob_get_clean(); $content = mb_convert_encoding($content, 'UTF-8', 'ISO-8859-1'); - /* create a tempary file and save XML output*/ - $cfg = $data['report_data']; - $tmpfile = REPORTIT_TMP_FD . strtotime($cfg['start_date']) . "_" . strtotime($cfg['end_date']) . "_" . time() . ".xml"; - $filehandle = fopen($tmpfile, "w"); + // create a tempary file and save XML output + $cfg = $data['report_data']; + $tmpfile = REPORTIT_TMP_FD . strtotime($cfg['start_date']) . '_' . strtotime($cfg['end_date']) . '_' . time() . '.xml'; + $filehandle = fopen($tmpfile, 'w'); fwrite($filehandle, $content); fclose($filehandle); - /* load zip file support */ + // load zip file support load_external_libs('pclzip'); - /* set handle for archiving */ + // set handle for archiving $archive = new PclZip($arc_file); - /* use file rotation */ + // use file rotation if (($stat = $archive->properties()) != 0) { $cnt = ($max == 0) ? 0 : $stat['nb']; - if ($cnt > $max+1) { - $end = $cnt - $max-1; - $archive->delete(PCLZIP_OPT_BY_INDEX, '0-'.$end); - } else if ($cnt == $max+1){ + + if ($cnt > $max + 1) { + $end = $cnt - $max - 1; + $archive->delete(PCLZIP_OPT_BY_INDEX, '0-' . $end); + } elseif ($cnt == $max + 1) { $archive->delete(PCLZIP_OPT_BY_INDEX, '0'); } - }; + } - /* add XML output to the archive */ + // add XML output to the archive $v_list = $archive->add($tmpfile, PCLZIP_OPT_REMOVE_ALL_PATH); + if ($v_list == 0) { - die("Error : ".$archive->errorInfo(true)); + die('Error : ' . $archive->errorInfo(true)); } - /* change mode */ + // change mode chmod($arc_file, 0644); - /* clean up TMP */ + // clean up TMP unlink($tmpfile); } -function cache_xml_file($report_id, $mtime){ +function cache_xml_file($report_id, $mtime) { $cache_id = $report_id . '_' . $mtime; $columns = ''; $values = ''; - $cols = array(); + $cols = []; $index = false; $arc_path = read_config_option('reportit_arc_folder'); - $arc_path .= (substr($arc_path, -1) == '/') ? '' : '/'; + $arc_path .= (substr($arc_path, -1) == '/') ? '' : '/'; $arc_file = (($arc_path == '') ? REPORTIT_ARC_FD : $arc_path) . $report_id . '.zip'; - /* check if cache is up to date */ + // check if cache is up to date if (db_table_exists('plugin_reportit_tmp_' . $cache_id)) { return; } - /* load zip file support */ + // load zip file support load_external_libs('pclzip'); - /* set handle for archiving */ + // set handle for archiving $archive = new PclZip($arc_file); - /* unzip xml archive and load xml file */ + // unzip xml archive and load xml file $info = $archive->listContent(); foreach ($info as $key => $array) { if ($array['mtime'] == $mtime) { $index = $array['index']; + break; } } if ($index === false) { - die_html_custom_error("Report not found in archive.", true); + die_html_custom_error('Report not found in archive.', true); } $data = $archive->extractByIndex($index, PCLZIP_OPT_EXTRACT_AS_STRING); @@ -1037,7 +1131,7 @@ function cache_xml_file($report_id, $mtime){ $json_content = json_encode($content); $archive = json_decode($json_content, true); - /* transform data and fill up the cache tables */ + // transform data and fill up the cache tables trans_array2sql($archive['report']['settings'], $columns, $values, $cache_id); db_execute("REPLACE INTO plugin_reportit_cache_reports $columns VALUES $values"); @@ -1052,33 +1146,33 @@ function cache_xml_file($report_id, $mtime){ $columns = str_replace('_di__', '', $columns); $cols = explode(',', substr($columns, 2, -1)); - $sql = "CREATE TABLE IF NOT EXISTS plugin_reportit_tmp_" . $cache_id . " ("; + $sql = 'CREATE TABLE IF NOT EXISTS plugin_reportit_tmp_' . $cache_id . ' ('; - foreach ($cols as $name){ + foreach ($cols as $name) { if ($name == '`id`') { - $sql .= $name . " int(11) NOT NULL DEFAULT 0,"; + $sql .= $name . ' int(11) NOT NULL DEFAULT 0,'; } elseif (strpos($name, '__') !== false) { - $sql .= $name . " DOUBLE,"; + $sql .= $name . ' DOUBLE,'; } else { $sql .= $name . " VARCHAR(255) NOT NULL DEFAULT '',"; } } - $sql .= "PRIMARY KEY (`id`)) ENGINE=Aria ROW_FORMAT=Page;"; + $sql .= 'PRIMARY KEY (`id`)) ENGINE=Aria ROW_FORMAT=Page;'; db_execute($sql); - db_execute("REPLACE INTO plugin_reportit_tmp_" . $cache_id . " $columns VALUES $values"); + db_execute('REPLACE INTO plugin_reportit_tmp_' . $cache_id . " $columns VALUES $values"); } function trans_array2sql(&$array, &$columns, &$values, $cache_id = false) { - $keys = false; - $multi = false; + $keys = false; + $multi = false; $sub_values = ''; - /* reset */ + // reset $columns = $cache_id ? '`cache_id`' : ''; - $values = ''; + $values = ''; if (!is_array($array)) { return false; @@ -1105,19 +1199,19 @@ function trans_array2sql(&$array, &$columns, &$values, $cache_id = false) { $keys = true; - $values .= $cache_id ? ",('$cache_id' $sub_values)" : ',(' . substr($sub_values, 1) .')'; + $values .= $cache_id ? ",('$cache_id' $sub_values)" : ',(' . substr($sub_values, 1) . ')'; $multi = true; } } else { foreach ($value as $sub_key => $sub_value) { $columns .= ", `$sub_key`"; - $values .= (is_array($sub_value) && !$sub_value) ? ", ''" : ', ' . db_qstr($sub_value); + $values .= (is_array($sub_value) && !$sub_value) ? ", ''" : ', ' . db_qstr($sub_value); } } } else { $columns .= ", `$key`"; - $values .= ', ' . db_qstr($value); + $values .= ', ' . db_qstr($value); } } } else { @@ -1125,52 +1219,50 @@ function trans_array2sql(&$array, &$columns, &$values, $cache_id = false) { } $columns = $cache_id ? "($columns)" : '(' . substr($columns, 1) . ')'; - $values = ($multi == true) ? substr($values, 1) : (($cache_id !== false)? "('$cache_id' $values)" : "(" . substr($values, 1) . ")" ); + $values = ($multi == true) ? substr($values, 1) : (($cache_id !== false) ? "('$cache_id' $values)" : '(' . substr($values, 1) . ')'); return true; } - - function info_xml_archive($report_id) { - $content = array(); + $content = []; $arc_path = read_config_option('reportit_arc_folder'); $arc_file = (($arc_path == '') ? REPORTIT_ARC_FD : $arc_path) . "/$report_id" . '.zip'; $format = config_date_format(); - /* load zip file support */ + // load zip file support load_external_libs('pclzip'); - /* set handle for archiving */ + // set handle for archiving $archive = new PclZip($arc_file); - /* collect some informations about this archive */ + // collect some informations about this archive if (($list = $archive->listContent()) != 0) { foreach ($list as $key => $file) { if ($file['status'] == 'ok') { - list($from, $to) = explode("_", str_replace('.xml', '', $file['filename'])); - $content[$file['mtime']] = date($format, $from) . " -> " . date($format, $to); + [$from, $to] = explode('_', str_replace('.xml', '', $file['filename'])); + $content[$file['mtime']] = date($format, $from) . ' -> ' . date($format, $to); } } - /* show the newest ones first */ + // show the newest ones first krsort($content, SORT_NUMERIC); + return $content; } else { return false; } } - function average($array) { - if (cacti_sizeof($array)== 0) { + if (cacti_sizeof($array) == 0) { return ''; } - return (array_sum($array)/count($array)); + return (array_sum($array) / count($array)); } -function transform_html_escape(&$data){ +function transform_html_escape(&$data) { if (!is_array($data)) { html_escape($data); } else { @@ -1180,7 +1272,6 @@ function transform_html_escape(&$data){ if (is_array($value_2)) { foreach ($value_2 as $key_3 => $value_3) { $value_2[$key_3] = is_null($value_3) ? '' : html_escape($value_3); - } $value_1[$key_2] = $value_2; @@ -1191,7 +1282,7 @@ function transform_html_escape(&$data){ $data[$key_1] = $value_1; } else { - $data[$key_1] = is_null($value_1)? '' : html_escape($value_1); + $data[$key_1] = is_null($value_1) ? '' : html_escape($value_1); } } } @@ -1199,7 +1290,7 @@ function transform_html_escape(&$data){ function return_bytes($val) { $val = trim($val); - $last = strtolower($val[strlen($val)-1]); + $last = strtolower($val[strlen($val) - 1]); $val = substr($val, 0, -1); switch($last) { @@ -1214,7 +1305,7 @@ function return_bytes($val) { return $val; } -function transform_htmlspecialchars(&$data){ +function transform_htmlspecialchars(&$data) { if (!is_array($data)) { htmlspecialchars($data); } else { @@ -1234,7 +1325,7 @@ function transform_htmlspecialchars(&$data){ $data[$key_1] = $value_1; } else { - $data[$key_1] = htmlspecialchars($value_1); + $data[$key_1] = htmlspecialchars($value_1); } } } @@ -1242,28 +1333,28 @@ function transform_htmlspecialchars(&$data){ function get_mem_usage() { $memory_system = return_bytes(ini_get('memory_limit')); - $memory_used = round(memory_get_usage()/pow(1024,2),2); - $memory_peak = round(memory_get_peak_usage()/pow(1024,2),2); + $memory_used = round(memory_get_usage() / pow(1024,2),2); + $memory_peak = round(memory_get_peak_usage() / pow(1024,2),2); if ($memory_system == -1 || $memory_system == '-') { $memory_system = 'unlimited'; - $memory_used .= 'MB'; - $memory_peak .= 'MB'; + $memory_used .= 'MB'; + $memory_peak .= 'MB'; } elseif (!is_numeric($memory_used) || !is_numeric($memory_peak) || !is_numeric($memory_system)) { $memory_used = 'Undetected'; $memory_peak = 'Undetected'; } else { - $memory_used .= 'MB(' . round($memory_used/$memory_system*100,2) . '%)'; - $memory_peak .= 'MB(' . round($memory_peak/$memory_system*100,2) . '%)'; + $memory_used .= 'MB(' . round($memory_used / $memory_system * 100,2) . '%)'; + $memory_peak .= 'MB(' . round($memory_peak / $memory_system * 100,2) . '%)'; } - return array('limit' => $memory_system, 'current' => $memory_used, 'peak' => $memory_peak); + return ['limit' => $memory_system, 'current' => $memory_used, 'peak' => $memory_peak]; } function xml_to_string($xml_object, $keep_spaces = true) { - $dom = new DOMDocument(); + $dom = new DOMDocument(); $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; + $dom->formatOutput = true; $dom->loadXML($xml_object->asXml()); $output = $dom->saveXML($dom->firstChild); @@ -1280,7 +1371,8 @@ function xml_to_array($xml_object, $indexed = false, $log = false) { $indent++; $indent_char = str_repeat(' ',$indent); - $out = array(); + $out = []; + if (!$xml_object) { return ''; } @@ -1337,70 +1429,69 @@ function xml_to_array($xml_object, $indexed = false, $log = false) { } function export_report_template($template_id, $indent = 0) { - /* load template data */ + // load template data $template_data = db_fetch_row_prepared('SELECT * FROM plugin_reportit_templates WHERE id = ?', - array($template_id)); + [$template_id]); - /* exit if no result has been returned */ + // exit if no result has been returned if ($template_data == false) { return false; } - /* export folder should not be shared */ + // export folder should not be shared $template_data['export_folder'] = ''; - /* load definitions of variables */ + // load definitions of variables $variables_data = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_variables WHERE template_id = ? ORDER BY id', - array($template_id)); + [$template_id]); - /* load definitions of measurands */ + // load definitions of measurands $measurands_data = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_measurands WHERE template_id = ? ORDER BY id', - array($template_id)); + [$template_id]); - /* load definitions of data source items */ + // load definitions of data source items $data_source_items_data = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_data_source_items WHERE template_id = ? ORDER BY id', - array($template_id)); + [$template_id]); - /* add template version and hash the checksum */ + // add template version and hash the checksum $reportit_info = plugin_reportit_version(); - $reportit = array('version' => $reportit_info['version'], 'type' => 1); + $reportit = ['version' => $reportit_info['version'], 'type' => 1]; - /* use an output puffer for flushing */ - $xml_array = array( - 'report_template' => array( + // use an output puffer for flushing + $xml_array = [ + 'report_template' => [ 'reportit' => $reportit, 'settings' => $template_data, - 'measurands' => array( + 'measurands' => [ 'xml_element' => 'measurand', 'xml_data' => $measurands_data, - ), - 'variables' => array( + ], + 'variables' => [ 'xml_element' => 'variable', 'xml_data' => $variables_data, - ), - 'data_source_items' => array( + ], + 'data_source_items' => [ 'xml_element' => 'data_source_item', 'xml_data' => $data_source_items_data, - ), - ), - ); - + ], + ], + ]; $xml_temp = convert_array2xml($xml_array, $indent); $xml_obj = simplexml_load_string($xml_temp); - $valid = true; + $valid = true; $checksum = ''; validate_xml_template($xml_obj, $valid, $checksum); @@ -1422,7 +1513,7 @@ function convert_array2xml($data, $indent = 0) { $pad = str_repeat("\t", $indent); if (is_array($data)) { - if (array_key_exists('xml_element', $data) && array_key_existS('xml_data', $data)) { + if (array_key_exists('xml_element', $data) && array_key_exists('xml_data', $data)) { $element = $data['xml_element']; foreach ($data['xml_data'] as $xml_data) { @@ -1477,18 +1568,18 @@ function clean_xml_waste(&$array, $replace = '') { } function import_template($report_template, $data_template_id) { - $values = ''; - $columns = ''; - $old = array(); - $new = array(); + $values = ''; + $columns = ''; + $old = []; + $new = []; - //foreach ($xml_data[0] as $report_template) { + // foreach ($xml_data[0] as $report_template) { $template_data = xml_to_array($report_template->{'settings'}); $template_variables = xml_to_array($report_template->variables, true); $template_measurands = xml_to_array($report_template->measurands, true); $template_data_source_items = xml_to_array($report_template->data_source_items, true); - $template_data['id'] = 0; + $template_data['id'] = 0; $template_data['data_template_id'] = $data_template_id; clean_xml_waste($template_data); @@ -1508,11 +1599,11 @@ function import_template($report_template, $data_template_id) { db_execute_prepared('UPDATE plugin_reportit_variables SET abbreviation = ? WHERE id = ?', - array($abbr, $new_id)); + [$abbr, $new_id]); } foreach ($template_measurands as $template_measurand) { - $measurand = $template_measurand; + $measurand = $template_measurand; $measurand['id'] = 0; $measurand['template_id'] = $template_id; $measurand['calc_formula'] = str_replace($old,$new, $measurand['calc_formula']); @@ -1529,11 +1620,10 @@ function import_template($report_template, $data_template_id) { WHERE local_data_id = 0 AND data_template_id = ? AND data_source_name = ?', - array(get_request_var('data_template'), $ds_item['data_source_name'])); + [get_request_var('data_template'), $ds_item['data_source_name']]); $ds_item['template_id'] = $template_id; - sql_save($ds_item, 'plugin_reportit_data_source_items', array('id', 'template_id'), false); + sql_save($ds_item, 'plugin_reportit_data_source_items', ['id', 'template_id'], false); } } - diff --git a/lib/funct_validate.php b/lib/funct_validate.php index bbe0338..2dcec44 100644 --- a/lib/funct_validate.php +++ b/lib/funct_validate.php @@ -29,16 +29,16 @@ function last_error($errno, $errstr) { global $error; - $error = array( + $error = [ 'Number' => $errno, 'Message' => $errstr - ); + ]; } function validate_calc_formula($calc_formula, $calc_intersizes, $calc_var_names, $calc_data_query_variables) { global $calc_fct_names, $calc_fct_names_params, $calc_fct_aliases; - //Valid signs: + // Valid signs: $valids['intersizes']['S'] = $calc_intersizes; $valids['intersizes']['R'] = 'E'; $valids['functions']['S'] = $calc_fct_names; @@ -54,35 +54,35 @@ function validate_calc_formula($calc_formula, $calc_intersizes, $calc_var_names, $valids['dq_variables']['S'] = $calc_data_query_variables; $valids['dq_variables']['R'] = 'E'; - $valids['signs']['S'] = array('(', ')', '.', ','); - $valids['signs']['R'] = array('L', 'R', '.', ','); - $valids['operators']['S'] = array('+','-','*','/'); - $valids['operators']['R'] = array('+','-','*','/'); - $valids['numbers']['S'] = array('1','2','3','4','5','6','7','8','9','0'); + $valids['signs']['S'] = ['(', ')', '.', ',']; + $valids['signs']['R'] = ['L', 'R', '.', ',']; + $valids['operators']['S'] = ['+', '-', '*', '/']; + $valids['operators']['R'] = ['+', '-', '*', '/']; + $valids['numbers']['S'] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; $valids['numbers']['R'] = 'N'; - //Invalid combinations of signs: - $invalids = array( + // Invalid combinations of signs: + $invalids = [ '++', '+*', '+/', '--', '-*', '-/', '**', '*/', '/*', '//', 'NE', 'EN', 'LR', 'L*', 'L/', '.L', 'EL', 'NL', 'RL', '+R', '-R', '*R', '/R', 'R.', 'RE', 'RN', 'EE', '..', ',,', '.,', 'L,', ',R' - ); + ]; - //Sometime it's better and easier to work with whitelists - $whitelist = array( - 'P' => array('PL') - ); + // Sometime it's better and easier to work with whitelists + $whitelist = [ + 'P' => ['PL'] + ]; - //Invalid divisions: - $invaldiv = array('/0'); + // Invalid divisions: + $invaldiv = ['/0']; - //Search for invalid signs or function calls: + // Search for invalid signs or function calls: $debug = ''; - $debug = str_replace(array(' ',"\r\n","\n"), '', $calc_formula); + $debug = str_replace([' ', "\r\n", "\n"], '', $calc_formula); - foreach($valids as $array) { + foreach ($valids as $array) { $debug = str_replace($array['S'], '', $debug); } @@ -90,23 +90,24 @@ function validate_calc_formula($calc_formula, $calc_intersizes, $calc_var_names, return "Invalid characters: $debug"; } - //Check the number of parenthensis; + // Check the number of parenthensis; if (substr_count($calc_formula, '(') != substr_count($calc_formula, ')')) { return "Missing parenthensis: $calc_formula"; } - //Check if the formula begins or ends with an operator - if (in_array($calc_formula[0], $valids['operators']['S'])) { + // Check if the formula begins or ends with an operator + if (in_array($calc_formula[0], $valids['operators']['S'], true)) { return 'Formula begins with an operator.'; } - if (in_array($calc_formula[strlen($calc_formula)-1], $valids['operators']['S'])) { + if (in_array($calc_formula[strlen($calc_formula) - 1], $valids['operators']['S'], true)) { return 'Formula ends with an operator.'; } - //Search invalid divisions + // Search invalid divisions $debug = $calc_formula; - foreach($invaldiv as $div) { + + foreach ($invaldiv as $div) { $position = strpos($debug, $div); if ($position !== false) { @@ -114,14 +115,15 @@ function validate_calc_formula($calc_formula, $calc_intersizes, $calc_var_names, } } - //Search invalid combinations of operators, functions and operands: + // Search invalid combinations of operators, functions and operands: $debug = $calc_formula; - foreach($valids as $array) { + + foreach ($valids as $array) { $debug = str_replace($array['S'], $array['R'], $debug); } - //Blacklist - foreach($invalids as $invalid) { + // Blacklist + foreach ($invalids as $invalid) { $position = strpos($debug, $invalid); if ($position !== false) { @@ -129,24 +131,24 @@ function validate_calc_formula($calc_formula, $calc_intersizes, $calc_var_names, } } - //Whitelist - foreach($whitelist as $key => $valids) { - $debug_w = $debug; + // Whitelist + foreach ($whitelist as $key => $valids) { + $debug_w = $debug; $position = strpos($debug_w, $key); - while($position !== false) { - foreach($valids as $valid) { + while ($position !== false) { + foreach ($valids as $valid) { if (substr($debug_w, $position, strlen($valid)) != $valid) { return "Syntax error w: $calc_formula"; } } - $debug_w = substr( $debug_w, $position+1, strlen($debug_w)); + $debug_w = substr($debug_w, $position + 1, strlen($debug_w)); $position = strpos($debug_w, $key); } } - //If no error occurs the formula seems to be valid + // If no error occurs the formula seems to be valid return 'VALID'; } @@ -168,27 +170,27 @@ function die_html_custom_error($msg = '', $top_header = false) { exit; } -function input_validate_input_whitelist($value, $valid_list, $undefined=false, $header=true){ +function input_validate_input_whitelist($value, $valid_list, $undefined = false, $header = true) { if ($value == false && $undefined == true) { return; } - if (!in_array($value, $valid_list)) { + if (!in_array($value, $valid_list, true)) { die_html_custom_error('', $header); } } -function input_validate_input_blacklist($value, $black_list, $undefined=false, $header=true){ +function input_validate_input_blacklist($value, $black_list, $undefined = false, $header = true) { if ($value == false && $undefined == true) { return; } - if (in_array($value, $black_list)) { + if (in_array($value, $black_list, true)) { die_html_custom_error('', $header); } } -function input_validate_input_key($value, $valid_list, $undefined=false, $header=true){ +function input_validate_input_key($value, $valid_list, $undefined = false, $header = true) { if ($value == false && $undefined == true) { return; } @@ -201,25 +203,25 @@ function input_validate_input_key($value, $valid_list, $undefined=false, $header /** * input_validate_input_limits() * - * @param float $value The input number that has to be checked - * @param float $lower_limit First limiting value - * @param float $upper_limit Second limiting value - * @param binary $inside Returns an error if the value is outside the limits. - * If 'false', function returns an error if value is inside the limits - * @param binary $header show top_header_graph + * @param float $value The input number that has to be checked + * @param float $lower_limit First limiting value + * @param float $upper_limit Second limiting value + * @param binary $inside Returns an error if the value is outside the limits. + * If 'false', function returns an error if value is inside the limits + * @param binary $header show top_header_graph */ -function input_validate_input_limits($value, $lower_limit, $upper_limit, $inside=true, $header=true ){ +function input_validate_input_limits($value, $lower_limit, $upper_limit, $inside = true, $header = true) { if ($inside) { - if ($value<$lower_limit && $value>$upper_limit) { + if ($value < $lower_limit && $value > $upper_limit) { die_html_custom_error('', $header); } - } elseif ($value>$lower_limit && $value<$upper_limit) { + } elseif ($value > $lower_limit && $value < $upper_limit) { die_html_custom_error('', $header); } } function validate_xml_template_section(&$xml_template, $section, &$valid, &$checksum) { - //print "validate_xml_template_section:start(xml_template, $section, $valid, $checksum)\n"; + // print "validate_xml_template_section:start(xml_template, $section, $valid, $checksum)\n"; if ($valid) { if (isset($xml_template->$section) && is_object($xml_template->$section)) { $checksum .= xml_to_string($xml_template->$section, false); @@ -228,20 +230,22 @@ function validate_xml_template_section(&$xml_template, $section, &$valid, &$chec } } - //print "validate_xml_template_section:end (xml_template, $section, $valid, $checksum)\n"; + // print "validate_xml_template_section:end (xml_template, $section, $valid, $checksum)\n"; return $valid; } function validate_xml_template(&$xml_template, &$valid, &$checksum) { - //print "validate_xml_template:begin(xml_template, $valid, $checksum)\n"; + // print "validate_xml_template:begin(xml_template, $valid, $checksum)\n"; if (isset($xml_template->reportit) && is_object($xml_template->reportit)) { - $count =0; + $count = 0; + // Loop through the values of the first reportit element (there should be only one) foreach ($xml_template->reportit[0] as $key => $value) { if ($key == 'hash') { // Lets do some magic and remove the hash, saving it for later $hash = $value; unset($xml_template->reportit[0]->{$key}); + break; } $count++; @@ -259,36 +263,43 @@ function validate_xml_template(&$xml_template, &$valid, &$checksum) { if (isset($hash)) { $xml_template->reportit->hash = $hash; } - //print "validate_xml_template:end (report_template, $valid, $checksum)\n"; + // print "validate_xml_template:end (report_template, $valid, $checksum)\n"; } -function validate_uploaded_templates(){ - /* check file transfer if used */ +function validate_uploaded_templates() { + // check file transfer if used if (isset($_FILES['file'])) { - /* check for errors first */ + // check for errors first if ($_FILES['file']['error'] != 0) { switch ($_FILES['file']['error']) { - case 1: - session_custom_error_message('file', __('The file is to big.', 'reportit'), false); - break; - case 2: - session_custom_error_message('file', __('The file is to big.', 'reportit'), false); - break; - case 3: - session_custom_error_message('file', __('Incomplete file transfer.', 'reportit'), false); - break; - case 4: - session_custom_error_message('file', __('No file uploaded.', 'reportit'), false); - break; - case 6: - session_custom_error_message('file', __('Temporary folder missing.', 'reportit'), false); - break; - case 7: - session_custom_error_message('file', __('Failed to write file to disk', 'reportit'), false); - break; - case 8: - session_custom_error_message('file', __('File upload stopped by extension', 'reportit'), false); - break; + case 1: + session_custom_error_message('file', __('The file is to big.', 'reportit'), false); + + break; + case 2: + session_custom_error_message('file', __('The file is to big.', 'reportit'), false); + + break; + case 3: + session_custom_error_message('file', __('Incomplete file transfer.', 'reportit'), false); + + break; + case 4: + session_custom_error_message('file', __('No file uploaded.', 'reportit'), false); + + break; + case 6: + session_custom_error_message('file', __('Temporary folder missing.', 'reportit'), false); + + break; + case 7: + session_custom_error_message('file', __('Failed to write file to disk', 'reportit'), false); + + break; + case 8: + session_custom_error_message('file', __('File upload stopped by extension', 'reportit'), false); + + break; } if (is_error_message()) { @@ -296,19 +307,21 @@ function validate_uploaded_templates(){ } } - /* check mine type of the uploaded file */ + // check mine type of the uploaded file if ($_FILES['file']['type'] != 'text/xml') { session_custom_error_message('file', __('Invalid file extension.', 'reportit'), false); + return false; } $template_data = file_get_contents($_FILES['file']['tmp_name']); } else { session_custom_error_message('file', __('No file uploaded.', 'reportit'), false); + return false; } - /* try to parse the report template */ + // try to parse the report template $xmldata = simplexml_load_string($template_data); $checksum = ''; $valid = true; @@ -318,31 +331,33 @@ function validate_uploaded_templates(){ if (!is_object($xmldata)) { session_custom_error_message('file', __('Unable to parse template file.', 'reportit')); } else { - /* generate a hash to check the data structure and to find changes */ + // generate a hash to check the data structure and to find changes $report_count = 0; + foreach ($xmldata as $report_template) { $report_count++; - $valid = true; + $valid = true; $report_compatible = false; - $checksum = ''; - $hash = (string)$report_template->reportit->hash; + $checksum = ''; + $hash = (string)$report_template->reportit->hash; validate_xml_template($report_template, $valid, $checksum); if ($hash == false || $hash !== md5($checksum) || $valid === false) { print __('Checksum error with Template %s in XML file', $report_count, 'reportit') . PHP_EOL; session_custom_error_message('file', __('Checksum error with Template %s in XML file', $report_count, 'reportit'), false); + return false; } - /* check dependences with existing data templates... */ + // check dependences with existing data templates... $data_template_id = $report_template->settings->data_template_id; $template_ds_items = $report_template->data_source_items[0]; - foreach($template_ds_items as $template_ds_item) { + foreach ($template_ds_items as $template_ds_item) { $template_ds_names[] = (string)$template_ds_item->data_source_name; } - /* load information about defined data sources of that data template */ + // load information about defined data sources of that data template $sql = "SELECT data_source_name FROM data_template_rrd WHERE local_data_id=0 @@ -350,25 +365,26 @@ function validate_uploaded_templates(){ $ds_names = db_custom_fetch_assoc($sql,false,false,false); - if (in_array($template_ds_names, $ds_names) === false) { + if (in_array($template_ds_names, $ds_names, true) === false) { $report_compatible = true; - $sql = ("SELECT id, name FROM data_template WHERE id = $data_template_id"); + $sql = ("SELECT id, name FROM data_template WHERE id = $data_template_id"); $data_templates = db_custom_fetch_assoc($sql, 'id', false); } else { - /* try to find a compatible data template */ + // try to find a compatible data template $names = ''; - /* drop generic data source item 'overall' */ - if (array_search('overall', $template_ds_names) !== false) { - unset($template_ds_names[array_search('overall', $template_ds_names)]); + // drop generic data source item 'overall' + if (array_search('overall', $template_ds_names, true) !== false) { + unset($template_ds_names[array_search('overall', $template_ds_names, true)]); } - foreach($template_ds_names as $ds) { + foreach ($template_ds_names as $ds) { $names .= "'$ds', "; } $data_templates = false; + if (count($template_ds_names)) { $names = substr($names, 0, -2); @@ -394,27 +410,25 @@ function validate_uploaded_templates(){ if ($report_compatible) { $tmp_node = $report_template->addChild('data_templates'); + foreach ($data_templates as $id => $name) { $tmp_child = $tmp_node->addChild('data_template'); $tmp_child->addChild('id',$id); $tmp_child->addChild('name',$name); } $report_template->compatible = true; - $compatible = true; + $compatible = true; } else { $report_template->compatible = false; } } - /* save data in the user session */ - if (!isset($_SESSION['sess_reportit'])) { - $_SESSION['sess_reportit'] = array(); - } + // save data in the user session + $_SESSION['sess_reportit'] ??= []; - $xmlstring = xml_to_string($xmldata); + $xmlstring = xml_to_string($xmldata); $_SESSION['sess_reportit']['report_templates'] = $xmlstring; } return $valid && $compatible; } - diff --git a/poller_reportit.php b/poller_reportit.php index bef70bd..27cc016 100644 --- a/poller_reportit.php +++ b/poller_reportit.php @@ -42,19 +42,19 @@ $PATH_RID_VIEW = ""; $PATH_DID_VIEW = ""; -$run_return = array(); +$run_return = []; $run_id = false; $queue_id = false; $run_verb = false; $run_scheduled = true; -$run_search = array('', '', ''); +$run_search = ['', '', '']; $socket_handle = ''; $email_counter = 0; $export_counter = 0; $debug = false; $schedule = false; -$path = dirname(__FILE__); +$path = __DIR__; chdir($path); chdir('../../'); @@ -78,11 +78,11 @@ global $debug; if (cacti_sizeof($parms)) { - foreach($parms as $parameter) { + foreach ($parms as $parameter) { if (strpos($parameter, '=')) { - list($arg, $value) = explode('=', $parameter); + [$arg, $value] = explode('=', $parameter); } else { - $arg = $parameter; + $arg = $parameter; $value = ''; } @@ -137,10 +137,10 @@ FROM reports_queued WHERE status = ? AND source = ?', - array('pending', 'reportit')); + ['pending', 'reportit']); if (cacti_sizeof($pending)) { - foreach($pending as $report) { + foreach ($pending as $report) { printf('Running Scheduled report %s with id %s' . PHP_EOL, $report['name'], $report['source_id']); reports_run($report['id']); } @@ -152,7 +152,7 @@ function run_report($report_id, $queue_id = 0) { global $run_verb, $email_counter, $export_counter; - $start = microtime(true); + $start = microtime(true); $start_time = time(); $report = db_fetch_row_prepared("SELECT report.* @@ -161,10 +161,10 @@ function run_report($report_id, $queue_id = 0) { ON template.locked = '' AND report.template_id = template.id WHERE report.id = ?", - array($report_id)); + [$report_id]); if (!cacti_sizeof($report)) { - print PHP_EOL . PHP_EOL . "ERROR: Invalid report ID !" . PHP_EOL; + print PHP_EOL . PHP_EOL . 'ERROR: Invalid report ID !' . PHP_EOL; display_help(); } else { $start_time = time(); @@ -188,11 +188,11 @@ function run_report($report_id, $queue_id = 0) { db_execute_prepared('UPDATE plugin_reportit_reports SET last_started = ?, last_runtime = ? WHERE id = ?', - array( + [ date('Y-m-d H:i:s', $start_time), $end - $start, $report_id - ) + ] ); exit(0); @@ -205,13 +205,14 @@ function run_error($code, $RID = 0, $DID = 0, $notice = '') { $run_output = ''; $run_logging = ''; - $run_repl_log = array( $notice, $PATH_RID_LOG, $PATH_DID_LOG); - $run_repl_view = array( $notice, $PATH_RID_VIEW, $PATH_DID_VIEW); - $run_repl_fin = array( $notice, $RID, $DID); + $run_repl_log = [ $notice, $PATH_RID_LOG, $PATH_DID_LOG]; + $run_repl_view = [ $notice, $PATH_RID_VIEW, $PATH_DID_VIEW]; + $run_repl_fin = [ $notice, $RID, $DID]; $run_logging = str_replace($run_search, $run_repl_fin, $runtime_messages[$code]); $log_level = POLLER_VERBOSITY_NONE; + if (strpos($run_logging, 'ERROR:') !== false) { $log_level = POLLER_VERBOSITY_LOW; } elseif (strpos($run_logging, 'WARNING:') !== false) { @@ -239,7 +240,7 @@ function runtime($report_id, $queue_id, $start_time = 0) { exit(1); } - //This report is in_process, so flag it! + // This report is in_process, so flag it! in_process($report_id); if (!$run_scheduled) { @@ -250,7 +251,7 @@ function runtime($report_id, $queue_id, $start_time = 0) { $rrdtool_pipe = rrd_init(); // ----- Define variables for Datasource and RRA descriptions ----- - $ds_description = ''; + $ds_description = ''; $result_description = ''; // ----- Define variable for monitoring a valid process ----- @@ -263,7 +264,7 @@ function runtime($report_id, $queue_id, $start_time = 0) { $report_settings = db_fetch_row_prepared('SELECT * FROM plugin_reportit_reports WHERE id = ?', - array($report_id)); + [$report_id]); // ----- auto clean-up RRDlist ----- autocleanup($report_id); @@ -285,7 +286,7 @@ function runtime($report_id, $queue_id, $start_time = 0) { debug($report_definitions, 'Definitions'); // ----- Define variable for dynamic time frame ----- - $dynamic = $report_definitions['report']['sliding'] == 'on' ? true:false; + $dynamic = $report_definitions['report']['sliding'] == 'on' ? true : false; $enable_tmz = read_config_option('reportit_use_tmz'); $dst_support = check_DST_support(); @@ -301,7 +302,7 @@ function runtime($report_id, $queue_id, $start_time = 0) { $number_of_rrds = cacti_count($report_definitions['data_items']); // ----- ERROR CHECK (2) ----- - //Check number of defined RRDs + // Check number of defined RRDs if (!$number_of_rrds > 0) { run_error(2, $report_id); @@ -325,10 +326,10 @@ function runtime($report_id, $queue_id, $start_time = 0) { // We need a key identifier to create columns with a unique name // and an array with the used cf indexes. - $keys = array(); - $rra_indexes = array(); + $keys = []; + $rra_indexes = []; - foreach($report_definitions['measurands'] as $measurand) { + foreach ($report_definitions['measurands'] as $measurand) { $keys[$measurand['abbreviation']] = $measurand['id']; $rra_indexes[$measurand['abbreviation']] = $measurand['cf']; } @@ -346,26 +347,26 @@ function runtime($report_id, $queue_id, $start_time = 0) { // ----- Variables ----- $variables = $report_definitions['variables']; - /************************************************************************************/ - //Define 5 caches to save the result of our system functions during the calculation. + // + // Define 5 caches to save the result of our system functions during the calculation. - $cache = array(); - $df_cache = array(); //Functions > Multi-dimensional - $dm_cache = array(); //Metrics - $dr_cache = array(); //Interim results - $dp_cache = array(); //Functions with parameters >Multi-dimensional - $ds_cache = array(); //Metrics with flag 'spanned' + $cache = []; + $df_cache = []; // Functions > Multi-dimensional + $dm_cache = []; // Metrics + $dr_cache = []; // Interim results + $dp_cache = []; // Functions with parameters >Multi-dimensional + $ds_cache = []; // Metrics with flag 'spanned' - foreach($rra_types as $rra_type) { - foreach($calc_fct_names as $value) { + foreach ($rra_types as $rra_type) { + foreach ($calc_fct_names as $value) { $df_cache[$rra_type][$value] = false; } - foreach($calc_fct_names_params as $value) { + foreach ($calc_fct_names_params as $value) { $dp_cache[$rra_type][$value] = false; } - foreach($calc_fct_aliases as $value) { + foreach ($calc_fct_aliases as $value) { $dp_cache[$rra_type][$value] = false; } } @@ -373,7 +374,7 @@ function runtime($report_id, $queue_id, $start_time = 0) { debug($df_cache, 'Defined Cache > Functions'); debug($dp_cache, 'Defined Cache > Functions with Parameters'); - foreach($report_definitions['measurands'] as $array) { + foreach ($report_definitions['measurands'] as $array) { $dm_cache[$array['abbreviation']] = $array['calc_formula']; } @@ -381,9 +382,9 @@ function runtime($report_id, $queue_id, $start_time = 0) { $cache = get_possible_rra_names($report_definitions['report']['template_id']); - foreach($cache as $rra) { - foreach($dm_cache as $key => $value) { - $name = $key . ':' . $rra; + foreach ($cache as $rra) { + foreach ($dm_cache as $key => $value) { + $name = $key . ':' . $rra; $dr_cache[$name] = false; } } @@ -391,23 +392,24 @@ function runtime($report_id, $queue_id, $start_time = 0) { debug($cache, 'Data Sources - Definition by Cacti'); debug($dr_cache, 'Defined Cache > Interim Results'); - $cache = $report_definitions['measurands']; - foreach($cache as $mm) { + $cache = $report_definitions['measurands']; + + foreach ($cache as $mm) { if ($mm['spanned'] == 'on') { $ds_cache[$mm['abbreviation']] = false; } } debug($ds_cache, 'Defined Cache > Metrics (spanned)'); - /************************************************************************************/ + // // ----- Start analysing each RRD ----- - for($i = 0; $i < $number_of_rrds; $i++) { + for ($i = 0; $i < $number_of_rrds; $i++) { // ----- Interface Settings ----- - $local_data_id = $report_definitions['data_items'][$i]['id']; + $local_data_id = $report_definitions['data_items'][$i]['id']; // ----- Get the local path of the RRD-file that belongs to the local_data_id ----- - $data_source_path = get_data_source_path($local_data_id, true); + $data_source_path = get_data_source_path($local_data_id, true); if ($data_source_path == '') { run_error(5, $report_id, $local_data_id, 'Non existing RRD file.'); @@ -426,7 +428,7 @@ function runtime($report_id, $queue_id, $start_time = 0) { run_error(5, $report_id, $local_data_id, 'Non existing RRD file.'); continue; - } + } $maxValue = $report_definitions['data_items'][$i]['maxValue']; $maxHighValue = $report_definitions['high_counters'][$i]['maxHighValue']; @@ -440,8 +442,8 @@ function runtime($report_id, $queue_id, $start_time = 0) { $shift_endday = day_to_number($report_definitions['data_items'][$i]['end_day']); // ----- Participate reporting times ----- - list($s_hour, $s_min) = explode(':',$s_time); - list($e_hour, $e_min) = explode(':',$e_time); + [$s_hour, $s_min] = explode(':',$s_time); + [$e_hour, $e_min] = explode(':',$e_time); if ($enable_tmz) { if (!isset($timezones[$timezone])) { @@ -455,22 +457,22 @@ function runtime($report_id, $queue_id, $start_time = 0) { } // ----- Participate reporting start- and enddate ----- - list($s_year, $s_month, $s_day) = explode('-',$s_date); - list($e_year, $e_month, $e_day) = explode('-',$e_date); + [$s_year, $s_month, $s_day] = explode('-',$s_date); + [$e_year, $e_month, $e_day] = explode('-',$e_date); // ----- Calculate correct timestamps ----- - $f_sp = ($enable_tmz) ? gmmktime($s_hour-$offset_hour,$s_min-$offset_min,0,$s_month,$s_day,$s_year) : mktime($s_hour,$s_min,0,$s_month,$s_day,$s_year); - $l_sp = ($enable_tmz) ? gmmktime($s_hour-$offset_hour,$s_min-$offset_min,0,$e_month,$e_day,$e_year) : mktime($s_hour,$s_min,0,$e_month,$e_day,$e_year); + $f_sp = ($enable_tmz) ? gmmktime($s_hour - $offset_hour,$s_min - $offset_min,0,$s_month,$s_day,$s_year) : mktime($s_hour,$s_min,0,$s_month,$s_day,$s_year); + $l_sp = ($enable_tmz) ? gmmktime($s_hour - $offset_hour,$s_min - $offset_min,0,$e_month,$e_day,$e_year) : mktime($s_hour,$s_min,0,$e_month,$e_day,$e_year); // ----- Check start and endtime ----- if ($s_time > $e_time) { // Endtime is a part of next day - $f_ep = ($enable_tmz) ? gmmktime($e_hour-$offset_hour,$e_min-$offset_min,0,$s_month,$s_day+1,$s_year) : mktime($e_hour,$e_min,0,$s_month,$s_day+1,$s_year); - $l_ep = ($enable_tmz) ? gmmktime($e_hour-$offset_hour,$e_min-$offset_min,0,$e_month,$e_day+1,$e_year) : mktime($e_hour,$e_min,0,$e_month,$e_day+1,$e_year); + $f_ep = ($enable_tmz) ? gmmktime($e_hour - $offset_hour,$e_min - $offset_min,0,$s_month,$s_day + 1,$s_year) : mktime($e_hour,$e_min,0,$s_month,$s_day + 1,$s_year); + $l_ep = ($enable_tmz) ? gmmktime($e_hour - $offset_hour,$e_min - $offset_min,0,$e_month,$e_day + 1,$e_year) : mktime($e_hour,$e_min,0,$e_month,$e_day + 1,$e_year); } else { // Endtime is a part of same day - $f_ep = ($enable_tmz) ? gmmktime($e_hour-$offset_hour,$e_min-$offset_min,0,$s_month,$s_day,$s_year) : mktime($e_hour,$e_min,0,$s_month,$s_day,$s_year); - $l_ep = ($enable_tmz) ? gmmktime($e_hour-$offset_hour,$e_min-$offset_min,0,$e_month,$e_day,$e_year) : mktime($e_hour,$e_min,0,$e_month,$e_day,$e_year); + $f_ep = ($enable_tmz) ? gmmktime($e_hour - $offset_hour,$e_min - $offset_min,0,$s_month,$s_day,$s_year) : mktime($e_hour,$e_min,0,$s_month,$s_day,$s_year); + $l_ep = ($enable_tmz) ? gmmktime($e_hour - $offset_hour,$e_min - $offset_min,0,$e_month,$e_day,$e_year) : mktime($e_hour,$e_min,0,$e_month,$e_day,$e_year); } // ----- ERROR CHECK (3) ----- @@ -482,12 +484,12 @@ function runtime($report_id, $queue_id, $start_time = 0) { } if ($f_ep > time()) { - $f_ep = time(); + $f_ep = time(); run_error(6, $report_id, $local_data_id); } if ($l_ep > time()) { - $l_ep = time(); + $l_ep = time(); if (!$dynamic) { run_error(6, $report_id, $local_data_id); @@ -515,10 +517,10 @@ function runtime($report_id, $queue_id, $start_time = 0) { } // ----- Set options for rrd_fetch and run it! ----- - $rrd_data = array(); - $valid_rra_indexes = array(); + $rrd_data = []; + $valid_rra_indexes = []; - foreach($rra_types as $rra_type => $rra_index) { + foreach ($rra_types as $rra_type => $rra_index) { $cmd_line = "fetch $data_source_path $rra_type -s $f_sp -e $l_ep"; debug($cmd_line, 'RRDfetch command'); @@ -526,7 +528,7 @@ function runtime($report_id, $queue_id, $start_time = 0) { $rrd_data[$rra_index] = rrdtool_execute($cmd_line, true, RRDTOOL_OUTPUT_STDOUT); if (strlen($rrd_data[$rra_index]) == 0) { - $cf = array_search($rra_index, $rra_types); + $cf = array_search($rra_index, $rra_types, true); run_error(5, $report_id, $local_data_id, "Can not open rrdfile or CF '$cf' does not match."); } else { $valid_rra_indexes[] = $rra_index; @@ -541,9 +543,9 @@ function runtime($report_id, $queue_id, $start_time = 0) { continue; } else { - /* transform data that has not been fetch via the PHP based RRDtool API */ - foreach($rrd_data as $rra_index => $data) { - if (in_array($rra_index, $valid_rra_indexes)) { + // transform data that has not been fetch via the PHP based RRDtool API + foreach ($rrd_data as $rra_index => $data) { + if (in_array($rra_index, $valid_rra_indexes, true)) { transform($data, $rrd_data[$rra_index], $report_definitions['template']); debug($rrd_data[$rra_index], 'Transformed RAW data.'); } @@ -554,9 +556,9 @@ function runtime($report_id, $queue_id, $start_time = 0) { $index = $valid_rra_indexes[0]; if (is_array($rrd_data[$index]) && isset($rrd_data[$index]['start'])) { - $rrd_f_mp = $rrd_data[$index]['start'] + $rrd_data[$index]['step']; //rrd_f_mp = first measured value + $rrd_f_mp = $rrd_data[$index]['start'] + $rrd_data[$index]['step']; // rrd_f_mp = first measured value $rrd_ep = $rrd_data[$index]['end']; - $rrd_p_mp = $rrd_data[$index]['end'] - $rrd_data[$index]['step']; //rrd_p_mp = penultimate measured value + $rrd_p_mp = $rrd_data[$index]['end'] - $rrd_data[$index]['step']; // rrd_p_mp = penultimate measured value $rrd_step = $rrd_data[$index]['step']; $rrd_ds_cnt = $rrd_data[$index]['ds_cnt']; $rrd_ds_namv = $rrd_data[$index]['ds_namv']; @@ -588,19 +590,19 @@ function runtime($report_id, $queue_id, $start_time = 0) { $corr_factor_end = 1; if ($ds_type == 2) { - $corr_factor_start = ($rrd_f_mp - $f_sp)/$rrd_step; - $corr_factor_end = ($l_ep - $rrd_p_mp)/$rrd_step; + $corr_factor_start = ($rrd_f_mp - $f_sp) / $rrd_step; + $corr_factor_end = ($l_ep - $rrd_p_mp) / $rrd_step; } - /* intersect all used data source items get the correct index keys */ + // intersect all used data source items get the correct index keys if (is_array($ds_items)) { - $rrd_ds_namv = array_intersect ($rrd_ds_namv, $ds_items); + $rrd_ds_namv = array_intersect($rrd_ds_namv, $ds_items); } else { - $rrd_ds_namv = array_intersect ($rrd_ds_namv, array($ds_items)); + $rrd_ds_namv = array_intersect($rrd_ds_namv, [$ds_items]); } // ----- Prepare data for normal calculating ----- - foreach($rrd_data as $rra_index => $data) { + foreach ($rrd_data as $rra_index => $data) { $pre_data[$rra_index] = get_prepared_data($rrd_data[$rra_index]['data'], $rrd_ad_data, $rrd_ds_cnt, $ds_type, $corr_factor_start, $corr_factor_end, $rrd_ds_namv, $rrd_nan); @@ -611,20 +613,20 @@ function runtime($report_id, $queue_id, $start_time = 0) { debug($pre_data, 'Data for calculation'); - /* update the data source counter */ + // update the data source counter $rrd_ds_cnt = cacti_count($rrd_ds_namv); // ----- Update variables and create calculating parameters ----- - if ($maxValue !== NULL && $maxValue != 0) { + if ($maxValue !== null && $maxValue != 0) { if ($maxValue > 0 && $maxValue < 4294967295) { foreach ($report_definitions['ds_items'] as $key => $ds_name) { $variables['maxValue:' . $ds_name] = $maxValue; } - } elseif ($maxValue == 4294967295 && $maxHighValue !== Null) { + } elseif ($maxValue == 4294967295 && $maxHighValue !== null) { foreach ($report_definitions['ds_items'] as $key => $ds_name) { - $variables['maxValue:' . $ds_name] = $maxHighValue*1000000; + $variables['maxValue:' . $ds_name] = $maxHighValue * 1000000; } - } elseif ($maxValue == 4294967295 && $maxHighValue === Null) { + } elseif ($maxValue == 4294967295 && $maxHighValue === null) { /** * This is a 10G interface (or higher), but ifHighSpeed counter is not available. * Individual configured maximum per data source item will be preferred if it is higher than the maximum of the 32 Bit counter @@ -658,9 +660,9 @@ function runtime($report_id, $queue_id, $start_time = 0) { $data_local = db_fetch_row_prepared('SELECT * FROM data_local WHERE id = ?', - array($local_data_id)); + [$local_data_id]); - foreach($data_query_variables as $dq_variable) { + foreach ($data_query_variables as $dq_variable) { if (isset($data_local['id'])) { // now fetch the cached data for given query variable $sql = 'SELECT field_value @@ -672,7 +674,7 @@ function runtime($report_id, $queue_id, $start_time = 0) { AND present > 0'; // and update the value for the given data query cache variable - $dq_variable_value = db_fetch_cell_prepared($sql, array($data_local['host_id'], $data_local['snmp_query_id'], $dq_variable, $data_local['snmp_index'])); + $dq_variable_value = db_fetch_cell_prepared($sql, [$data_local['host_id'], $data_local['snmp_query_id'], $dq_variable, $data_local['snmp_index']]); $variables[$dq_variable] = ($dq_variable_value === false) ? REPORTIT_NAN : $dq_variable_value; } else { @@ -687,31 +689,31 @@ function runtime($report_id, $queue_id, $start_time = 0) { debug($variables, 'Variables'); - /***************** Start calculation *****************/ + // Start calculation $results = calculate($pre_data, $params, $variables, $df_cache, $dm_cache, $dr_cache, $dp_cache, $ds_cache); debug($results, 'Calculation results for saving'); - /***************** Start calculation *****************/ + // Start calculation // ----- Create new columns for table 'rrd_results_$report_id' ----- if ($create_result_table_columns == false) { // Create the sql string - $list = ''; + $list = ''; - foreach($results as $key => $value) { - if ($key != '_spanned_') { - foreach($value as $mea_key => $value) { - $list .= " ADD `{$key}__{$keys[$mea_key]}` DOUBLE,"; + foreach ($results as $key => $value) { + if ($key != '_spanned_') { + foreach ($value as $mea_key => $value) { + $list .= " ADD `{$key}__{$keys[$mea_key]}` DOUBLE,"; } - } else { - foreach($value as $mea_key => $value) { - $list .= " ADD `spanned__{$keys[$mea_key]}` DOUBLE,"; + } else { + foreach ($value as $mea_key => $value) { + $list .= " ADD `spanned__{$keys[$mea_key]}` DOUBLE,"; } - } + } } // Remove last comma and complete the sql string - $list = substr($list, 0, strlen($list)-1); + $list = substr($list, 0, strlen($list) - 1); $list = "ALTER TABLE plugin_reportit_results_$report_id $list"; // Add columns @@ -721,29 +723,31 @@ function runtime($report_id, $queue_id, $start_time = 0) { $create_result_table_columns = true; // Update variable 'Datasource description' - foreach($rrd_ds_namv as $value) { + foreach ($rrd_ds_namv as $value) { $ds_description = $ds_description . "$value|"; } // Remove last '|' - $ds_description = substr($ds_description, 0, strlen($ds_description)-1); + $ds_description = substr($ds_description, 0, strlen($ds_description) - 1); // Update variable 'Result Definition' $first_element = reset($results); - foreach($first_element as $key => $value) { + + foreach ($first_element as $key => $value) { $result_description = $result_description . "{$keys[$key]}|"; } // Remove last '|' and add the number of id - $rs_def = substr($result_description, 0, strlen($result_description)-1) . '-' . cacti_count($first_element); + $rs_def = substr($result_description, 0, strlen($result_description) - 1) . '-' . cacti_count($first_element); // Update variable 'Spanned Definition' $spanned_description = ''; - foreach($results['_spanned_'] as $key => $value) { + + foreach ($results['_spanned_'] as $key => $value) { $spanned_description = $spanned_description . "{$keys[$key]}|"; } // Remove last '|' and add the number of id - $sp_def = substr($spanned_description, 0, strlen($spanned_description)-1) . '-' . cacti_count($results['_spanned_']); + $sp_def = substr($spanned_description, 0, strlen($spanned_description) - 1) . '-' . cacti_count($results['_spanned_']); // Set report's state valid $valid_report = true; @@ -751,28 +755,28 @@ function runtime($report_id, $queue_id, $start_time = 0) { // ----- Save results into the MySQL database ----- // Create the sql string - $list = ''; + $list = ''; - foreach($results as $key => $value) { - if ($key != '_spanned_') { - foreach($value as $mea_key => $value) { - $list .= " `{$key}__{$keys[$mea_key]}` = $value,"; + foreach ($results as $key => $value) { + if ($key != '_spanned_') { + foreach ($value as $mea_key => $value) { + $list .= " `{$key}__{$keys[$mea_key]}` = $value,"; } - } else { - foreach($value as $mea_key => $value) { - $list .= " `spanned__{$keys[$mea_key]}` = $value,"; + } else { + foreach ($value as $mea_key => $value) { + $list .= " `spanned__{$keys[$mea_key]}` = $value,"; } - } + } } // Remove last comma - $list = substr($list, 0, strlen($list)-1); + $list = substr($list, 0, strlen($list) - 1); // Save values db_execute("REPLACE plugin_reportit_results_$report_id SET id = $local_data_id, $list"); } - /* store results in the table, with the report data */ + // store results in the table, with the report data // ----- Close socket connection if its open ----- if ($socket_handle != '' && !$run_scheduled) { @@ -799,21 +803,21 @@ function runtime($report_id, $queue_id, $start_time = 0) { // ----- Save/update report data ----- $now = date('Y-m-d H:i:s'); - db_execute_prepared("UPDATE plugin_reportit_reports + db_execute_prepared('UPDATE plugin_reportit_reports SET last_started = ?, last_runtime = ?, start_date = ?, end_date = ?, ds_description = ?, rs_def = ?, sp_def = ? - WHERE id = ?", - array($now, $runtime, $s_date, $e_date, $ds_description, $rs_def, $sp_def, $report_id)); + WHERE id = ?', + [$now, $runtime, $s_date, $e_date, $ds_description, $rs_def, $sp_def, $report_id]); // ----- Archive / Email ----- if ($run_scheduled) { - /* update the XML Archive */ - //if (read_config_option('reportit_archive') == 'on') { + // update the XML Archive + // if (read_config_option('reportit_archive') == 'on') { // update_xml_archive($report_id); - //} + // } - /* export report to custom format */ - //if (read_config_option('reportit_auto_export') == 'on' + // export report to custom format + // if (read_config_option('reportit_auto_export') == 'on' // && $report_definitions['report']['autoexport'] != 'None' // && $report_definitions['report']['autoexport'] != '') { // @@ -822,14 +826,14 @@ function runtime($report_id, $queue_id, $start_time = 0) { // if ($export) { // $export_counter++; // } - //} + // } $report_data = reportit_prepare_store_report_results($report_id, $queue_id, $start_time); if ($report_data) { run_error(13, $report_id, 0, "EMAIL: $error"); } - /* create and send out an email */ + // create and send out an email // if (read_config_option('reportit_email') == 'on') { // if ($report_definitions['report']['auto_email'] == 'on') { // $error = send_scheduled_email('0', $report_id); @@ -866,7 +870,7 @@ function autorrdlist($reportid) { $report_data = db_fetch_row_prepared('SELECT * FROM plugin_reportit_reports WHERE id = ?', - array($reportid)); + [$reportid]); $header_label = $report_data['description'] . ' ID: ' . $reportid; @@ -874,7 +878,7 @@ function autorrdlist($reportid) { $desc = db_fetch_cell_prepared('SELECT name FROM host_template WHERE id = ?', - array($report_data['host_template_id'])); + [$report_data['host_template_id']]); $header_label .= ', using Device Template Filter: ' . $desc; } @@ -883,7 +887,7 @@ function autorrdlist($reportid) { $desc = db_fetch_cell_prepared('SELECT name FROM sites WHERE id = ?', - array($report_data['host_template_id'])); + [$report_data['host_template_id']]); $header_label .= ', using Site Filter: ' . $desc; } @@ -896,18 +900,18 @@ function autorrdlist($reportid) { $current_rows = db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_reportit_data_items WHERE report_id = ?', - array($reportid)); + [$reportid]); - //Get the filter setting by template + // Get the filter setting by template $template_filter = db_fetch_row_prepared('SELECT b.pre_filter, b.data_template_id FROM plugin_reportit_reports AS a INNER JOIN plugin_reportit_templates AS b ON a.template_id = b.id - WHERE a.id = ?', array($reportid));; + WHERE a.id = ?', [$reportid]); - $sql_params = array(); + $sql_params = []; - //Get all RRDs which are not in RRD table and match with filter settings + // Get all RRDs which are not in RRD table and match with filter settings $sql = 'SELECT a.local_data_id AS id, a.name_cache FROM data_template_data AS a LEFT JOIN ( @@ -964,19 +968,19 @@ function autorrdlist($reportid) { $sql_params[] = '%' . get_request_var('txt_filter') . '%'; } - /* set the sql for the device template id */ + // set the sql for the device template id if ($report_data['host_template_id'] != 0) { $sql .= ' AND e.id = ?'; $sql_params[] = $report_data['host_template_id']; } - /* set the sql for the site id */ + // set the sql for the site id if ($report_data['site_id'] != 0) { $sql .= ' AND s.id = ?'; $sql_params[] = $report_data['site_id']; } - /* set the filter on the name cache */ + // set the filter on the name cache if ($report_data['data_source_filter'] != '') { $sql .= ' AND a.name_cache LIKE ?'; $sql_params[] = '%' . $report_data['data_source_filter'] . '%'; @@ -1000,29 +1004,29 @@ function autorrdlist($reportid) { if ($number_of_matches > $maxrrdchg) { array_splice($rrdlist, $maxrrdchg); - /* reduce the number of data items to defined limitation */ + // reduce the number of data items to defined limitation if (read_config_option('log_verbosity', true) == POLLER_VERBOSITY_DEBUG) { cacti_log('Current Rows: ' . $current_rows . ' New Rows: ' . $number_of_matches . ' Max. Change: ' . $maxrrdchg . ' mismatch. Auto-Generate RRD List Processing limited for Report ' . $reportid, false, 'REPORTIT'); } } - $enable_tmz = read_config_option('reportit_use_tmz'); - $tmz = ($enable_tmz) ? "'GMT'" : "'".date('T')."'"; - $columns = ''; - $values = ''; - $rrd = ''; + $enable_tmz = read_config_option('reportit_use_tmz'); + $tmz = ($enable_tmz) ? "'GMT'" : "'" . date('T') . "'"; + $columns = ''; + $values = ''; + $rrd = ''; - /* load data item presets */ + // load data item presets $presets = db_fetch_row_prepared('SELECT * FROM plugin_reportit_presets WHERE id = ?', - array($reportid)); + [$reportid]); if (cacti_sizeof($presets)) { $presets['report_id'] = $reportid; - foreach($presets as $key => $value) { - $columns .= ', ' .$key; + foreach ($presets as $key => $value) { + $columns .= ', ' . $key; if ($key != 'id') { $values .= ',' . db_qstr($value); @@ -1033,16 +1037,16 @@ function autorrdlist($reportid) { $values .= ',' . db_qstr($reportid); } - foreach($rrdlist as $rd) { + foreach ($rrdlist as $rd) { $rrd .= '(' . $rd['id'] . ' ' . $values . '),'; cacti_log('Adding Id: ' . $rd['id'] . ' to Report ' . $reportid, false, 'REPORTIT', POLLER_VERBOSITY_DEBUG); } - $rrd = substr($rrd, 0, strlen($rrd)-1); + $rrd = substr($rrd, 0, strlen($rrd) - 1); $columns = substr($columns, 1); - /* save */ + // save db_execute("INSERT INTO plugin_reportit_data_items ($columns) VALUES $rrd"); } } @@ -1050,7 +1054,7 @@ function autorrdlist($reportid) { /** * autocleanup() * removes automatically all data items which do not exist any longer - * @param int $report_id contains the report identifier + * @param int $report_id contains the report identifier * @return */ function autocleanup($report_id) { @@ -1065,69 +1069,71 @@ function autocleanup($report_id) { db_execute_prepared("DELETE FROM `plugin_reportit_data_items` WHERE `plugin_reportit_data_items`.`report_id` = ? AND `plugin_reportit_data_items`.`id` in ($data_items)", - array($report_id)); + [$report_id]); } } function autoexport($report_id) { - /* load report settings */ + // load report settings $report_settings = db_fetch_row_prepared('SELECT * FROM plugin_reportit_reports WHERE id = ?', - array($report_id)); + [$report_id]); - /* main export folder */ + // main export folder $main_folder = read_config_option('reportit_exp_folder'); + if ($main_folder != '') { $main_folder .= (substr($main_folder, -1) == '/') ? '' : '/'; } else { $main_folder = REPORTIT_EXP_FD; } - /* export folder per template definition */ + // export folder per template definition $template_folder = db_fetch_cell_prepared('SELECT b.export_folder FROM plugin_reportit_reports AS a INNER JOIN plugin_reportit_templates as b ON a.template_id = b.id WHERE a.id = ?', - array($report_id)); + [$report_id]); $template_id = $report_settings['template_id']; - /* define the correct report folder */ + // define the correct report folder if ($template_folder != '') { $template_folder .= (substr($template_folder, -1) == '/') ? '' : '/'; $report_folder = $template_folder . "$report_id/"; } else { - /* check if main export folder is available */ + // check if main export folder is available if (!is_dir($main_folder)) { run_error(17, $report_id, 0, "Main export folder '{$main_folder}' does not exist."); return false; } - $template_folder = $main_folder . "$template_id/"; + $template_folder = $main_folder . "$template_id/"; $report_folder = $template_folder . "$report_id/"; } - /* check if the template folder is available or try to create it */ + // check if the template folder is available or try to create it if (!is_dir($template_folder)) { run_error(16, $report_id, 0, "Export folder '$template_folder' does not exist."); - /* try to create that folder */ + // try to create that folder if (mkdir($template_folder, 0755, true) == false) { run_error(17, $report_id, 0, "Unable to create export folder '$template_folder'."); + return false; } else { run_error(16, $report_id, 0, "New export folder '$template_folder' created."); } } - /* check if report folder is available or try to create it*/ + // check if report folder is available or try to create it if (!is_dir($report_folder)) { run_error(16, $report_id, 0, "Export folder '$report_folder' does not exist."); - /* try to create that folder */ + // try to create that folder if (mkdir($report_folder, 0755, true) == false) { run_error(17, $report_id, 0, "Unable to create export folder '$report_folder'."); @@ -1137,24 +1143,24 @@ function autoexport($report_id) { } } - /* try to create a new report export file */ + // try to create a new report export file $file_format = ($report_settings['autoexport'] != '') ? $report_settings['autoexport'] : 'CSV'; $file_type = ($file_format != 'SML') ? strtolower($file_format) : 'xml'; $filename = $report_settings['start_date'] . '_' . $report_settings['end_date'] . '.' . $file_type; $report_path = $report_folder . $filename; $export_function = 'export_to_' . $file_format; - /* clean up the export folder if necessary */ + // clean up the export folder if necessary if ($report_settings['autoexport_max_records']) { if ($path_handle = opendir($report_folder)) { $file_format_length = strlen($file_format); - $files = array(); + $files = []; while (false !== ($file = readdir($path_handle))) { if (substr($file, -$file_format_length) == $file_type) { - list($start, $end) = explode('_', $file); - list($year, $month, $day) = explode('-', $start); + [$start, $end] = explode('_', $file); + [$year, $month, $day] = explode('-', $start); $files[mktime(0,0,0,$month, $day, $year)] = $file; } @@ -1163,13 +1169,13 @@ function autoexport($report_id) { ksort($files); closedir($path_handle); - if (cacti_sizeof($files)> $report_settings['autoexport_max_records']) { - /* define the number of files that has to be dropped */ + if (cacti_sizeof($files) > $report_settings['autoexport_max_records']) { + // define the number of files that has to be dropped $num_of_drops = sizeof($files) - $report_settings['autoexport_max_records'] + 1; $files = array_slice($files, 0, $num_of_drops); - foreach($files as $filename) { + foreach ($files as $filename) { if (!unlink($report_folder . $filename)) { run_error(17, $report_id, 0, "Unable to delete old export file path '{$report_folder}{$filename}'."); } @@ -1184,7 +1190,9 @@ function autoexport($report_id) { run_error(17, $report_id, 0, "Export path '{$report_path}' is not writable."); return false; - } elseif (!is_writeable(dirname($report_path))) { + } + + if (!is_writeable(dirname($report_path))) { run_error(17, $report_id, 0, "Export path '" . dirname($report_path) . "' is not writable."); return false; @@ -1197,7 +1205,7 @@ function autoexport($report_id) { return false; } - /* load export data and write it into the export file */ + // load export data and write it into the export file if (function_exists($export_function)) { $data = get_prepared_report_data($report_id, 'export'); $data = $export_function($data); @@ -1215,8 +1223,8 @@ function autoexport($report_id) { * display_version - displays version information */ function display_version() { - $version = plugin_reportit_version()['version']; - print "ReportIt Main Poller, Version $version, " . COPYRIGHT_YEARS . PHP_EOL; + $version = plugin_reportit_version()['version']; + print "ReportIt Main Poller, Version $version, " . COPYRIGHT_YEARS . PHP_EOL; } function display_help() { @@ -1226,7 +1234,7 @@ function display_help() { print 'usage: poller_reportit.php [ --report-id=N ] [ --queue-id=N ] [ --scheduled ] [--verbose] [--debug]' . PHP_EOL . PHP_EOL; - print 'Cacti\'s ReportIt main poller. This poller is the launcher for ReportIt reports.' . PHP_EOL . PHP_EOL; + print 'Cacti\'s ReportIt main poller. This poller is the launcher for ReportIt reports.' . PHP_EOL . PHP_EOL; print 'Provide either of the following:' . PHP_EOL; print ' --report-id=N Run as specific report now' . PHP_EOL; @@ -1237,4 +1245,3 @@ function display_help() { print ' --scheduled Run the scheduled reports' . PHP_EOL; print ' --verbose Provide verbose output' . PHP_EOL . PHP_EOL; } - diff --git a/reportit.php b/reportit.php index 3a29eae..9f635e9 100644 --- a/reportit.php +++ b/reportit.php @@ -88,8 +88,8 @@ } function report_wizard() { - $templates_list = array(); - $templates = array(); + $templates_list = []; + $templates = []; $templates_list = db_fetch_assoc("SELECT id, description FROM plugin_reportit_templates @@ -114,15 +114,15 @@ function report_wizard() { } else { $save_html = " "; - foreach($templates_list as $tmp) { + foreach ($templates_list as $tmp) { $templates[$tmp['id']] = $tmp['name']; } print " -

" . __('Choose a template this report should depend on.', 'reportit') . "

+

" . __('Choose a template this report should depend on.', 'reportit') . '

- "; + '; form_dropdown('template', $templates, '', '', '', '', ''); @@ -145,7 +145,7 @@ function report_wizard() { function report_filter() { global $item_rows; - html_start_box( __('Report Filters', 'reportit'), '100%', '', '3', 'center', 'reportit.php?action=report_add'); + html_start_box(__('Report Filters', 'reportit'), '100%', '', '3', 'center', 'reportit.php?action=report_add'); ?> @@ -153,30 +153,34 @@ function report_filter() { @@ -228,51 +232,53 @@ function standard() { $myId = my_id(); $myName = my_name(); $reportAdmin = re_admin(); - $tmz = (read_config_option('reportit_show_tmz') == 'on') ? '('.date('T').')' : ''; + $tmz = (read_config_option('reportit_show_tmz') == 'on') ? '(' . date('T') . ')' : ''; $enable_tmz = read_config_option('reportit_use_tmz'); - /* ================= input validation and session storage ================= */ - $filters = array( - 'rows' => array( - 'filter' => FILTER_VALIDATE_INT, + // ================= input validation and session storage ================= + $filters = [ + 'rows' => [ + 'filter' => FILTER_VALIDATE_INT, 'pageset' => true, 'default' => '-1' - ), - 'page' => array( - 'filter' => FILTER_VALIDATE_INT, + ], + 'page' => [ + 'filter' => FILTER_VALIDATE_INT, 'default' => '1' - ), - 'filter' => array( - 'filter' => FILTER_CALLBACK, + ], + 'filter' => [ + 'filter' => FILTER_CALLBACK, 'pageset' => true, 'default' => '', - 'options' => array('options' => 'sanitize_search_string') - ), - 'sort_column' => array( - 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'] + ], + 'sort_column' => [ + 'filter' => FILTER_CALLBACK, 'default' => 'name', - 'options' => array('options' => 'sanitize_search_string') - ), - 'sort_direction' => array( - 'filter' => FILTER_CALLBACK, + 'options' => ['options' => 'sanitize_search_string'] + ], + 'sort_direction' => [ + 'filter' => FILTER_CALLBACK, 'default' => 'ASC', - 'options' => array('options' => 'sanitize_search_string') - ), - 'owner' => array( - 'filter' => FILTER_VALIDATE_INT, + 'options' => ['options' => 'sanitize_search_string'] + ], + 'owner' => [ + 'filter' => FILTER_VALIDATE_INT, 'default' => '-1' - ), - 'template' => array( - 'filter' => FILTER_VALIDATE_INT, + ], + 'template' => [ + 'filter' => FILTER_VALIDATE_INT, 'default' => '-1' - ), - ); + ], + ]; validate_store_request_vars($filters, 'sess_reportit_reports'); - /* ================= Input validation ================= */ + // ================= Input validation ================= + + $where_clauses = []; if ($reportAdmin) { - /* fetch user names */ + // fetch user names $ownerlist = db_fetch_assoc('SELECT DISTINCT a.user_id as id, c.username FROM plugin_reportit_reports AS a LEFT JOIN plugin_reportit_templates AS b @@ -281,20 +287,21 @@ function standard() { ON c.id = a.user_id ORDER BY c.username'); - /* fetch template list */ + // fetch template list $sql = 'SELECT DISTINCT b.id, b.description FROM plugin_reportit_reports AS a INNER JOIN plugin_reportit_templates AS b ON b.id = a.template_id'; if (get_request_var('owner') !== '-1' && !isempty_request_var('owner')) { - $sql .= ' WHERE a.user_id = ' . get_request_var('owner') . ' ORDER BY b.description'; + $sql .= ' WHERE a.user_id = ' . (int) get_request_var('owner') . ' ORDER BY b.description'; $templatelist = db_fetch_assoc($sql); - if (cacti_sizeof($templatelist)>0) { - foreach($templatelist as $template) { + if (cacti_sizeof($templatelist) > 0) { + foreach ($templatelist as $template) { if ($template['id'] == get_request_var('template')) { $a = 1; + break; } } @@ -308,28 +315,33 @@ function standard() { } } - /* form the 'where' clause for our main sql query */ + // form the 'where' clause for our main sql query if (get_request_var('filter') != '') { - $affix .= " WHERE a.name LIKE '%" . get_request_var('filter') . "%'"; + $where_clauses[] = 'a.name LIKE ' . db_qstr('%' . get_request_var('filter') . '%'); } - /* check admin's filter settings */ + // check admin's filter settings if ($reportAdmin) { if (get_request_var('owner') == '-1') { - /* filter nothing */ + // filter nothing } elseif (!isempty_request_var('owner')) { - /* show only data items of selected report owner */ - $affix .= ' AND a.user_id =' . get_request_var('owner'); + // show only data items of selected report owner + $where_clauses[] = 'a.user_id = ' . (int) get_request_var('owner'); } + if (get_request_var('template') == '-1') { - /* filter nothing */ + // filter nothing } elseif (!isempty_request_var('template')) { - /* show only data items of selected template */ - $affix .= ' AND a.template_id =' . get_request_var('template'); + // show only data items of selected template + $where_clauses[] = 'a.template_id = ' . (int) get_request_var('template'); } } else { - /* filter for user */ - $affix .= "AND a.user_id = $myId"; + // filter for user + $where_clauses[] = 'a.user_id = ' . (int) $myId; + } + + if (cacti_sizeof($where_clauses)) { + $affix = ' WHERE ' . implode(' AND ', $where_clauses); } if (get_request_var('rows') == '-1') { @@ -350,60 +362,60 @@ function standard() { LEFT JOIN user_auth AS d ON d.id = a.user_id' . $affix . ' ORDER BY ' . get_request_var('sort_column') . ' ' . get_request_var('sort_direction') . - ' LIMIT ' . ($rows*(get_request_var('page')-1)) . ',' . $rows); + ' LIMIT ' . ($rows * (get_request_var('page') - 1)) . ',' . $rows); - $desc_array = array( - 'name' => array( + $desc_array = [ + 'name' => [ 'display' => __('Name', 'reportit'), 'sort' => 'ASC', - ), - 'nosort0' => array( - 'display' => __("Period %s From - To", $tmz, 'reportit') - ), - 'frequency' => array( + ], + 'nosort0' => [ + 'display' => __('Period %s From - To', $tmz, 'reportit') + ], + 'frequency' => [ 'display' => __('Schedule', 'reportit'), 'sort' => 'ASC' - ), - 'state' => array( + ], + 'state' => [ 'display' => __('State', 'reportit'), 'sort' => 'ASC', - ), - 'next_start' => array( + ], + 'next_start' => [ 'display' => __('Next Start %s', $tmz, 'reportit'), 'align' => 'right', 'sort' => 'ASC', - ), - 'last_started' => array( + ], + 'last_started' => [ 'display' => __('Last Started %s', $tmz, 'reportit'), 'align' => 'right', 'sort' => 'ASC', - ), - 'last_runtime' => array( + ], + 'last_runtime' => [ 'display' => __('Last Runtime', 'reportit'), 'align' => 'right', 'sort' => 'ASC', - ), - 'public' => array( + ], + 'public' => [ 'display' => __('Public', 'reportit'), 'align' => 'right', 'sort' => 'ASC', - ), - 'enabled' => array( + ], + 'enabled' => [ 'display' => __('Enabled', 'reportit'), 'align' => 'right', 'sort' => 'ASC', - ), - 'ds_cnt' => array( + ], + 'ds_cnt' => [ 'display' => __('Data Sources', 'reportit'), 'align' => 'right', 'sort' => 'DESC', - ), - ); + ], + ]; - /* start with HTML output */ + // start with HTML output report_filter(); - $nav = html_nav_bar('reportit.php?filter=' . get_request_var('filter'), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, sizeof($desc_array), __('Reports', 'reportit'), 'page', 'main'); + $nav = html_nav_bar('reportit.php?filter=' . rawurlencode(get_request_var('filter')), MAX_DISPLAY_PAGES, get_request_var('page'), $rows, $total_rows, sizeof($desc_array), __('Reports', 'reportit'), 'page', 'main'); print $nav; @@ -414,7 +426,7 @@ function standard() { html_header_sort_checkbox($desc_array, get_request_var('sort_column'), get_request_var('sort_direction'), false, 'reportit.php'); if (cacti_sizeof($report_list)) { - foreach($report_list as $report) { + foreach ($report_list as $report) { $link = 'reportit.php?action=report_edit&id=' . $report['id']; form_alternate_row('line' . $report['id'], true); @@ -423,7 +435,7 @@ function standard() { if ($report['sliding'] == 'on' && $report['last_started'] == '0000-00-00 00:00:00') { $dates = rp_get_timespan($report['preset_timespan'], $report['present'], $enable_tmz); - form_selectable_cell(date(config_date_format(), strtotime($dates['start_date'])) . " - " . date(config_date_format(), strtotime($dates['end_date'])), $report['id']); + form_selectable_cell(date(config_date_format(), strtotime($dates['start_date'])) . ' - ' . date(config_date_format(), strtotime($dates['end_date'])), $report['id']); } else { form_selectable_cell(($report['start_date'] == '0000-00-00' ? '00-00-0000' : date(config_date_format(), strtotime($report['start_date']))) . ' - ' . ($report['start_date'] == '0000-00-00' ? '00-00-0000' : date(config_date_format(), strtotime($report['end_date']))), $report['id']); } @@ -442,7 +454,7 @@ function standard() { form_selectable_cell(filter_value($report['last_started'], '', $link), $report['id'], '', 'right'); } - form_selectable_cell(sprintf("%0.2f sec", $report['last_runtime']), $report['id'], '', 'right'); + form_selectable_cell(sprintf('%0.2f sec', $report['last_runtime']), $report['id'], '', 'right'); form_selectable_cell(html_check_icon($report['public']), $report['id'], '', 'right'); form_selectable_cell(html_check_icon($report['enabled']), $report['id'], '', 'right'); @@ -459,7 +471,7 @@ function standard() { form_end_row(); } } else { - print ""; + print "'; } html_end_box(true); @@ -474,41 +486,41 @@ function standard() { } function remove_recipient() { - /* ================= input validation ================= */ + // ================= input validation ================= get_filter_request_var('id'); get_filter_request_var('rec'); - /* ==================================================== */ + // ==================================================== - /* ==================== Checkpoint ==================== */ + // ==================== Checkpoint ==================== my_report(get_request_var('id')); - /* ==================================================== */ + // ==================================================== db_execute_prepared('DELETE FROM plugin_reportit_recipients WHERE id = ? AND report_id = ?', - array(get_request_var('rec'), get_request_var('id'))); + [get_request_var('rec'), get_request_var('id')]); header('Location: reportit.php?action=report_edit&id=' . get_request_var('id') . '&tab=email'); exit; } function form_save() { - global $templates, $timespans, $frequency, $timezone, $shifttime, $shifttime2, $weekday, $format, $add_recipients; + global $templates, $timespans, $frequency, $timezone, $shifttime, $shifttime2, $weekday, $format, $add_recipients; global $timezone, $shifttime, $shifttime2, $weekday; - $owner = array(); + $owner = []; $post = $_POST; - $sql = "SELECT DISTINCT a.id, a.username as name FROM user_auth AS a + $sql = 'SELECT DISTINCT a.id, a.username as name FROM user_auth AS a INNER JOIN user_auth_realm AS b - ON a.id = b.user_id WHERE (b.realm_id = " . REPORTIT_USER_OWNER . " OR b.realm_id = " . REPORTIT_USER_VIEWER . ") - ORDER BY username"; + ON a.id = b.user_id WHERE (b.realm_id = ' . REPORTIT_USER_OWNER . ' OR b.realm_id = ' . REPORTIT_USER_VIEWER . ') + ORDER BY username'; $owner = db_custom_fetch_assoc($sql, 'id', false); - /* ================= Input Validation ================= */ - get_filter_request_var('tab', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '(general|presets|admin|email|items)'))); + // ================= Input Validation ================= + get_filter_request_var('tab', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '(general|presets|admin|email|items)']]); get_filter_request_var('id'); get_filter_request_var('template_id'); get_filter_request_var('site_id'); @@ -516,20 +528,18 @@ function form_save() { get_filter_request_var('id'); get_filter_request_var('owner'); - /* item specific validation */ + // item specific validation get_filter_request_var('report_id'); get_filter_request_var('timezone'); get_filter_request_var('start_time'); get_filter_request_var('end_time'); get_filter_request_var('start_day'); get_filter_request_var('end_day'); - /* ==================================================== */ + // ==================================================== - if (!isset($post['tab'])) { - $post['tab'] = 'general'; - } + $post['tab'] ??= 'general'; - /* stop if user is not authorised to save a report config */ + // stop if user is not authorised to save a report config if ($post['tab'] != 'items') { if ($post['id'] != 0) { my_report($post['id']); @@ -539,13 +549,13 @@ function form_save() { } if (!re_owner()) { - die_html_custom_error(__('Not Authorized', 'reportit'), true); //this should normally done by Cacti itself + die_html_custom_error(__('Not Authorized', 'reportit'), true); // this should normally done by Cacti itself } - /* check for the type of saving if it was sent through the email tab */ + // check for the type of saving if it was sent through the email tab switch($post['tab']) { case 'presets': - input_validate_input_blacklist($post['id'], array(0)); + input_validate_input_blacklist($post['id'], [0]); input_validate_input_key($post['timezone'], $timezone, true); input_validate_input_key($post['start_time'], $shifttime); input_validate_input_key($post['end_time'], $shifttime2); @@ -563,18 +573,18 @@ function form_save() { form_input_validate($post['email_body'], 'email_body', '', false, 3); input_validate_input_key($post['email_format'], $format); } else { - /* if javascript is disabled */ + // if javascript is disabled form_input_validate($post['email_address'], 'email_address', '', false, 3); } break; case 'items': if (isset($post['save_component_rrdlist'])) { - /* ================= input validation ================= */ + // ================= input validation ================= locked(my_template($post['report_id'])); - /* ==================================================== */ + // ==================================================== - /* check start and end of shifttime */ + // check start and end of shifttime $a = $post['start_time']; $b = $post['end_time']; @@ -582,7 +592,7 @@ function form_save() { $b = count($shifttime); } - /* prepare data array */ + // prepare data array $rrdlist_data['id'] = $post['id']; $rrdlist_data['report_id'] = $post['report_id']; $rrdlist_data['start_day'] = $weekday[$post['start_day']]; @@ -595,10 +605,10 @@ function form_save() { $rrdlist_data['timezone'] = $timezone[$post['timezone']]; } - /* save settings */ - sql_save($rrdlist_data, 'plugin_reportit_data_items', array('id', 'report_id'), false); + // save settings + sql_save($rrdlist_data, 'plugin_reportit_data_items', ['id', 'report_id'], false); - /* return to list view */ + // return to list view raise_message(1); header('Location: reportit.php?action=report_edit&tab=items&id=' . $post['report_id']); @@ -611,12 +621,12 @@ function form_save() { input_validate_input_key($post['preset_timespan'], $timespans, true); } - /* if template is locked we don't know if the variables have been changed */ + // if template is locked we don't know if the variables have been changed locked($post['template_id']); form_input_validate($post['name'], 'name', '', false, 3); - /* validate start- and end date if sliding time should not be used */ + // validate start- and end date if sliding time should not be used if (!isset($post['sliding'])) { if (!preg_match('/^\d{4}\-\d{2}\-\d{2}$/', $post['start_date'])) { session_custom_error_message('start_date', 'Invalid date'); @@ -627,15 +637,21 @@ function form_save() { } if (!is_error_message()) { - list($ys, $ms, $ds) = explode('-', $post['start_date']); - list($ye, $me, $de) = explode('-', $post['end_date']); + [$ys, $ms, $ds] = explode('-', $post['start_date']); + [$ye, $me, $de] = explode('-', $post['end_date']); - if (!checkdate($ms, $ds, $ys)) session_custom_error_message('start_date', 'Invalid date'); - if (!checkdate($me, $de, $ye)) session_custom_error_message('end_date', 'Invalid date'); + if (!checkdate($ms, $ds, $ys)) { + session_custom_error_message('start_date', 'Invalid date'); + } + + if (!checkdate($me, $de, $ye)) { + session_custom_error_message('end_date', 'Invalid date'); + } if (($start_date = mktime(0,0,0,$ms,$ds,$ys)) > ($end_date = mktime(0,0,0,$me,$de,$ye)) || $ys > $ye || $ys > date('Y')) { session_custom_error_message('start_date', 'Start date lies ahead'); } + if (($end_date = mktime(0,0,0,$me,$de,$ye)) > time() || $ye > date('Y')) { session_custom_error_message('start_date', 'End date lies ahead'); } @@ -643,7 +659,7 @@ function form_save() { } } - /* return if validation failed */ + // return if validation failed if (is_error_message()) { header('Location: reportit.php?action=report_edit&id=' . $post['id'] . '&tab=' . $post['tab']); exit; @@ -669,9 +685,9 @@ function form_save() { $report_data['site_id'] = $post['site_id']; $report_data['host_template_id'] = $post['host_template_id']; $report_data['data_source_filter'] = $post['data_source_filter']; - $report_data['autorrdlist'] = (isset($post['autorrdlist']) ? 'on':''); + $report_data['autorrdlist'] = (isset($post['autorrdlist']) ? 'on' : ''); - /* save settings */ + // save settings sql_save($report_data, 'plugin_reportit_reports'); sql_save($rrdlist_data, 'plugin_reportit_presets', 'id', false); @@ -686,12 +702,13 @@ function form_save() { $report_data['email'] = $post['email']; $report_data['bcc'] = $post['bcc']; - /* save settings */ + // save settings sql_save($report_data, 'plugin_reportit_reports'); } else { $id = $post['id']; - $addresses = array(); + $addresses = []; + if ($post['email_address'] != '' && strpos($post['email_address'], ';')) { $addresses = explode(';', $post['email_address']); } elseif ($post['email_address'] != '' && strpos($post['email_address'], ',')) { @@ -700,7 +717,8 @@ function form_save() { $addresses[] = $post['email_address']; } - $recipients = array(); + $recipients = []; + if ($post['email_recipient'] != '' && strpos($post['email_recipient'], ';')) { $recipients = explode(';', $post['email_recipient']); } elseif ($post['email_recipient'] != '' && strpos($post['email_recipient'], ',')) { @@ -710,10 +728,10 @@ function form_save() { } if (cacti_sizeof($addresses)) { - foreach($addresses as $key => $value) { + foreach ($addresses as $key => $value) { $value = trim($value); - if (!preg_match("/(^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*\\.[a-zA-Z]{2,3}$)/", $value)) { + if (!preg_match('/(^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*\\.[a-zA-Z]{2,3}$)/', $value)) { cacti_log('WARNING: Unable to add email address "' . $value . '" to RIReport[' . $id . ']', false, 'REPORTIT'); session_custom_error_message('email_address', 'Invalid email address'); } else { @@ -725,7 +743,7 @@ function form_save() { db_execute_prepared('INSERT INTO plugin_reportit_recipients (report_id, email, name) VALUES (?,?,?)', - array($id, $value, $name)); + [$id, $value, $name]); } } } @@ -733,11 +751,11 @@ function form_save() { break; case 'items': - /* ================= input validation ================= */ + // ================= input validation ================= locked(my_template($post['report_id'])); - /* ==================================================== */ + // ==================================================== - /* check start and end of shifttime */ + // check start and end of shifttime $a = $post['start_time']; $b = $post['end_time']; @@ -745,7 +763,7 @@ function form_save() { $b = count($shifttime); } - /* prepare data array */ + // prepare data array $rrdlist_data['id'] = $post['id']; $rrdlist_data['report_id'] = $post['report_id']; $rrdlist_data['start_day'] = $weekday[$post['start_day']]; @@ -758,17 +776,17 @@ function form_save() { $rrdlist_data['timezone'] = $timezone[$post['timezone']]; } - /* save settings */ - sql_save($rrdlist_data, 'plugin_reportit_data_items', array('id', 'report_id'), false); + // save settings + sql_save($rrdlist_data, 'plugin_reportit_data_items', ['id', 'report_id'], false); - /* return to list view */ + // return to list view raise_message(1); break; default: $report_data['id'] = $post['id']; - $report_data['user_id'] = isset($post['owner']) ? $post['owner']:''; + $report_data['user_id'] = $post['owner'] ?? ''; $report_data['name'] = $post['name']; $report_data['template_id'] = $post['template_id']; $report_data['public'] = $post['public']; @@ -784,26 +802,26 @@ function form_save() { $report_data['present'] = $post['present']; } - $report_data['enabled'] = (isset($post['enabled']) ? 'on':''); - $report_data['autorrdlist'] = (isset($post['autorrdlist']) ? 'on':''); - $report_data['auto_email'] = (isset($post['auto_email']) ? 'on':''); - $report_data['graph_permission'] = (isset($post['graph_permission']) ? 'on':''); + $report_data['enabled'] = (isset($post['enabled']) ? 'on' : ''); + $report_data['autorrdlist'] = (isset($post['autorrdlist']) ? 'on' : ''); + $report_data['auto_email'] = (isset($post['auto_email']) ? 'on' : ''); + $report_data['graph_permission'] = (isset($post['graph_permission']) ? 'on' : ''); $report_data = api_scheduler_augment_save($report_data, $post); - /* define the owner if it's a new configuration */ + // define the owner if it's a new configuration if ($post['id'] == 0) { $report_data['user_id'] = my_id(); } - //Now we've to keep our variables - $vars = array(); - $rvars = array(); - $var_data = array(); + // Now we've to keep our variables + $vars = []; + $rvars = []; + $var_data = []; - foreach($post as $key => $value) { + foreach ($post as $key => $value) { if (strstr($key, 'var_')) { - $id = substr($key, 4); + $id = substr($key, 4); $vars[$id] = $value; } } @@ -814,53 +832,56 @@ function form_save() { ON a.id = b.variable_id AND report_id = ? WHERE a.template_id = ?', - array($post['id'], $post['template_id'])); + [$post['id'], $post['template_id']]); - foreach($rvars as $key => $v) { + foreach ($rvars as $key => $v) { $value = $vars[$v['id']]; + if ($v['input_type'] == 1) { - $i = 0; - $array = array(); - $a = $v['min_value']; - $b = $v['max_value']; - $c = $v['stepping']; + $i = 0; + $array = []; + $a = $v['min_value']; + $b = $v['max_value']; + $c = $v['stepping']; - for($i=$a; $i <= $b; $i+=$c) { + for ($i = $a; $i <= $b; $i += $c) { $array[] = $i; } $value = $array[$value]; - if ($value > $v['max_value'] || $value < $v['min_value']) die_html_custom_error('', true); + if ($value > $v['max_value'] || $value < $v['min_value']) { + die_html_custom_error('', true); + } } else { if ($value > $v['max_value'] || $value < $v['min_value']) { - session_custom_error_message($v['name'], "{$v['name']} is out of range"); + break; } } - //If there's no error we can go on - $var_data[] = array( - 'id' => (($v['b_id'] != NULL) ? $v['b_id'] : 0), + // If there's no error we can go on + $var_data[] = [ + 'id' => (($v['b_id'] != null) ? $v['b_id'] : 0), 'template_id' => $post['template_id'], 'report_id' => $post['id'], 'variable_id' => $v['id'], 'value' => $value - ); + ]; } - /* start saving process or return is_error_message()*/ + // start saving process or return is_error_message() if (is_error_message()) { header('Location: reportit.php?action=report_edit&id=' . $post['id'] . '&tab=' . $post['tab']); exit; } else { - /* save report config */ + // save report config $report_id = sql_save($report_data, 'plugin_reportit_reports'); - /* save additional report variables */ - foreach($var_data as $data) { + // save additional report variables + foreach ($var_data as $data) { if ($post['id'] == 0) { $data['report_id'] = $report_id; } @@ -870,7 +891,7 @@ function form_save() { } } - header('Location: reportit.php?action=report_edit&id=' . (isset($report_id)? $report_id : $post['id']) . '&tab=' . $post['tab']); + header('Location: reportit.php?action=report_edit&id=' . ($report_id ?? $post['id']) . '&tab=' . $post['tab']); raise_message(1); } @@ -885,49 +906,49 @@ function report_edit() { set_request_var('tab', 'general'); } - /* ================= input validation ================= */ - get_filter_request_var('tab', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '(general|presets|admin|email|items)'))); + // ================= input validation ================= + get_filter_request_var('tab', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '(general|presets|admin|email|items)']]); get_filter_request_var('id'); get_filter_request_var('template'); - /* ==================================================== */ + // ==================================================== - /* ==================== Checkpoint ==================== */ + // ==================== Checkpoint ==================== my_report(get_request_var('id')); - /* ==================================================== */ + // ==================================================== - /* load config settings if it's not a new one */ + // load config settings if it's not a new one if (!isempty_request_var('id')) { $report_data = db_fetch_row_prepared('SELECT * FROM plugin_reportit_reports WHERE id = ?', - array(get_request_var('id'))); + [get_request_var('id')]); $rrdlist_data = db_fetch_row_prepared('SELECT * FROM plugin_reportit_presets WHERE id = ?', - array(get_request_var('id'))); + [get_request_var('id')]); $report_recipients = db_fetch_assoc_prepared('SELECT * FROM plugin_reportit_recipients WHERE report_id = ?', - array(get_request_var('id'))); + [get_request_var('id')]); $header_label = '[edit: ' . $report_data['name'] . ']'; - /* update rrdlist_data */ + // update rrdlist_data if ($rrdlist_data) { - $rrdlist_data['timezone'] = array_search($rrdlist_data['timezone'],$timezone); - $rrdlist_data['start_time'] = array_search($rrdlist_data['start_time'],$shifttime); - $rrdlist_data['end_time'] = array_search($rrdlist_data['end_time'],$shifttime2); - $rrdlist_data['start_day'] = array_search($rrdlist_data['start_day'],$weekday); - $rrdlist_data['end_day'] = array_search($rrdlist_data['end_day'],$weekday); + $rrdlist_data['timezone'] = array_search($rrdlist_data['timezone'],$timezone, true); + $rrdlist_data['start_time'] = array_search($rrdlist_data['start_time'],$shifttime, true); + $rrdlist_data['end_time'] = array_search($rrdlist_data['end_time'],$shifttime2, true); + $rrdlist_data['start_day'] = array_search($rrdlist_data['start_day'],$weekday, true); + $rrdlist_data['end_day'] = array_search($rrdlist_data['end_day'],$weekday, true); } - /* update report_data array for getting compatible to Cacti's drawing functions */ - $report_data['preset_timespan'] = array_search($report_data['preset_timespan'], $timespans); + // update report_data array for getting compatible to Cacti's drawing functions + $report_data['preset_timespan'] = array_search($report_data['preset_timespan'], $timespans, true); - /* replace all binary settings to get compatible with Cacti's draw functions */ - $rpm = array( + // replace all binary settings to get compatible with Cacti's draw functions + $rpm = [ 'public', 'sliding', 'present', @@ -938,39 +959,37 @@ function report_edit() { 'auto_email', 'email_compression', 'autoexport_no_formatting' - ); + ]; - foreach($report_data as $key => $value) { - if (in_array($key, $rpm)) { + foreach ($report_data as $key => $value) { + if (in_array($key, $rpm, true)) { if ($value == 1) { $report_data[$key] = 'on'; } } } - /* load values for host_template_filter */ + // load values for host_template_filter $filter = db_fetch_cell_prepared('SELECT pre_filter FROM plugin_reportit_templates WHERE id = ?', - array($report_data['template_id'])); + [$report_data['template_id']]); $tmp = db_fetch_assoc_prepared('SELECT id, description FROM plugin_reportit_templates WHERE pre_filter = ?', - array($filter)); + [$filter]); } else { - $header_label = '[new]'; - $report_data = array(); + $header_label = '[new]'; + $report_data = []; $report_data['user_id'] = my_id(); } - $id = (isset_request_var('id') ? get_request_var('id') : '0'); - $rrdlist_data['id']= $id; + $id = (isset_request_var('id') ? get_request_var('id') : '0'); + $rrdlist_data['id'] = $id; if (isset_request_var('template')) { - if (!isset($_SESSION['reportit']['template'])) { - $_SESSION['reportit']['template'] = get_request_var('template'); - } + $_SESSION['reportit']['template'] ??= get_request_var('template'); } if (isset($report_data['template_id'])) { @@ -981,7 +1000,7 @@ function report_edit() { $template_id = 0; } - /* leave if base template is locked */ + // leave if base template is locked if ($template_id) { locked($template_id); } @@ -991,11 +1010,11 @@ function report_edit() { $report_data['template'] = db_fetch_cell_prepared('SELECT description FROM plugin_reportit_templates WHERE id = ?', - array($template_id)); + [$template_id]); - /* start with HTML output */ + // start with HTML output if ($id != 0) { - /* remove the email tab if emailing is deactivated globally */ + // remove the email tab if emailing is deactivated globally if (read_config_option('reportit_email') != 'on') { unset($tabs['email']); } @@ -1004,18 +1023,18 @@ function report_edit() { unset($tabs['email']); } - /* draw the categories tabs on the top of the page */ + // draw the categories tabs on the top of the page $current_tab = get_request_var('tab'); if (cacti_sizeof($tabs)) { $i = 0; - /* draw the tabs */ + // draw the tabs print "
- + - '> + '> - + - ' id='refresh'> - ' id='clear'> + ' id='refresh'> + ' id='clear'>
" . __('No reports', 'reportit') . "
" . __('No reports', 'reportit') . '
-
'> + '> @@ -1286,7 +1309,7 @@ function report_edit() { "; +$escaped = htmlspecialchars($payload, ENT_QUOTES, 'UTF-8'); + +if (strpos($escaped, '
- + - '> + '> - + - > - + > + - ' id='refresh'> - ' id='clear'> + ' id='refresh'> + ' id='clear'>