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 ( 4ccb09...2f9dc2 )
by Nicolas
03:16
created

Log::pushDeprecateWarningToLog()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 32
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 24
nc 12
nop 3
dl 0
loc 32
rs 8.439
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 date format that this Log entries will be written as. Defaults to
54
     * Y/m/d H:i:s.
55
     * @var string
56
     */
57
    private $_datetime_format = 'Y/m/d H:i:s';
58
59
    /**
60
     * The log constructor takes a path to the folder where the Log should be
61
     * written to.
62
     *
63
     * @param string $path
64
     *  The path to the folder where the Log files should be written
65
     */
66
    public function __construct($path)
67
    {
68
        $this->setLogPath($path);
69
    }
70
71
    /**
72
     * Setter for the `$_log_path`.
73
     *
74
     * @param string $path
75
     *  The path to the folder where the Log files should be written
76
     */
77
    public function setLogPath($path)
78
    {
79
        $this->_log_path = $path;
80
    }
81
82
    /**
83
     * Accessor for the `$_log_path`.
84
     *
85
     * @return string
86
     */
87
    public function getLogPath()
88
    {
89
        return $this->_log_path;
90
    }
91
92
    /**
93
     * Accessor for the `$_log`.
94
     *
95
     * @return array
96
     */
97
    public function getLog()
98
    {
99
        return $this->_log;
100
    }
101
102
    /**
103
     * Setter for the `$_archive`.
104
     *
105
     * @param boolean $archive
106
     *  If true, Log files will be archived using gz when they are rotated,
107
     *  otherwise they will just be overwritten when they are due for rotation
108
     */
109
    public function setArchive($archive)
110
    {
111
        $this->_archive = $archive;
112
    }
113
114
    /**
115
     * Setter for the `$_max_size`.
116
     *
117
     * @param integer $size
118
     *  The size, in bytes, that the Log can reach before it is rotated.
119
     */
120
    public function setMaxSize($size)
121
    {
122
        $this->_max_size = $size;
123
    }
124
125
    /**
126
     * Setter for the `$_date_format`.
127
     *
128
     * @since Symphony 2.2
129
     * @link http://au.php.net/manual/en/function.date.php
130
     * @param string $format
131
     *  Takes a valid date format using the PHP date tokens
132
     */
133
    public function setDateTimeFormat($format)
134
    {
135
        if (empty($format)) {
136
            throw new Exception('Datetime format can not be empty');
137
        }
138
        $this->_datetime_format = $format;
139
    }
140
141
    /**
142
     * Given a PHP error constant, return a human readable name. Uses the
143
     * `GenericErrorHandler::$errorTypeStrings` array to return
144
     * the name
145
     *
146
     * @see core.GenericErrorHandler::$errorTypeStrings
147
     * @param integer $type
148
     *  A PHP error constant
149
     * @return string
150
     *  A human readable name of the error constant, or if the type is not
151
     *  found, UNKNOWN.
152
     */
153
    private function __defineNameString($type)
154
    {
155
        if (isset(GenericErrorHandler::$errorTypeStrings[$type])) {
156
            return GenericErrorHandler::$errorTypeStrings[$type];
157
        }
158
159
        return 'UNKNOWN';
160
    }
161
162
    /**
163
     * Function will return the last message added to `$_log` and remove
164
     * it from the array.
165
     *
166
     * @return array|boolean
167
     *  Returns an associative array of a log message, containing the type of the log
168
     *  message, the actual message and the time at the which it was added to the log.
169
     *  If the log is empty, this function removes false.
170
     */
171
    public function popFromLog()
172
    {
173
        if (!empty($this->_log)) {
174
            return array_pop($this->_log);
175
        }
176
177
        return false;
178
    }
179
180
    /**
181
     * Given a message, this function will add it to the internal `$_log`
182
     * so that it can be written to the Log. Optional parameters all the message to
183
     * be immediately written, insert line breaks or add to the last log message
184
     *
185
     * @param string $message
186
     *  The message to add to the Log
187
     * @param integer $type
188
     *  A PHP error constant for this message, defaults to E_NOTICE
189
     * @param boolean $writeToLog
190
     *  If set to true, this message will be immediately written to the log. By default
191
     *  this is set to false, which means that it will only be added to the array ready
192
     *  for writing
193
     * @param boolean $addbreak
194
     *  To be used in conjunction with `$writeToLog`, this will add a line break
195
     *  before writing this message in the log file. Defaults to true.
196
     * @param boolean $append
197
     *  If set to true, the given `$message` will be append to the previous log
198
     *  message found in the `$_log` array
199
     * @return boolean|null
200
     *  If `$writeToLog` is passed, this function will return boolean, otherwise
201
     *  void
202
     */
203
    public function pushToLog($message, $type = E_NOTICE, $writeToLog = false, $addbreak = true, $append = false)
