GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 2f9dc2...c88488 )
by Nicolas
06:16
created

Log::setFilter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @package core
5
 */
6
/**
7
 * The Log class acts a simple wrapper to write errors to a file so that it can
8
 * be read at a later date. There is one Log file in Symphony, stored in the main
9
 * `LOGS` directory.
10
 */
11
12
class Log
13
{
14
    /**
15
     * A constant for if this message should add to an existing log file
16
     * @var integer
17
     */
18
    const APPEND = 10;
19
20
    /**
21
     * A constant for if this message should overwrite the existing log
22
     * @var integer
23
     */
24
    const OVERWRITE = 11;
25
26
    /**
27
     * The path to this log file
28
     * @var string
29
     */
30
    private $_log_path = null;
31
32
    /**
33
     * An array of log messages to write to the log.
34
     * @var array
35
     */
36
    private $_log = array();
37
38
    /**
39
     * The maximise size of the log can reach before it is rotated and a new
40
     * Log file written started. The units are bytes. Default is -1, which
41
     * means that the log will never be rotated.
42
     * @var integer
43
     */
44
    private $_max_size = -1;
45
46
    /**
47
     * Whether to archive olds logs or not, by default they will not be archived.
48
     * @var boolean
49
     */
50
    private $_archive = false;
51
52
    /**
53
     * The filter applied to logs before they are written.
54
     * @since Symphony 2.7.1
55
     * @var integer
56
     */
57
    private $_filter = -1;
58
59
    /**
60
     * The date format that this Log entries will be written as. Defaults to
61
     * Y/m/d H:i:s.
62
     * @var string
63
     */
64
    private $_datetime_format = 'Y/m/d H:i:s';
65
66
    /**
67
     * The log constructor takes a path to the folder where the Log should be
68
     * written to.
69
     *
70
     * @param string $path
71
     *  The path to the folder where the Log files should be written
72
     */
73
    public function __construct($path)
74
    {
75
        $this->setLogPath($path);
76
    }
77
78
    /**
79
     * Setter for the `$_log_path`.
80
     *
81
     * @param string $path
82
     *  The path to the folder where the Log files should be written
83
     */
84
    public function setLogPath($path)
85
    {
86
        $this->_log_path = $path;
87
    }
88
89
    /**
90
     * Accessor for the `$_log_path`.
91
     *
92
     * @return string
93
     */
94
    public function getLogPath()
95
    {
96
        return $this->_log_path;
97
    }
98
99
    /**
100
     * Accessor for the `$_log`.
101
     *
102
     * @return array
103
     */
104
    public function getLog()
105
    {
106
        return $this->_log;
107
    }
108
109
    /**
110
     * Setter for the `$_archive`.
111
     *
112
     * @param boolean $archive
113
     *  If true, Log files will be archived using gz when they are rotated,
114
     *  otherwise they will just be overwritten when they are due for rotation
115
     */
116
    public function setArchive($archive)
117
    {
118
        $this->_archive = $archive;
119
    }
120
121
    /**
122
     * Setter for the `$_max_size`.
123
     *
124
     * @param integer $size
125
     *  The size, in bytes, that the Log can reach before it is rotated.
126
     */
127
    public function setMaxSize($size)
128
    {
129
        $this->_max_size = General::intval($size);
130
    }
131
132
    /**
133
     * Setter for the `$_filter`.
134
     *
135
     * @since Symphony 2.7.1
136
     * @param mixed $filter
137
     *  The filter used on log $type parameter.
138
     */
139
    public function setFilter($filter)
140
    {
141
        $this->_filter = General::intval($filter);
142
    }
143
144
    /**
145
     * Setter for the `$_date_format`.
146
     *
147
     * @since Symphony 2.2
148
     * @link http://au.php.net/manual/en/function.date.php
149
     * @param string $format
150
     *  Takes a valid date format using the PHP date tokens
151
     */
152
    public function setDateTimeFormat($format)
153
    {
154
        if (empty($format)) {
155
            throw new Exception('Datetime format can not be empty');
156
        }
157
        $this->_datetime_format = $format;
158
    }
159
160
    /**
161
     * Given a PHP error constant, return a human readable name. Uses the
162
     * `GenericErrorHandler::$errorTypeStrings` array to return
163
     * the name
164
     *
165
     * @see core.GenericErrorHandler::$errorTypeStrings
166
     * @param integer $type
167
     *  A PHP error constant
168
     * @return string
169
     *  A human readable name of the error constant, or if the type is not
170
     *  found, UNKNOWN.
171
     */
172
    private function __defineNameString($type)
173
    {
174
        if (isset(GenericErrorHandler::$errorTypeStrings[$type])) {
175
            return GenericErrorHandler::$errorTypeStrings[$type];
176
        }
177
178
        return 'UNKNOWN';
179
    }
180
181
    /**
182
     * Function will return the last message added to `$_log` and remove
183
     * it from the array.
184
     *
185
     * @return array|boolean
186
     *  Returns an associative array of a log message, containing the type of the log
187
     *  message, the actual message and the time at the which it was added to the log.
188
     *  If the log is empty, this function removes false.
189
     */
190
    public function popFromLog()
191
    {
192
        if (!empty($this->_log)) {
193
            return array_pop($this->_log);
194
        }
195
196
        return false;
197
    }
198
199
    /**
200
     * Given a message, this function will add it to the internal `$_log`
201
     * so that it can be written to the Log. Optional parameters all the message to
202
     * be immediately written, insert line breaks or add to the last log message
203
     *
204
     * @param string $message
205
     *  The message to add to the Log
206
     * @param integer $type
207
     *  A PHP error constant for this message, defaults to E_NOTICE.
208
     *  If null or 0, will be converted to E_ERROR.
209
     * @param boolean $writeToLog
210
     *  If set to true, this message will be immediately written to the log. By default
211
     *  this is set to false, which means that it will only be added to the array ready
212
     *  for writing
213
     * @param boolean $addbreak
214
     *  To be used in conjunction with `$writeToLog`, this will add a line break
215
     *  before writing this message in the log file. Defaults to true.
216
     * @param boolean $append
217
     *  If set to true, the given `$message` will be append to the previous log
218
     *  message found in the `$_log` array
219
     * @return boolean|null
220
     *  If `$writeToLog` is passed, this function will return boolean, otherwise
221
     *  void
222
     */
223
    public function pushToLog($message, $type = E_NOTICE, $writeToLog = false, $addbreak = true, $append = false)
224
    {
225
        if (!$type) {
226
            $type = E_ERROR;
227
        }
228
229
        if ($append) {
230
            $this->_log[count($this->_log) - 1]['message'] =  $this->_log[count($this->_log) - 1]['message'] . $message;
231
        } else {
232
            array_push($this->_log, array('type' => $type, 'time' => time(), 'message' => $message));
233
            $message = DateTimeObj::get($this->_datetime_format) . ' > ' . $this->__defineNameString($type) . ': ' . $message;
234
        }
235
236
        if ($writeToLog && ($this->_filter === -1 || ($this->_filter & $type))) {
237
            return $this->writeToLog($message, $addbreak);
238
        }
239
    }
240
241
    /**
242
     * This function will write the given message to the log file. Messages will be appended
243
     * the existing log file.
244
     *
245
     * @param string $message
246
     *  The message to add to the Log
247
     * @param boolean $addbreak
248
     *  To be used in conjunction with `$writeToLog`, this will add a line break
249
     *  before writing this message in the log file. Defaults to true.
250
     * @return boolean
251
     *  Returns true if the message was written successfully, false otherwise
252
     */
253
    public function writeToLog($message, $addbreak = true)
254
    {
255
        if (file_exists($this->_log_path) && !is_writable($this->_log_path)) {
256
            $this->pushToLog('Could not write to Log. It is not readable.');
257
            return false;
258
        }
259
260
        $permissions = class_exists('Symphony', false) ? Symphony::Configuration()->get('write_mode', 'file') : '0664';
261
262
        return General::writeFile($this->_log_path, $message . ($addbreak ? PHP_EOL : ''), $permissions, 'a+');
263
    }
264
265
    /**
266
     * Given an Throwable, this function will add it to the internal `$_log`
267
     * so that it can be written to the Log.
268
     *
269
     * @since Symphony 2.3.2
270
     *
271
     * @since Symphony 2.7.0
272
     *  This function works with both Exceptions and Throwable
273
     *  Supporting both PHP 5.6 and 7 forces use to not qualify the $e parameter
274
     *
275
     * @param Throwable $exception
276
     * @param boolean $writeToLog
277
     *  If set to true, this message will be immediately written to the log. By default
278
     *  this is set to false, which means that it will only be added to the array ready
279
     *  for writing
280
     * @param boolean $addbreak
281
     *  To be used in conjunction with `$writeToLog`, this will add a line break
282
     *  before writing this message in the log file. Defaults to true.
283
     * @param boolean $append
284
     *  If set to true, the given `$message` will be append to the previous log
285
     *  message found in the `$_log` array
286
     * @return boolean|null
287
     *  If `$writeToLog` is passed, this function will return boolean, otherwise
288
     *  void
289
     */
290
    public function pushExceptionToLog($exception, $writeToLog = false, $addbreak = true, $append = false)
291
    {
292
        $message = sprintf(
293
            '%s %s - %s on line %d of %s',
294
            get_class($exception),
295
            $exception->getCode(),
296
            $exception->getMessage(),
297
            $exception->getLine(),
298
            $exception->getFile()
299
        );
300
301
        return $this->pushToLog($message, $exception->getCode(), $writeToLog, $addbreak, $append);
302
    }
303
304
    /**
305
     * Given an method name, this function will properly format a message
306
     * and pass it down to `pushToLog()`
307
     *
308
     * @see Log::pushToLog()
309
     * @since Symphony 2.7.0
310
     * @param string $method
311
     *  The name of the deprecated call
312
     * @param string $alternative
313
     *  The name of the new method to use
314
     * @param array $opts (optional)
315
     * @param string $opts.message-format
0 ignored issues
show
Bug introduced by
There is no parameter named $opts.message-format. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
316
     *  The sprintf format to apply to $method
317
     * @param string $opts.alternative-format
0 ignored issues
show
Documentation introduced by
There is no parameter named $opts.alternative-format. Did you maybe mean $alternative?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
318
     *  The sprintf format to apply to $alternative
319
     * @param string $opts.removal-format
0 ignored issues
show
Bug introduced by
There is no parameter named $opts.removal-format. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
320
     *  The sprintf format to apply to $opts.removal-version
321
     * @param string $opts.removal-version
0 ignored issues
show
Bug introduced by
There is no parameter named $opts.removal-version. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
322
     *  The Symphony version at which the removal is planned
323
     * @param boolean $opts.write-to-log
0 ignored issues
show
Bug introduced by
There is no parameter named $opts.write-to-log. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
324
     *  If set to true, this message will be immediately written to the log. By default
325
     *  this is set to false, which means that it will only be added to the array ready
326
     *  for writing
327
     * @param boolean $opts.addbreak
0 ignored issues
show
Bug introduced by
There is no parameter named $opts.addbreak. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
328
     *  To be used in conjunction with `$opts.write-to-log`, this will add a line break
329
     *  before writing this message in the log file. Defaults to true.
330
     * @param boolean $opts.append
0 ignored issues
show
Bug introduced by
There is no parameter named $opts.append. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
331
     *  If set to true, the given `$message` will be append to the previous log
332
     *  message found in the `$_log` array
333
     * @param boolean $opts.addtrace
0 ignored issues
show
Bug introduced by
There is no parameter named $opts.addtrace. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
334
     *  If set to true, the caller of the function will be added. Defaults to true.
335
     * @return boolean|null
336
     *  If `$writeToLog` is passed, this function will return boolean, otherwise
337
     *  void
338
     */
339
    public function pushDeprecateWarningToLog($method, $alternative = null, array $opts = array())
340
    {
341
        $defaults = array(
342
            'message-format' => __('The method `%s` is deprecated.'),
343
            'alternative-format' => __('Please use `%s` instead.'),
344
            'removal-format' => __('It will be removed in Symphony %s.'),
345
            'removal-version' => '3.0.0',
346
            'write-to-log' => true,
347
            'addbreak' => true,
348
            'append' => false,
349
            'addtrace' => true,
350
        );
351
        $opts = array_replace($defaults, $opts);
352
353
        $message = sprintf($opts['message-format'], $method);
354
        if (!empty($opts['removal-version'])) {
355
            $message .= ' ' . sprintf($opts['removal-format'], $opts['removal-version']);
356
        }
357
        if (!empty($alternative)) {
358
            $message .= ' ' . sprintf($opts['alternative-format'], $alternative);
359
        }
360
        if ($opts['addtrace'] === true) {
361
            if (version_compare(phpversion(), '5.4', '<')) {
362
                $trace = debug_backtrace(0);
363
            } else {
364
                $trace = debug_backtrace(0, 3);
365
            }
366
            $index = isset($trace[2]['class']) ? 2 : 1;
367
            $caller = $trace[$index]['class'] . '::' . $trace[$index]['function'] . '()';
368
            $file = basename($trace[$index - 1]['file']);
369
            $line = $trace[$index - 1]['line'];
370
            $message .= " Called from `$caller` in $file at line $line";
371
        }
372
373
        return $this->pushToLog($message, E_DEPRECATED, $opts['write-to-log'], $opts['addbreak'], $opts['append']);
374
    }
375
376
    /**
377
     * The function handles the rotation of the log files. By default it will open
378
     * the current log file, 'main', which is written to `$_log_path` and
379
     * check it's file size doesn't exceed `$_max_size`. If it does, the log
380
     * is appended with a date stamp and if `$_archive` has been set, it will
381
     * be archived and stored. If a log file has exceeded it's size, or `Log::OVERWRITE`
382
     * flag is set, the existing log file is removed and a new one created. Essentially,
383
     * if a log file has not reached it's `$_max_size` and the the flag is not
384
     * set to `Log::OVERWRITE`, this function does nothing.
385
     *
386
     * @link http://au.php.net/manual/en/function.intval.php
387
     * @param integer $flag
388
     *  One of the Log constants, either `Log::APPEND` or `Log::OVERWRITE`
389
     *  By default this is `Log::APPEND`
390
     * @param integer $mode
391
     *  The file mode used to apply to the archived log, by default this is 0777. Note that this
392
     *  parameter is modified using PHP's intval function with base 8.
393
     * @throws Exception
394
     * @return integer
395
     *  Returns 1 if the log was overwritten, or 2 otherwise.
396
     */
397
    public function open($flag = self::APPEND, $mode = 0777)
398
    {
399
        if (!file_exists($this->_log_path)) {
400
            $flag = self::OVERWRITE;
401
        }
402
403
        if ($flag == self::APPEND && file_exists($this->_log_path) && is_readable($this->_log_path)) {
404
            if ($this->_max_size > 0 && filesize($this->_log_path) > $this->_max_size) {
405
                $flag = self::OVERWRITE;
406
407
                if ($this->_archive) {
408
                    $this->close();
409
                    $file = $this->_log_path . DateTimeObj::get('Ymdh').'.gz';
410
                    if (function_exists('gzopen64')) {
411
                        $handle = gzopen64($file, 'w9');
412
                    } else {
413
                        $handle = gzopen($file, 'w9');
414
                    }
415
                    gzwrite($handle, file_get_contents($this->_log_path));
416
                    gzclose($handle);
417
                    chmod($file, intval($mode, 8));
418
                }
419
            }
420
        }
421
422
        if ($flag == self::OVERWRITE) {
423
            General::deleteFile($this->_log_path);
424
425
            $this->writeToLog('============================================', true);
426
            $this->writeToLog('Log Created: ' . DateTimeObj::get('c'), true);
427
            $this->writeToLog('============================================', true);
428
429
            @chmod($this->_log_path, intval($mode, 8));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
430
431
            return 1;
432
        }
433
434
        return 2;
435
    }
436
437
    /**
438
     * Writes a end of file block at the end of the log file with a datetime
439
     * stamp of when the log file was closed.
440
     */
441
    public function close()
442
    {
443
        $this->writeToLog('============================================', true);
444
        $this->writeToLog('Log Closed: ' . DateTimeObj::get('c'), true);
445
        $this->writeToLog("============================================" . PHP_EOL . PHP_EOL, true);
446
    }
447
448
    /* Initialises the log file by writing into it the log name, the date of
449
     * creation, the current Symphony version and the current domain.
450
     *
451
     * @param string $name
452
     *  The name of the log being initialised
453
     */
454
    public function initialise($name)
455
    {
456
        $version = (is_null(Symphony::Configuration())) ? VERSION : Symphony::Configuration()->get('version', 'symphony');
457
458
        $this->writeToLog($name, true);
459
        $this->writeToLog('Opened:  '. DateTimeObj::get('c'), true);
460
        $this->writeToLog('Version: '. $version, true);
461
        $this->writeToLog('Domain:  '. DOMAIN, true);
462
        $this->writeToLog('--------------------------------------------', true);
463
    }
464
}
465