Issues (304)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

class/stats.php (46 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 29 and the first side effect is on line 22.

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
/*
3
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
/**
12
 *  userlog module
13
 *
14
 * @copyright       XOOPS Project (https://xoops.org)
15
 * @license         GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
16
 * @package         userlog class
17
 * @since           1
18
 * @author          irmtfan ([email protected])
19
 * @author          XOOPS Project <www.xoops.org> <www.xoops.ir>
20
 */
21
22
defined('XOOPS_ROOT_PATH') || exit('Restricted access.');
23
require_once __DIR__ . '/../include/common.php';
24
xoops_loadLanguage('admin', USERLOG_DIRNAME);
25
26
/**
27
 * Class UserlogStats
28
 */
29
class UserlogStats extends XoopsObject
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...
30
{
31
    /**
32
     * @var string
33
     */
34
    public $userlog = null;
35
    public $period  = ['all' => 0, 'today' => 1, 'week' => 7, 'month' => 30];
36
    public $type    = [
37
        'log'      => _AM_USERLOG_STATS_LOG,
38
        'logdel'   => _AM_USERLOG_STATS_LOGDEL,
39
        'set'      => _AM_USERLOG_STATS_SET,
40
        'file'     => _AM_USERLOG_STATS_FILE,
41
        'fileall'  => _AM_USERLOG_STATS_FILEALL,
42
        'referral' => _AM_USERLOG_STATS_REFERRAL,
43
        'browser'  => _AM_USERLOG_STATS_BROWSER,
44
        'OS'       => _AM_USERLOG_STATS_OS,
45
        'views'    => _AM_USERLOG_STATS_VIEWS
46
    ];
47
48
    /**
49
     *
50
     */
51
    public function __construct()
52
    {
53
        $this->userlog = Userlog::getInstance();
0 ignored issues
show
Documentation Bug introduced by
It seems like \Userlog::getInstance() of type object<Userlog> is incompatible with the declared type string of property $userlog.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
54
        $this->initVar('stats_id', XOBJ_DTYPE_INT, null, false);
55
        $this->initVar('stats_type', XOBJ_DTYPE_TXTBOX, null, false, 10);
56
        $this->initVar('stats_link', XOBJ_DTYPE_TXTBOX, null, false, 100);
57
        $this->initVar('stats_value', XOBJ_DTYPE_INT, null, false);
58
        $this->initVar('stats_period', XOBJ_DTYPE_INT, null, false);
59
        $this->initVar('time_update', XOBJ_DTYPE_INT, null, false);
60
    }
61
62
    /**
63
     * @param string $method
64
     * @param array  $args
65
     *
66
     * @return mixed
67
     */
68
    public function __call($method, $args)
69
    {
70
        $arg = isset($args[0]) ? $args[0] : null;
71
72
        return $this->getVar($method, $arg);
73
    }
74
75
    /**
76
     * @return UserlogStats
77
     */
78
    public static function getInstance()
79
    {
80
        static $instance;
81
        if (null === $instance) {
82
            $instance = new static();
83
        }
84
85
        return $instance;
86
    }
87
88
    /**
89
     * @return bool|string
90
     */
91
    public function time_update()
92
    {
93
        return $this->userlog->formatTime($this->getVar('time_update'));
0 ignored issues
show
The method formatTime cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
94
    }
95
    // $type = null or array() => get all types
96
97
    /**
98
     * @param array  $type
99
     * @param int    $start
100
     * @param int    $limit
101
     * @param string $sort
102
     * @param string $order
103
     * @param null   $otherCriteria
104
     *
105
     * @return mixed
106
     */
107
    public function getAll(
108
        $type = [],
109
        $start = 0,
110
        $limit = 0,
111
        $sort = 'stats_value',
112
        $order = 'DESC',
113
        $otherCriteria = null
114
    ) {
115
        $criteria = new CriteriaCompo();
116
        if (!empty($type)) {
117
            $typeArr = is_array($type) ? $type : [$type];
118
            foreach ($typeArr as $tt) {
119
                $criteria->add(new Criteria('stats_type', $tt), 'OR');
120
            }
121
        }
122
        if (!empty($otherCriteria)) {
123
            $criteria->add($otherCriteria);
124
        }
125
        $criteria->setStart($start);
126
        $criteria->setLimit($limit);
127
        $criteria->setSort($sort);
128
        $criteria->setOrder($order);
129
        $statsObj = $this->userlog->getHandler('stats')->getAll($criteria);
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
130
        if (empty($statsObj)) {
131
            return false;
132
        } // if no result nothing in database
133
        foreach ($statsObj as $sObj) {
134
            $link = $sObj->stats_link();
135
            // if there is a link and only one type just index link
136
            $index1 = (!empty($link) && 1 == count($type)) ? $link : $sObj->stats_type() . $link;
137
            $index2 = $sObj->stats_period();
138
            if (!isset($ret[$index1])) {
139
                $ret[$index1] = [];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$ret was never initialized. Although not strictly required by PHP, it is generally a good practice to add $ret = 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...
140
            }
141
            if (!isset($ret[$index1][$index2])) {
142
                $ret[$index1][$index2] = [];
0 ignored issues
show
The variable $ret 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...
143
            }
144
            $ret[$index1][$index2]['value']       = $sObj->stats_value();
145
            $ret[$index1][$index2]['time_update'] = $sObj->time_update();
146
        }
147
148
        return $ret;
149
    }
150
151
    /**
152
     * @param string $type
153
     * @param int    $prob
154
     *
155
     * @return bool
156
     */
157
    public function updateAll($type = 'log', $prob = 11)
158
    {
159
        if (!$this->userlog->probCheck($prob)) {
0 ignored issues
show
The method probCheck cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
160
            return false;
161
        }
162
        switch ($type) {
163
            case 'set':
164
                // total
165
                $sets = $this->userlog->getHandler('setting')->getCount();
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
166
                $this->update('set', 0, $sets);
167
                break;
168
            case 'file':
169
                list($allFiles, $totalFiles) = $this->userlog->getAllLogFiles();
0 ignored issues
show
The method getAllLogFiles cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
170
                foreach ($allFiles as $path => $files) {
171
                    $log_file = $path . '/' . $this->userlog->getConfig('logfilename') . '.' . $this->userlog->logext;
0 ignored issues
show
The method getConfig cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
172
                    $this->update('file', 0, count($files), false, $log_file); // update working file in all paths (now 2)
173
                }
174
                // update all files in db link='all'
175
                $this->update('file', 0, $totalFiles, false, 'all');
176
                break;
177
            case 'views':
178
                break;
179
            case 'log':
180
                // if logs exceed the maxlogsperiod delete them
181
                if (0 != $this->userlog->getConfig('maxlogsperiod')) {
0 ignored issues
show
The method getConfig cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
182
                    $criteriaDel = new CriteriaCompo();
183
                    $until       = time() - $this->userlog->getSinceTime($this->userlog->getConfig('maxlogsperiod'));
0 ignored issues
show
The method getConfig cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
The method getSinceTime cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
184
                    $criteriaDel->add(new Criteria('log_time', $until, '<'), 'AND');
185
                    $numDelPeriod = $this->delete('log', 0, 0, $criteriaDel); // all time = maxlogsperiod
0 ignored issues
show
$numDelPeriod 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...
186
                }
187
                foreach ($this->period as $per) {
188
                    $criteria = new CriteriaCompo();
189 View Code Duplication
                    if (!empty($per)) {
0 ignored issues
show
This code seems to be duplicated across 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...
190
                        // today, week, month
191
                        $since = $this->userlog->getSinceTime($per);
0 ignored issues
show
The method getSinceTime cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
192
                        $criteria->add(new Criteria('log_time', time() - $since, '>'), 'AND');
193
                    }
194
                    $logs   = $this->userlog->getHandler('log')->getLogsCount($criteria);
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
195
                    $exceed = $logs - $this->userlog->getConfig('maxlogs');
0 ignored issues
show
The method getConfig cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
196
                    // if logs exceed the maxlogs delete them
197
                    if ($exceed > 0) {
198
                        $numDel = $this->delete('log', $per, $exceed, null, true);
199
                        $logs   -= $numDel;
200
                    }
201
                    $this->update('log', $per, $logs);
202
                }
203
                break;
204
            case 'referral':
205
                $criteria = new CriteriaCompo();
206
                $criteria->add(new Criteria('referer', XOOPS_URL . '%', 'NOT LIKE'));
207
                $criteria->setGroupBy('referer');
208
                $outsideReferers = $this->userlog->getHandler('log')->getCounts($criteria);
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
209
                $referrals       = [];
210
                foreach ($outsideReferers as $ref => $views) {
211
                    if (empty($ref)) {
212
                        continue;
213
                    }
214
                    $outRef = parse_url($ref, PHP_URL_HOST);
215
                    if (!isset($referrals[$outRef])) {
216
                        $referrals[$outRef] = 0;
217
                    }
218
                    $referrals[$outRef] += $views;
219
                }
220
                foreach ($referrals as $ref => $views) {
221
                    $this->update('referral', 0, $views, false, $ref);
222
                }
223
                $this->deleteExpiredStats('referral');
224
                break;
225
            case 'browser':
226
            case 'OS':
227
                $criteria = new CriteriaCompo();
228
                $criteria->setGroupBy('user_agent');
229
                $agents   = $this->userlog->getHandler('log')->getCounts($criteria);
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
230
                $browsers = [];
231
                $OSes     = [];
232
                foreach ($agents as $agent => $views) {
233
                    if (empty($agent)) {
234
                        continue;
235
                    }
236
                    $browserArr    = $this->userlog->getBrowsCap()->getBrowser($agent, true);
0 ignored issues
show
The method getBrowsCap cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
237
                    $browserParent = !empty($browserArr['Parent']) ? (!empty($browserArr['Crawler']) ? 'crawler: ' : '') . $browserArr['Parent'] : 'unknown';
238
                    if (!isset($browsers[$browserParent])) {
239
                        $browsers[$browserParent] = 0;
240
                    }
241
                    $browsers[$browserParent] += $views;
242
                    if (!isset($OSes[$browserArr['Platform']])) {
243
                        $OSes[$browserArr['Platform']] = 0;
244
                    }
245
                    $OSes[$browserArr['Platform']] += $views;
246
                }
247
                foreach ($browsers as $browser => $views) {
248
                    $this->update('browser', 0, $views, false, $browser);
249
                }
250
                foreach ($OSes as $OS => $views) {
251
                    $this->update('OS', 0, $views, false, $OS);
252
                }
253
                $this->deleteExpiredStats(['browser', 'OS']);
254
                break;
255
        }
256
257
        return true;
258
    }
259
260
    /**
261
     * @param string $type
262
     * @param int    $period
263
     * @param int    $limitDel
264
     * @param null   $criteria
265
     * @param bool   $asObject
266
     *
267
     * @return int
268
     */
269
    public function delete($type = 'log', $period = 0, $limitDel = 0, $criteria = null, $asObject = false)
270
    {
271
        switch ($type) {
272
            case 'log':
273
                if ($asObject) {
274
                    $logsObj = $this->userlog->getHandler('log')->getLogs($limitDel, 0, $criteria, 'log_id', 'ASC');
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
275
                    $numDel  = 0;
276
                    foreach (array_keys($logsObj) as $key) {
277
                        $numDel += $this->userlog->getHandler('log')->delete($logsObj[$key], true) ? 1 : 0;
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
278
                    }
279
                    if ($numDel > 0) {
280
                        $this->update('logdel', $period, $numDel, true); // increment
281
                    }
282
                    unset($logsObj);
283
284
                    return $numDel;
285
                }
286
                $numDel = $this->userlog->getHandler('log')->deleteAll($criteria, true, $asObject);
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
287
                if ($numDel > 0) {
288
                    $this->update('logdel', $period, $numDel, true); // increment
289
                }
290
291
                return $numDel;
292
                break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
293
        }
294
    }
295
296
    /**
297
     * @param string $type
298
     * @param int    $period
299
     * @param null   $value
300
     * @param bool   $increment
301
     * @param string $link
302
     *
303
     * @return mixed
304
     */
305
    public function update($type = 'log', $period = 0, $value = null, $increment = false, $link = '')
306
    {
307
        // check if version is 115 => unique index is added
308
        if ($this->userlog->getModule()->getVar('version') < 115) {
0 ignored issues
show
The method getModule cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
309
            return false;
310
        }
311
        // if there is nothing to add to db
312
        if (empty($value) && !empty($increment)) {
313
            return false;
314
        }
315
        // for file,referral,browser,OS we should have a link
316
        if (in_array($type, ['file', 'referral', 'browser', 'OS']) && empty($link)) {
317
            return false;
318
        }
319
        $statsObj = $this->userlog->getHandler('stats')->create();
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
320
321
        $statsObj->setVar('stats_type', $type);
322
        $statsObj->setVar('stats_period', $period);
323
        $statsObj->setVar('stats_link', $link);
324
        $statsObj->setVar('stats_value', $value);
325
        $statsObj->setVar('time_update', time());
326
        // increment value if increment is true
327
        $ret = $this->userlog->getHandler('stats')->insertUpdate($statsObj, [
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
328
            'stats_value' => empty($increment) ? $value : "stats_value + {$value}",
329
            'time_update' => time()
330
        ]);
331
        $this->unsetNew();
332
333
        return $ret;
334
    }
335
336
    /**
337
     * Delete expired statistics for types when time_update < expire time
338
     *
339
     * @access public
340
     *
341
     * @param array $types  - types ($this->type)
342
     * @param int   $expire - delete all records exist in the table before expire time - positive for days and negatice for hours - 0 = never expired
343
     *
344
     * @return int count of deleted rows
345
     */
346
    public function deleteExpiredStats($types = ['browser'], $expire = 1)
347
    {
348
        if (empty($expire)) {
349
            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 UserlogStats::deleteExpiredStats of type integer.

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...
350
        } // if $expire = 0 dont delete
351
        $criteriaDel = new CriteriaCompo();
352
        $until       = time() - $this->userlog->getSinceTime($expire);
0 ignored issues
show
The method getSinceTime cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
353
        if (!empty($types)) {
354
            $criteriaTypes = new CriteriaCompo();
355
            $types         = is_array($types) ? $types : [$types];
356
            foreach ($types as $type) {
357
                $criteriaTypes->add(new Criteria('stats_type', $type, '='), 'OR');
358
            }
359
            $criteriaDel->add($criteriaTypes, 'AND');
360
        }
361
        $criteriaTime = new CriteriaCompo();
362
        $criteriaTime->add(new Criteria('time_update', $until, '<'), 'AND');
363
        $criteriaDel->add($criteriaTime, 'AND');
364
365
        return $this->userlog->getHandler('stats')->deleteAll($criteriaDel); // function deleteAll($criteria = null, $force = true, $asObject = false)
0 ignored issues
show
The method getHandler cannot be called on $this->userlog (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Unused Code Comprehensibility introduced by
44% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
366
    }
367
}
368
369
/**
370
 * Class UserlogStatsHandler
371
 */
372
class UserlogStatsHandler extends XoopsPersistableObjectHandler
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
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...
373
{
374
    public $userlog = null;
375
376
    /**
377
     * @param null|XoopsDatabase $db
378
     */
379
    public function __construct(XoopsDatabase $db)
380
    {
381
        $this->userlog = Userlog::getInstance();
382
        parent::__construct($db, USERLOG_DIRNAME . '_stats', 'UserlogStats', 'stats_id', 'stats_type');
383
    }
384
385
    /**
386
     * @param       $object
387
     * @param array $duplicate
388
     * @param bool  $force
389
     *
390
     * @return bool
391
     */
392
    public function insertUpdate($object, $duplicate = [], $force = true)
393
    {
394
        $handler = $this->loadHandler('write');
395
396 View Code Duplication
        if (!$object->isDirty()) {
0 ignored issues
show
This code seems to be duplicated across 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...
397
            trigger_error("Data entry is not inserted - the object '" . get_class($object) . "' is not dirty," . "' with errors: " . implode(', ', $object->getErrors()), E_USER_NOTICE);
398
399
            return $object->getVar($this->keyName);
400
        }
401 View Code Duplication
        if (!$handler->cleanVars($object)) {
0 ignored issues
show
This code seems to be duplicated across 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...
402
            trigger_error("Insert failed in method 'cleanVars' of object '" . get_class($object) . "' with errors: " . implode(', ', $object->getErrors()), E_USER_WARNING);
403
404
            return $object->getVar($this->keyName);
405
        }
406
        $queryFunc = empty($force) ? 'query' : 'queryF';
407
408
        if ($object->isNew()) {
409
            $sql = "INSERT INTO {$this->table}";
410
            if (!empty($object->cleanVars)) {
411
                $keys = array_keys($object->cleanVars);
412
                $vals = array_values($object->cleanVars);
413
                $sql  .= ' (' . implode(', ', $keys) . ') VALUES (' . implode(',', $vals) . ')';
414 View Code Duplication
            } else {
0 ignored issues
show
This code seems to be duplicated across 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...
415
                trigger_error("Data entry is not inserted - no variable is changed in object of '" . get_class($object) . "' with errors: " . implode(', ', $object->getErrors()), E_USER_NOTICE);
416
417
                return $object->getVar($this->keyName);
418
            }
419
            // START ON DUPLICATE KEY UPDATE
420
            if (!empty($duplicate)) {
421
                $sql  .= ' ON DUPLICATE KEY UPDATE';
422
                $keys = [];
423
                foreach ($duplicate as $keyD => $valD) {
424
                    $keys[] = " {$keyD} = {$valD} ";
425
                }
426
                $sql .= implode(', ', $keys);
427
            }
428
            // END ON DUPLICATE KEY UPDATE
429
            if (!$result = $this->db->{$queryFunc}($sql)) {
430
                return false;
431
            }
432
            if (!$object->getVar($this->keyName) && $object_id = $this->db->getInsertId()) {
433
                $object->assignVar($this->keyName, $object_id);
434
            }
435
        } elseif (!empty($object->cleanVars)) {
436
            $keys = [];
437
            foreach ($object->cleanVars as $k => $v) {
438
                $keys[] = " `{$k}` = {$v}";
439
            }
440
            $sql = 'UPDATE `' . $this->table . '` SET ' . implode(',', $keys) . ' WHERE `' . $this->keyName . '` = ' . $this->db->quote($object->getVar($this->keyName));
441
            if (!$result = $this->db->{$queryFunc}($sql)) {
442
                return false;
443
            }
444
        }
445
446
        return $object->getVar($this->keyName);
447
    }
448
449
    /**
450
     * Show index in a table
451
     *
452
     * @access   public
453
     *
454
     * @param string $index - name of the index (will be used in KEY_NAME)
0 ignored issues
show
Should the type for parameter $index not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
455
     *
456
     * @internal param array $ret = Table    Non_unique    Key_name    Seq_in_index    Column_name        Collation    Cardinality        Sub_part    Packed    Null    Index_type    Comment    Index_comment
457
     *
458
     * @return array|bool
459
     */
460 View Code Duplication
    public function showIndex($index = null)
0 ignored issues
show
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...
461
    {
462
        $sql = "SHOW INDEX FROM {$this->table}";
463
        if (isset($index)) {
464
            $sql .= " WHERE KEY_NAME = '{$index}'";
465
        }
466
        if (!$result = $this->db->queryF($sql)) {
467
            xoops_error($this->db->error() . '<br>' . $sql);
468
469
            return false;
470
        }
471
        $ret = [];
472
        while (false !== ($myrow = $this->db->fetchArray($result))) {
473
            $ret[] = $myrow;
474
        }
475
476
        return $ret;
477
    }
478
479
    /**
480
     * Add Index to a table
481
     *
482
     * @access public
483
     *
484
     * @param string $index      - name of the index
0 ignored issues
show
Should the type for parameter $index not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
485
     * @param array  $fields     - array of table fields should be in the index
486
     * @param string $index_type - type of the index array("INDEX", "UNIQUE", "SPATIAL", "FULLTEXT")
487
     * @param        bool
488
     *
489
     * @return bool
490
     */
491 View Code Duplication
    public function addIndex($index = null, $fields = [], $index_type = 'INDEX')
0 ignored issues
show
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...
492
    {
493
        if (empty($index) || empty($fields)) {
494
            return false;
495
        }
496
        if ($this->showIndex($index)) {
497
            return false;
498
        } // index is exist
499
        $index_type = strtoupper($index_type);
500
        if (!in_array($index_type, ['INDEX', 'UNIQUE', 'SPATIAL', 'FULLTEXT'])) {
501
            return false;
502
        }
503
        $fields = is_array($fields) ? implode(',', $fields) : $fields;
504
        $sql    = "ALTER TABLE {$this->table} ADD {$index_type} {$index} ( {$fields} )";
505
        if (!$result = $this->db->queryF($sql)) {
506
            xoops_error($this->db->error() . '<br>' . $sql);
507
508
            return false;
509
        }
510
511
        return true;
512
    }
513
514
    /**
515
     * Drop index in a table
516
     *
517
     * @access public
518
     *
519
     * @param string $index - name of the index
0 ignored issues
show
Should the type for parameter $index not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
520
     * @param        bool
521
     *
522
     * @return bool
523
     */
524 View Code Duplication
    public function dropIndex($index = null)
0 ignored issues
show
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...
525
    {
526
        if (empty($index)) {
527
            return false;
528
        }
529
        if (!$this->showIndex($index)) {
530
            return false;
531
        } // index is not exist
532
        $sql = "ALTER TABLE {$this->table} DROP INDEX {$index}";
533
        if (!$result = $this->db->queryF($sql)) {
534
            xoops_error($this->db->error() . '<br>' . $sql);
535
536
            return false;
537
        }
538
539
        return true;
540
    }
541
542
    /**
543
     * Change Index = Drop index + Add Index
544
     *
545
     * @access public
546
     *
547
     * @param string $index      - name of the index
0 ignored issues
show
Should the type for parameter $index not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
548
     * @param array  $fields     - array of table fields should be in the index
549
     * @param string $index_type - type of the index array("INDEX", "UNIQUE", "SPATIAL", "FULLTEXT")
550
     * @param        bool
551
     *
552
     * @return bool
553
     */
554 View Code Duplication
    public function changeIndex($index = null, $fields = [], $index_type = 'INDEX')
0 ignored issues
show
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...
555
    {
556
        if ($this->showIndex($index) && !$this->dropIndex($index)) {
557
            return false;
558
        } // if index is exist but cannot drop it
559
560
        return $this->addIndex($index, $fields, $index_type);
561
    }
562
}
563