204
    {
205
        if ($append) {
206
            $this->_log[count($this->_log) - 1]['message'] =  $this->_log[count($this->_log) - 1]['message'] . $message;
207
        } else {
208
            array_push($this->_log, array('type' => $type, 'time' => time(), 'message' => $message));
209
            $message = DateTimeObj::get($this->_datetime_format) . ' > ' . $this->__defineNameString($type) . ': ' . $message;
210
        }
211
212
        if ($writeToLog) {
213
            return $this->writeToLog($message, $addbreak);
214
        }
215
    }
216
217
    /**
218
     * This function will write the given message to the log file. Messages will be appended
219
     * the existing log file.
220
     *
221
     * @param string $message
222
     *  The message to add to the Log
223
     * @param boolean $addbreak
224
     *  To be used in conjunction with `$writeToLog`, this will add a line break
225
     *  before writing this message in the log file. Defaults to true.
226
     * @return boolean
227
     *  Returns true if the message was written successfully, false otherwise
228
     */
229
    public function writeToLog($message, $addbreak = true)
230
    {
231
        if (file_exists($this->_log_path) && !is_writable($this->_log_path)) {
232
            $this->pushToLog('Could not write to Log. It is not readable.');
233
            return false;
234
        }
235
236
        $permissions = class_exists('Symphony', false) ? Symphony::Configuration()->get('write_mode', 'file') : '0664';
237
238
        return General::writeFile($this->_log_path, $message . ($addbreak ? PHP_EOL : ''), $permissions, 'a+');
239
    }
240
241
    /**
242
     * Given an Throwable, this function will add it to the internal `$_log`
243
     * so that it can be written to the Log.
244
     *
245
     * @since Symphony 2.3.2
246
     *
247
     * @since Symphony 2.7.0
248
     *  This function works with both Exceptions and Throwable
249
     *  Supporting both PHP 5.6 and 7 forces use to not qualify the $e parameter
250
     *
251
     * @param Throwable $exception
252
     * @param boolean $writeToLog
253
     *  If set to true, this message will be immediately written to the log. By default
254
     *  this is set to false, which means that it will only be added to the array ready
255
     *  for writing
256
     * @param boolean $addbreak
257
     *  To be used in conjunction with `$writeToLog`, this will add a line break
258
     *  before writing this message in the log file. Defaults to true.
259
     * @param boolean $append
260
     *  If set to true, the given `$message` will be append to the previous log
261
     *  message found in the `$_log` array
262
     * @return boolean|null
263
     *  If `$writeToLog` is passed, this function will return boolean, otherwise
264
     *  void
265
     */
266
    public function pushExceptionToLog($exception, $writeToLog = false, $addbreak = true, $append = false)
267
    {
268
        $message = sprintf(
269
            '%s %s - %s on line %d of %s',
270
            get_class($exception),
271
            $exception->getCode(),
272
            $exception->getMessage(),
273
            $exception->getLine(),
274
            $exception->getFile()
275
        );
276
277
        return $this->pushToLog($message, $exception->getCode(), $writeToLog, $addbreak, $append);
278
    }
279
280
    /**
281
     * Given an method name, this function will properly format a message
282
     * and pass it down to `pushToLog()`
283
     *
284
     * @see Log::pushToLog()
285
     * @since Symphony 2.7.0
286
     * @param string $method
287
     *  The name of the deprecated call
288
     * @param string $alternative
289
     *  The name of the new method to use
290
     * @param array $opts (optional)
291
     * @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...
292
     *  The sprintf format to apply to $method
293
     * @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...
294
     *  The sprintf format to apply to $alternative
295
     * @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...
296
     *  The sprintf format to apply to $opts.removal-version
297
     * @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...
298
     *  The Symphony version at which the removal is planned
299
     * @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...
300
     *  If set to true, this message will be immediately written to the log. By default
301
     *  this is set to false, which means that it will only be added to the array ready
302
     *  for writing
303
     * @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...
304
     *  To be used in conjunction with `$opts.write-to-log`, this will add a line break
305
     *  before writing this message in the log file. Defaults to true.
306
     * @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...
307
     *  If set to true, the given `$message` will be append to the previous log
308
     *  message found in the `$_log` array
309
     * @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...
310
     *  If set to true, the caller of the function will be added. Defaults to true.
311
     * @return boolean|null
312
     *  If `$writeToLog` is passed, this function will return boolean, otherwise
313
     *  void
314
     */
315
    public function pushDeprecateWarningToLog($method, $alternative = null, array $opts = array())
