Completed
Pull Request — master (#182)
by
unknown
03:01
created

IncidentsTable::_getServer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
/* vim: set expandtab sw=4 ts=4 sts=4: */
3
4
/**
5
 * An incident a representing a single incident of a submited bug.
6
 *
7
 * phpMyAdmin Error reporting server
8
 * Copyright (c) phpMyAdmin project (https://www.phpmyadmin.net/)
9
 *
10
 * Licensed under The MIT License
11
 * For full copyright and license information, please see the LICENSE.txt
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @copyright Copyright (c) phpMyAdmin project (https://www.phpmyadmin.net/)
15
 * @license   https://opensource.org/licenses/mit-license.php MIT License
16
 *
17
 * @see      https://www.phpmyadmin.net/
18
 */
19
20
namespace App\Model\Table;
21
22
use Cake\Log\Log;
23
use Cake\Model\Model;
24
use Cake\ORM\Table;
25
use Cake\ORM\TableRegistry;
26
27
/**
28
 * An incident a representing a single incident of a submited bug.
29
 */
30
class IncidentsTable extends Table
31
{
32
    /**
33
     * @var array
34
     *
35
     * @see http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors
36
     * @see Model::$actsAs
37
     */
38
    public $actsAs = array('Summarizable');
39
40
    /**
41
     * @var array
42
     *
43
     * @see http://book.cakephp.org/2.0/en/models/model-attributes.html#validate
44
     * @see http://book.cakephp.org/2.0/en/models/data-validation.html
45
     * @see Model::$validate
46
     */
47
    public $validate = array(
48
        'pma_version' => array(
49
            'rule' => 'notEmpty',
50
            'required' => true,
51
        ),
52
        'php_version' => array(
53
            'rule' => 'notEmpty',
54
            'required' => true,
55
        ),
56
        'full_report' => array(
57
            'rule' => 'notEmpty',
58
            'required' => true,
59
        ),
60
        'stacktrace' => array(
61
            'rule' => 'notEmpty',
62
            'required' => true,
63
        ),
64
        'browser' => array(
65
            'rule' => 'notEmpty',
66
            'required' => true,
67
        ),
68
        'stackhash' => array(
69
            'rule' => 'notEmpty',
70
            'required' => true,
71
        ),
72
        'user_os' => array(
73
            'rule' => 'notEmpty',
74
            'required' => true,
75
        ),
76
        'locale' => array(
77
            'rule' => 'notEmpty',
78
            'required' => true,
79
        ),
80
        'script_name' => array(
81
            'rule' => 'notEmpty',
82
            'required' => true,
83
        ),
84
        'server_software' => array(
85
            'rule' => 'notEmpty',
86
            'required' => true,
87
        ),
88
        'configuration_storage' => array(
89
            'rule' => 'notEmpty',
90
            'required' => true,
91
        ),
92
    );
93
94
    /**
95
     * @var array
96
     *
97
     * @see http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
98
     * @see Model::$belongsTo
99
     */
100
101
    /**
102
     * The fields which are summarized in the report page with charts and are also
103
     * used in the overall stats and charts for the website.
104
     *
105
     * @var array
106
     */
107
    public $summarizableFields = array(
108
        'browser', 'pma_version', 'php_version',
109
        'locale', 'server_software', 'user_os', 'script_name',
110
        'configuration_storage',
111
    );
112
113 28
    public function __construct($id = false, $table = null, $ds = null)
114
    {
115 28
        parent::__construct($id, $table, $ds);
0 ignored issues
show
Unused Code introduced by
The call to Table::__construct() has too many arguments starting with $table.

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...
116
117 28
        $this->filterTimes = array(
0 ignored issues
show
Bug introduced by
The property filterTimes 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...
118 28
            'all_time' => array(
119
                'label' => 'All Time',
120
                'limit' => null,
121
                'group' => "DATE_FORMAT(Incidents.created, '%m %Y')",
122
            ),
123
            'day' => array(
124 28
                'label' => 'Last Day',
125 28
                'limit' => date('Y-m-d', strtotime('-1 day')),
126 28
                'group' => "DATE_FORMAT(Incidents.created, '%a %b %d %Y %H')",
127
            ),
128
            'week' => array(
129 28
                'label' => 'Last Week',
130 28
                'limit' => date('Y-m-d', strtotime('-1 week')),
131 28
                'group' => "DATE_FORMAT(Incidents.created, '%a %b %d %Y')",
132
            ),
133
            'month' => array(
134 28
                'label' => 'Last Month',
135 28
                'limit' => date('Y-m-d', strtotime('-1 month')),
136 28
                'group' => "DATE_FORMAT(Incidents.created, '%a %b %d %Y')",
137
            ),
138
            'year' => array(
139 28
                'label' => 'Last Year',
140 28
                'limit' => date('Y-m-d', strtotime('-1 year')),
141 28
                'group' => "DATE_FORMAT(Incidents.created, '%b %u %Y')",
142
            ),
143
        );
144 28
    }
145
146
    /**
147
     * creates an incident/report record given a raw bug report object.
148
     *
149
     * This gets a decoded bug report from the submitted json body. This has not
150
     * yet been santized. It either adds it as an incident to another report or
151
     * creates a new report if nothing matches.
152
     *
153
     * @param array $bugReport the bug report being submitted
154
     *
155
     * @return array of:
156
     *          1. array of inserted incident ids. If the report/incident was not
157
     *               correctly saved, false is put in it place.
158
     *          2. array of newly created report ids. If no new report was created,
159
     *               an empty array is returned
160
     */
161 2
    public function createIncidentFromBugReport($bugReport)
162
    {
163 2
        if ($bugReport == null) {
164 1
            return array('incidents' => array(false), 'reports' => array());
165
        }
166 2
        $incident_ids = array();    // array to hold ids of all the inserted incidents
167 2
        $new_report_ids = array(); // array to hold ids of all newly created reports
168
169
        // Avoid storing too many errors from single report
170 2
        if (isset($bugReport['errors']) && count($bugReport['errors']) > 40) {
171 1
            $bugReport['errors'] = array_slice($bugReport['errors'], 0, 40);
172
        }
173 2
        if (isset($bugReport['exception']['stack']) && count($bugReport['exception']['stack']) > 40) {
174 1
            $bugReport['exception']['stack'] = array_slice($bugReport['exception']['stack'], 0, 40);
175
        }
176
177
        // Also sanitizes the bug report
178 2
        $schematizedIncidents = $this->_getSchematizedIncidents($bugReport);
179 2
        $incidentsTable = TableRegistry::get('Incidents');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
180 2
        $reportsTable = TableRegistry::get('Reports');
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
181 2
        foreach ($schematizedIncidents as $index => $si) {
182
183
            // find closest report. If not found, create a new report.
184 2
            $closestReport = $this->_getClosestReport($bugReport, $index);
185 2
            if ($closestReport) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $closestReport of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
186 2
                $si['report_id'] = $closestReport['id'];
187 2
                $si = $incidentsTable->newEntity($si);
188 2
                $si->created = date('Y-m-d H:i:s', time());
0 ignored issues
show
Bug introduced by
Accessing created on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
189 2
                $si->modified = date('Y-m-d H:i:s', time());
0 ignored issues
show
Bug introduced by
Accessing modified on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
190
191 2
                $this->_logLongIncidentSubmissions($si, $incident_ids);
192 2
                if (in_array(false, $incident_ids)) {
193 2
                    break;
194
                }
195
            } else {
196
                // no close report. Create a new report.
197 2
                $report = $this->_getReportDetails($bugReport, $index);
198
199 2
                $this->_logLongIncidentSubmissions($si, $incident_ids);
200 2
                if (in_array(false, $incident_ids)) {
201
                    break;
202
                }
203
204 2
                $report = $reportsTable->newEntity($report);
205 2
                $report->created = date('Y-m-d H:i:s', time());
0 ignored issues
show
Bug introduced by
Accessing created on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
206 2
                $report->modified = date('Y-m-d H:i:s', time());
0 ignored issues
show
Bug introduced by
Accessing modified on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
207 2
                $reportsTable->save($report);
208
209 2
                $si['report_id'] = $report->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
210 2
                $new_report_ids[] = $report->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
211 2
                $si = $incidentsTable->newEntity($si);
212 2
                $si->created = date('Y-m-d H:i:s', time());
0 ignored issues
show
Bug introduced by
Accessing created on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
213 2
                $si->modified = date('Y-m-d H:i:s', time());
0 ignored issues
show
Bug introduced by
Accessing modified on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
214
            }
215
216 2
            $isSaved = $incidentsTable->save($si);
217 2
            if ($isSaved) {
218 2
                array_push($incident_ids, $si->id);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
219 2
                if (!$closestReport) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $closestReport of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
220
                    // add notifications entry
221 2
                    $tmpIncident = $incidentsTable->findById($si->id)->all()->first();
0 ignored issues
show
Bug introduced by
Accessing id on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
222 2
                    if (!TableRegistry::get('Notifications')->addNotifications(intval($tmpIncident['report_id']))) {
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
223
                        Log::write(
224
                            'error',
225
                            'ERRORED: Notification::addNotifications() failed on Report#'
226
                                . $tmpIncident['report_id'],
227 2
                            'alert'
228
                        );
229
                    }
230
                }
231
            } else {
232
                array_push($incident_ids, false);
233
            }
234
        }
235
236
        return array(
237 2
            'incidents' => $incident_ids,
238 2
            'reports' => $new_report_ids
239
        );
240
    }
