Completed
Push — development ( 3cb167...9e6f02 )
by Sebastian
15s
created

Monitoring::getLastCronStarted()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 4 and the first side effect is on line 2.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;
3
4
class Monitoring extends Base {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
5
   protected $table = 'monitoring';
6
7
  /**
8
   * Store Uptime Robot status information as JSON in settings table
9
   * @param none
10
   * @return bool true on success, false on error
11
   **/
12
  public function storeUptimeRobotStatus() {
13
    if ($api_keys = $this->setting->getValue('monitoring_uptimerobot_api_keys')) {
14
      $aJSONData = array();
0 ignored issues
show
Unused Code introduced by
$aJSONData is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
15
      $url = 'https://api.uptimerobot.com';
16
      $aMonitors = explode(',', $api_keys);
17
      foreach ($aMonitors as $aData) {
18
        $temp = explode('|', $aData);
19
        $aMonitor['api_key'] = trim($temp[0]);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aMonitor was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aMonitor = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
20
        $aMonitor['monitor_id'] = trim($temp[1]);
0 ignored issues
show
Bug introduced by
The variable $aMonitor does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
21
        $target = '/getMonitors?apiKey=' . $aMonitor['api_key'] . '&monitors=' . $aMonitor['monitor_id'] . '&format=json&noJsonCallback=1&customUptimeRatio=1-7-30&logs=1';
22
        $aMonitorStatus = $this->tools->getApi($url, $target);
0 ignored issues
show
Bug introduced by
The property tools does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
23
        if (!$aMonitorStatus || @$aMonitorStatus['stat'] == 'fail') {
24
          if (is_array($aMonitorStatus) && array_key_exists('message', @$aMonitorStatus)) {
25
            $this->setErrorMessage($this->getErrorMsg('E0032', $aMonitorStatus['message']));
26
          } else {
27
            $this->setErrorMessage($this->getErrorMsg('E0032', $this->tools->getError()));
28
          }
29
          return false;
30
        }
31
        $aMonitorStatus['monitors']['monitor'][0]['customuptimeratio'] = explode('-', $aMonitorStatus['monitors']['monitor'][0]['customuptimeratio']);
32
        $aAllMonitorsStatus[] = $aMonitorStatus['monitors']['monitor'][0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aAllMonitorsStatus was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aAllMonitorsStatus = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
33
      }
34
      if (!$this->setting->setValue('monitoring_uptimerobot_status', json_encode($aAllMonitorsStatus)) || !$this->setting->setValue('monitoring_uptimerobot_lastcheck', time())) {
0 ignored issues
show
Bug introduced by
The property setting does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The variable $aAllMonitorsStatus does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
35
        $this->setErrorMessage($this->getErrorMsg('E0033'), $setting->getError());
0 ignored issues
show
Bug introduced by
The variable $setting does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Unused Code introduced by
The call to Monitoring::setErrorMessage() has too many arguments starting with $setting->getError().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
36
        return false;
37
      }
38
    }
39
    return true;
40
  }
41
42
  /**
43
   * Fetch Uptime Robot Status from settings table
44
   * @param none
45
   * @return array Data on success, false on failure
46
   **/
47
  public function getUptimeRobotStatus() {
48
    if ($json = $this->setting->getValue('monitoring_uptimerobot_status'))
49
      return json_decode($json, true);
50
    return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Monitoring::getUptimeRobotStatus of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
51
  }
52
53
  /**
54
   * Check that our cron is currently activated
55
   * @param name string Cronjob name
56
   * @return bool true or false
57
   **/
58
  public function isDisabled($name) {
59
    $aStatus = $this->getStatus($name . '_disabled');
60
    return $aStatus['value'];
61
  }
62
63
  /**
64
   * Get the timestamp that last time a cronjob started
65
   * @param name string Cronjob name
66
   * @return int unix timestamp of last time the cronjob started
67
   **/
68
  public function getLastCronStarted($name) {
69
    $aStatus = $this->getStatus($name . '_starttime');
70
    return $aStatus['value'];
71
  }
72
73
  /**
74
   * Fetch a value from our table
75
   * @param name string Setting name
76
   * @return value string Value
77
   **/
78
  public function getStatus($name) {
79
    $query = $this->mysqli->prepare("SELECT * FROM $this->table WHERE name = ? LIMIT 1");
80
    if ($query && $query->bind_param('s', $name) && $query->execute() && $result = $query->get_result()) {
81
      return $result->fetch_assoc();
82
    } else {
83
      return $this->sqlError();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->sqlError(); (boolean) is incompatible with the return type documented by Monitoring::getStatus of type value.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
84
    }
85
  }
86
87
  /**
88
   * Insert or update a setting
89
   * @param name string Name of the variable
90
   * @param value string Variable value
91
   * @return bool
92
   **/
93 View Code Duplication
  public function setStatus($name, $type, $value) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94
    $stmt = $this->mysqli->prepare("
95
      INSERT INTO $this->table (name, type, value)
96
      VALUES (?, ?, ?)
97
      ON DUPLICATE KEY UPDATE value = ?
98
      ");
99
    if ($stmt && $stmt->bind_param('ssss', $name, $type, $value, $value) && $stmt->execute())
100
      return true;
101
    $this->debug->append("Failed to set $name to $value");
102
    return false;
103
  }
104
105
  /**
106
   * Start a cronjob, mark various fields properly
107
   * @param cron_name string Cronjob name
108
   **/
109
  public function startCronjob($cron_name) {
110
    $aStatus = $this->getStatus($cron_name . '_active');
111
    if ($aStatus['value'] == 1) {
112
      $this->setErrorMessage('Cron is already active in database: ' . $cron_name . '_active is 1, please force run with -f once ensured it\' not running');
113
      return false;
114
    }
115
    $this->setStatus($cron_name . "_active", "yesno", 1);
116
    $this->setStatus($cron_name . '_starttime', 'date', time());
117
    return true;
118
  }
119
120
  /**
121
   * End cronjob with an error message
122
   * @param cron_name string Cronjob Name
123
   * @param msgCode string Message code as stored in error_codes array
124
   * @param exitCode int Exit code to pass on to exit function and monitor report
125
   * @param fatal boolean Should we exit out entirely
126
   * @return none
127
   **/
128
  public function endCronjob($cron_name, $msgCode, $exitCode=0, $fatal=false, $mail=true) {
129
    $this->setStatus($cron_name . "_active", "yesno", 0);
130
    $this->setStatus($cron_name . "_message", "message", $this->getErrorMsg($msgCode));
131
    $this->setStatus($cron_name . "_status", "okerror", $exitCode);
132
    $this->setStatus($cron_name . "_endtime", "date", time());
133
    if ($mail) {
134
      $aMailData = array(
135
        'email' => $this->setting->getValue('system_error_email'),
136
        'subject' => 'Cronjob Failure',
137
        'Error Code' => $msgCode,
138
        'Error Message' => $this->getErrorMsg($msgCode)
139
      );
140
      if (!$this->mail->sendMail('notifications/error', $aMailData))
0 ignored issues
show
Bug introduced by
The property mail does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
141
        $this->setErrorMessage('Failed to send mail notification');
142
    }
143
    if ($fatal) {
144
      if ($exitCode == 1) $this->setStatus($cron_name . "_disabled", "yesno", 1);
145
      exit($exitCode);
0 ignored issues
show
Coding Style Compatibility introduced by
The method endCronjob() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
146
    }
147
  }
148
}
149
150
$monitoring = new Monitoring();
151
$monitoring->setErrorCodes($aErrorCodes);
152
$monitoring->setConfig($config);
153
$monitoring->setDebug($debug);
154
$monitoring->setMail($mail);
155
$monitoring->setMysql($mysqli);
156
$monitoring->setSetting($setting);
157