316
    {
317
        $defaults = array(
318
            'message-format' => __('The method `%s` is deprecated.'),
319
            'alternative-format' => __('Please use `%s` instead.'),
320
            'removal-format' => __('It will be removed in Symphony %s.'),
321
            'removal-version' => '3.0.0',
322
            'write-to-log' => true,
323
            'addbreak' => true,
324
            'append' => false,
325
            'addtrace' => true,
326
        );
327
        $opts = array_replace($defaults, $opts);
328
329
        $message = sprintf($opts['message-format'], $method);
330
        if (!empty($opts['removal-version'])) {
331
            $message .= ' ' . sprintf($opts['removal-format'], $opts['removal-version']);
332
        }
333
        if (!empty($alternative)) {
334
            $message .= ' ' . sprintf($opts['alternative-format'], $alternative);
335
        }
336
        if ($opts['addtrace'] === true) {
337
            $trace = debug_backtrace(0, 3);
338
            $index = isset($trace[2]['class']) ? 2 : 1;
339
            $caller = $trace[$index]['class'] . '::' . $trace[$index]['function'] . '()';
340
            $file = basename($trace[$index - 1]['file']);
341
            $line = $trace[$index - 1]['line'];
342
            $message .= " Called from `$caller` in $file at line $line";
343
        }
344
345
        return $this->pushToLog($message, E_DEPRECATED, $opts['write-to-log'], $opts['addbreak'], $opts['append']);
346
    }
347
348
    /**
349
     * The function handles the rotation of the log files. By default it will open
350
     * the current log file, 'main', which is written to `$_log_path` and
351
     * check it's file size doesn't exceed `$_max_size`. If it does, the log
352
     * is appended with a date stamp and if `$_archive` has been set, it will
353
     * be archived and stored. If a log file has exceeded it's size, or `Log::OVERWRITE`
354
     * flag is set, the existing log file is removed and a new one created. Essentially,
355
     * if a log file has not reached it's `$_max_size` and the the flag is not
356
     * set to `Log::OVERWRITE`, this function does nothing.
357
     *
358
     * @link http://au.php.net/manual/en/function.intval.php
359
     * @param integer $flag
360
     *  One of the Log constants, either `Log::APPEND` or `Log::OVERWRITE`
361
     *  By default this is `Log::APPEND`
362
     * @param integer $mode
363
     *  The file mode used to apply to the archived log, by default this is 0777. Note that this
364
     *  parameter is modified using PHP's intval function with base 8.
365
     * @throws Exception
366
     * @return integer
367
     *  Returns 1 if the log was overwritten, or 2 otherwise.
368
     */
369
    public function open($flag = self::APPEND, $mode = 0777)
370
    {
371
        if (!file_exists($this->_log_path)) {
372
            $flag = self::OVERWRITE;
373
        }
374
375
        if ($flag == self::APPEND && file_exists($this->_log_path) && is_readable($this->_log_path)) {
376
            if ($this->_max_size > 0 && filesize($this->_log_path) > $this->_max_size) {
377
                $flag = self::OVERWRITE;
378
379
                if ($this->_archive) {
380
                    $this->close();
381
                    $file = $this->_log_path . DateTimeObj::get('Ymdh').'.gz';
382
                    if (function_exists('gzopen64')) {
383
                        $handle = gzopen64($file, 'w9');
384
                    } else {
385
                        $handle = gzopen($file, 'w9');
386
                    }
387
                    gzwrite($handle, file_get_contents($this->_log_path));
388
                    gzclose($handle);
389
                    chmod($file, intval($mode, 8));
390
                }
391
            }
392
        }
393
394
        if ($flag == self::OVERWRITE) {
395
            if (file_exists($this->_log_path) && is_writable($this->_log_path)) {
396
                General::deleteFile($this->_log_path);
397
            }
398
399
            $this->writeToLog('============================================', true);
400
            $this->writeToLog('Log Created: ' . DateTimeObj::get('c'), true);
401
            $this->writeToLog('============================================', true);
402
403
            @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...
404
405
            return 1;
406
        }
407
408
        return 2;
409
    }
410
411
    /**
412
     * Writes a end of file block at the end of the log file with a datetime
413
     * stamp of when the log file was closed.
414
     */
415
    public function close()
416
    {
417
        $this->writeToLog('============================================', true);
418
        $this->writeToLog('Log Closed: ' . DateTimeObj::get('c'), true);
419
        $this->writeToLog("============================================" . PHP_EOL . PHP_EOL, true);
420
    }
421
422
    /* Initialises the log file by writing into it the log name, the date of
423
     * creation, the current Symphony version and the current domain.
424
     *
425
     * @param string $name
426
     *  The name of the log being initialised
427
     */
428
    public function initialise($name)
429
    {
430
        $version = (is_null(Symphony::Configuration())) ? VERSION : Symphony::Configuration()->get('version', 'symphony');
431
432
        $this->writeToLog($name, true);
433
        $this->writeToLog('Opened:  '. DateTimeObj::get('c'), true);
434
        $this->writeToLog('Version: '. $version, true);
435
        $this->writeToLog('Domain:  '. DOMAIN, true);
436
        $this->writeToLog('--------------------------------------------', true);
437
    }
438
}
439