241
242
    /**
243
     * retrieves the closest report to a given bug report.
244
     *
245
     * it checks for another report with the same line number, filename and
246
     * pma_version
247
     *
248
     * @param array $bugReport the bug report being checked
249
     *                         Integer $index: for php exception type
250
     * @param mixed $index
251
     *
252
     * @return array the first similar report or null
253
     */
254 3
    protected function _getClosestReport($bugReport, $index = 0)
255
    {
256 3
        if (isset($bugReport['exception_type'])
257 3
            && $bugReport['exception_type'] == 'php'
258
        ) {
259 2
            $location = $bugReport['errors'][$index]['file'];
260 2
            $linenumber = $bugReport['errors'][$index]['lineNum'];
261
        } else {
262
            list($location, $linenumber) =
263 3
                    $this->_getIdentifyingLocation($bugReport['exception']['stack']);
264
        }
265 3
        $report = TableRegistry::get('Reports')->findByLocationAndLinenumberAndPmaVersion(
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\TableRegistry::get() has been deprecated with message: 3.6.0 Use \Cake\ORM\Locator\TableLocator::get() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
266 3
                    $location, $linenumber,
267 3
                    $this->getStrippedPmaVersion($bugReport['pma_version'])
268 3
                )->all()->first();
269
270 3
        return $report;
271
    }
272
273
    /**
274
     * creates the report data from an incident that has no related report.
275
     *
276
     * @param array $bugReport the bug report the report record is being created for
277
     *                         Integer $index: for php exception type
278
     * @param mixed $index
279
     *
280
     * @return array an array with the report fields can be used with Report->save
281
     */
282 3
    protected function _getReportDetails($bugReport, $index = 0)
283
    {
284 3
        if (isset($bugReport['exception_type'])
285 3
            && $bugReport['exception_type'] == 'php'
286
        ) {
287 3
            $location = $bugReport['errors'][$index]['file'];
288 3
            $linenumber = $bugReport['errors'][$index]['lineNum'];
289
            $reportDetails = array(
290 3
                    'error_message' => $bugReport['errors'][$index]['msg'],
291 3
                    'error_name' => $bugReport['errors'][$index]['type'],
292
                    );
293 3
            $exception_type = 1;
294
        } else {
295
            list($location, $linenumber) =
296 3
                $this->_getIdentifyingLocation($bugReport['exception']['stack']);
297
298
            $reportDetails = array(
299 3
                    'error_message' => $bugReport['exception']['message'],
300 3
                    'error_name' => $bugReport['exception']['name'],
301
                    );
302 3
            $exception_type = 0;
303
        }
304
305 3
        $reportDetails = array_merge(
306 3
            $reportDetails,
307
            array(
308 3
                'status' => 'new',
309 3
                'location' => $location,
310 3
                'linenumber' => is_null($linenumber) ? 0 : $linenumber,
311 3
                'pma_version' => $this->getStrippedPmaVersion($bugReport['pma_version']),
312 3
                'exception_type' => $exception_type,
313
            )
314
        );
315
316 3
        return $reportDetails;
317
    }
318
319
    /**
320
     * creates the incident data from the submitted bug report.
321
     *
322
     * @param array $bugReport the bug report the report record is being created for
323
     *
324
     * @return array an array of schematized incident.
325
     *               Can be used with Incident->save
326
     */
327 3
    protected function _getSchematizedIncidents($bugReport)
328
    {
329
        //$bugReport = Sanitize::clean($bugReport, array('escape' => false));
330 3
        $schematizedReports = array();
331
        $schematizedCommonReport = array(
332 3
            'pma_version' => $this->getStrippedPmaVersion($bugReport['pma_version']),
333 3
            'php_version' => $this->_getSimpleVersion($bugReport['php_version'], 2),
334 3
            'browser' => $bugReport['browser_name'] . ' '
335 3
                    . $this->_getSimpleVersion($bugReport['browser_version'], 1),
336 3
            'user_os' => $bugReport['user_os'],
337 3
            'locale' => $bugReport['locale'],
338 3
            'configuration_storage' => $bugReport['configuration_storage'],
339 3
            'server_software' => $this->_getServer($bugReport['server_software']),
340 3
            'full_report' => json_encode($bugReport),
341
        );
342
343 3
        if (isset($bugReport['exception_type'])
344 3
            && $bugReport['exception_type'] == 'php'
345
        ) {
346
            // for each "errors"
347 3
            foreach ($bugReport['errors'] as $error) {
348 3
                $tmpReport = array_merge(
349 3
                    $schematizedCommonReport,
350
                    array(
351 3
                        'error_name' => $error['type'],
352 3
                        'error_message' => $error['msg'],
353 3
                        'script_name' => $error['file'],
354 3
                        'stacktrace' => json_encode($error['stackTrace']),
355 3
                        'stackhash' => $error['stackhash'],
356 3
                        'exception_type' => 1,         // 'php'
357
                    )
358
                );
359 3
                array_push($schematizedReports, $tmpReport);
360
            }
361
        } else {
362 3
            $tmpReport = array_merge(
363 3
                $schematizedCommonReport,
364
                array(
365 3
                    'error_name' => $bugReport['exception']['name'],
366 3
                    'error_message' => $bugReport['exception']['message'],
367 3
                    'script_name' => $bugReport['script_name'],
368 3
                    'stacktrace' => json_encode($bugReport['exception']['stack']),
369 3
                    'stackhash' => $this->getStackHash($bugReport['exception']['stack']),
370 3
                    'exception_type' => 0,     //'js'
371
                )
372
            );
373
374 3
            if (isset($bugReport['steps'])) {
375 3
                $tmpReport['steps'] = $bugReport['steps'];
376
            }
377 3
            array_push($schematizedReports, $tmpReport);
378
        }
379
380 3
        return $schematizedReports;
381
    }
382
383
    /**
384
     * Gets the identifiying location info from a stacktrace.
385
     *
386
     * This is used to skip stacktrace levels that are within the error reporting js
387
     * files that sometimes appear in the stacktrace but are not related to the bug
388
     * report
389
     *
390
     * returns two things in an array:
391
     * - the first element is the filename/scriptname of the error
392
     * - the second element is the linenumber of the error
393
     *
394
     * @param array $stacktrace the stacktrace being examined
395
     *
396
     * @return array an array with the filename/scriptname and linenumber of the
397
     *               error
398
     */
399 5
    protected function _getIdentifyingLocation($stacktrace)
400
    {
401 5
        $fallback = array('UNKNOWN', 0);
402 5
        foreach ($stacktrace as $level) {
403 5
            if (isset($level['filename'])) {
404
                // ignore unrelated files that sometimes appear in the error report
405 5
                if ($level['filename'] === 'tracekit/tracekit.js') {
406 1
                    continue;
407 5
                } elseif ($level['filename'] === 'error_report.js') {
408
                    // in case the error really is in the error_report.js file save it for
409
                    // later
410 1
                    if ($fallback[0] == 'UNKNOWN') {
411 1
                        $fallback = array($level['filename'], $level['line']);
412
                    }
413 1
                    continue;
414
                }
415
416 5
                return array($level['filename'], $level['line']);
417 1
            } elseif (isset($level['scriptname'])) {
418 1
                return array($level['scriptname'], $level['line']);
419
            }
420 1
            continue;
421
        }
422
423 1
        return $fallback;
424
    }
425
426
    /**
427
     * Gets a part of a version string according to the specified version Length.
428
     *
429
     * @param string $versionString the version string
430
     * @param string $versionLength the number of version components to return. eg
431
     *                              1 for major version only and 2 for major and
432
     *                              minor version
433
     *
434
     * @return string the major and minor version part
435
     */
436 4
    protected function _getSimpleVersion($versionString, $versionLength)
437
    {
438 4
        $versionLength = (int) $versionLength;
439 4
        if ($versionLength < 1) {
440 1
            $versionLength = 1;
441
        }
442
        /* modify the re to accept a variable number of version components. I
443
         * atleast take one component and optionally get more components if need be.
444
         * previous code makes sure that the $versionLength variable is a positive
445
         * int
446
         */
447 4
        $result = preg_match(
448 4
            "/^(\d+\.){" . ($versionLength - 1) . "}\d+/",
449 4
            $versionString,
450 4
            $matches
451
        );
452 4
        if ($result) {
453 4
            $simpleVersion = $matches[0];
454
455 4
            return $simpleVersion;
456
        }
457
458
        return $versionString;
459
    }
460
461
    /**
462
     * Returns the version string stripped of
463
     * 'deb', 'ubuntu' and other suffixes
464
     *
465
     * @param string $versionString phpMyAdmin version
466
     *
467
     * @return string stripped phpMyAdmin version
468
     */
469 12
    public function getStrippedPmaVersion($versionString)
470
    {
471 12
        $allowedRegexp = '/^(\d+)(\.\d+){0,3}(\-.*)?/';
472 12
        $matches = array();
473
474
        // Check if $versionString matches the regexp
475
        // and store the matched strings
476 12
        if (preg_match($allowedRegexp, $versionString, $matches)) {
477 12
            return $matches[0];
478
        }
479
480
        // If $versionString does not match the regexp at all,
481
        // leave it as it is
482
        return $versionString;
483
    }
484
485
    /**
486
     * Gets the server name and version from the server signature.
487
     *
488
     * @param string $signature the server signature
489
     *
490
     * @return string the server name and version or UNKNOWN
491
     */
492 4
    protected function _getServer($signature)
493
    {
494 4
        if (preg_match("/(apache\/\d+\.\d+)|(nginx\/\d+\.\d+)|(iis\/\d+\.\d+)"
495 4
                . "|(lighttpd\/\d+\.\d+)/i",
496 4
                $signature, $matches)) {
497 4
            return $matches[0];
498
        }
499
500 1
        return 'UNKNOWN';
501
    }
502
503
    /**
504
     * returns the hash pertaining to a stacktrace.
505
     *
506
     * @param array $stacktrace the stacktrace in question
507
     *
508
     * @return string the hash string of the stacktrace
509
     */
510 4
    public function getStackHash($stacktrace)
511
    {
512 4
        $handle = hash_init('md5');
513 4
        foreach ($stacktrace as $level) {
514 4
            $elements = array('filename', 'scriptname', 'line', 'func', 'column');
515 4
            foreach ($elements as $element) {
516 4
                if (!isset($level[$element])) {
517 4
                    continue;
518
                }
519 4
                hash_update($handle, $level[$element]);
520
            }
521
        }
522
523 4
        return hash_final($handle);
524
    }
525
526
    /**
527
     * Checks the length of stacktrace and full_report
528
     * and logs if it is greater than what it can hold
529
     *
530
     * @param array $si           submitted incident
531
     * @param array $incident_ids incident IDs
532
     *
533
     * @return array $incident_ids
534
     */
535 2
    private function _logLongIncidentSubmissions($si, &$incident_ids) {
536
537 2
        $stacktraceLength = mb_strlen($si['stacktrace']);
538 2
        $fullReportLength = mb_strlen($si['full_report']);
539 2
        $errorMessageLength = mb_strlen($si['error_message']);
540
541 2
        if ($stacktraceLength > 65535
542 2
            || $fullReportLength > 65535
543 2
            || $errorMessageLength > 200 // length of field in 'incidents' table
544
        ) {
545
            // If length of report is longer than
546
            // what can fit in the table field,
547
            // we log it and don't save it in the database
548 1
            Log::error(
549
                'Too long data submitted in the incident. The length of stacktrace: '
550 1
                . $stacktraceLength . ', the length of bug report: '
551 1
                . $fullReportLength . ', the length of error message: '
552 1
                . $errorMessageLength . '. The full incident reported was as follows: '
553 1
                . json_encode($si)
554
            );
555
556
            // add a 'false' to the return array
557 1
            array_push($incident_ids, false);
558
        }
559 2
    }
560
}
561