Passed
Push — devel-3.0 ( bc80e8...31a38b )
by Rubén
03:32
created

flattenExceptionBacktrace()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 26
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 2
nop 1
dl 0
loc 26
rs 8.9777
c 0
b 0
f 0
1
<?php
2
/**
3
 * sysPass
4
 *
5
 * @author    nuxsmin
6
 * @link      http://syspass.org
7
 * @copyright 2012-2017, Rubén Domínguez nuxsmin@$syspass.org
8
 *
9
 * This file is part of sysPass.
10
 *
11
 * sysPass is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation, either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * sysPass is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 *  along with sysPass.  If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
/**
26
 * [type] [caller] data
27
 */
28
define('LOG_FORMAT', "[%s] [%s] %s");
29
/**
30
 * [timestamp] [type] [caller] data
31
 */
32
define('LOG_FORMAT_OWN', "%s [%s] [%s] %s\n");
33
34
/**
35
 * Basic logger to handle some debugging and exception messages.
36
 *
37
 * It will log messages into syspass.log or PHP error log file.
38
 *
39
 * In order to log debugging messages, DEBUG constant must be set to true.
40
 *
41
 * A more advanced event logging should be handled through EventDispatcher
42
 *
43
 * @param mixed $data
44
 * @param string $type
45
 */
46
function logger($data, $type = 'DEBUG')
47
{
48
    if (!DEBUG && $type === 'DEBUG') {
49
        return;
50
    }
51
52
    $date = date('Y-m-d H:i:s');
53
    $caller = getLastCaller();
54
55
    if (is_scalar($data)) {
56
        $line = sprintf(LOG_FORMAT_OWN, $date, $type, $caller, $data);
57
    } else {
58
        $line = sprintf(LOG_FORMAT_OWN, $date, $type, $caller, print_r($data, true));
59
    }
60
61
    $useOwn = (!defined('LOG_FILE')
62
        || !error_log($line, 3, LOG_FILE)
63
    );
64
65
    if ($useOwn === false) {
66
        if (is_scalar($data)) {
67
            $line = sprintf(LOG_FORMAT, $type, $caller, $data);
68
        } else {
69
            $line = sprintf(LOG_FORMAT, $type, $caller, print_r($data, true));
70
        }
71
72
        error_log($line);
73
    }
74
}
75
76
/**
77
 * Print last callers from backtrace
78
 */
79
function printLastCallers()
80
{
81
    logger(formatTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)));
82
}
83
84
/**
85
 * Print last caller from backtrace
86
 *
87
 * @return string
88
 */
89
function getLastCaller()
90
{
91
    $callers = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
92
93
    if (isset($callers[2])
94
        && isset($callers[2]['class'])
95
        && isset($callers[2]['function'])
96
    ) {
97
        return $callers[2]['class'] . '::' . $callers[2]['function'];
98
    }
99
100
    return 'N/A';
101
}
102
103
/**
104
 * Process an exception and log into the error log
105
 *
106
 * @param \Exception $exception
107
 */
108
function processException(\Exception $exception)
109
{
110
    logger(sprintf("%s\n%s", __($exception->getMessage()), $exception->getTraceAsString()), 'EXCEPTION');
111
112
    if (($previous = $exception->getPrevious()) !== null) {
113
        logger(sprintf("(P) %s\n%s", __($previous->getMessage()), $previous->getTraceAsString()), 'EXCEPTION');
114
    }
115
}
116
117
/**
118
 * @param $trace
119
 *
120
 * @return string
121
 */
122
function formatTrace($trace)
123
{
124
    $btLine = [];
125
    $i = 0;
126
127
    foreach ($trace as $caller) {
128
        $class = isset($caller['class']) ? $caller['class'] : '';
129
        $file = isset($caller['file']) ? $caller['file'] : '';
130
        $line = isset($caller['line']) ? $caller['line'] : 0;
131
132
        $btLine[] = sprintf('Caller %d: %s\%s (%s:%d)', $i, $class, $caller['function'], $file, $line);
133
        $i++;
134
    }
135
136
    return implode(PHP_EOL, $btLine);
137
}
138
139
/**
140
 * Alias gettext function
141
 *
142
 * @param string $message
143
 * @param bool $translate Si es necesario traducir
144
 *
145
 * @return string
146
 */
147
function __($message, $translate = true)
148
{
149
    return $translate === true && $message !== '' && mb_strlen($message) < 4096 ? gettext($message) : $message;
150
}
151
152
/**
153
 * Returns an untranslated string (gettext placeholder)
154
 *
155
 * @param string $message
156
 *
157
 * @return string
158
 */
159
function __u($message)
160
{
161
    return $message;
162
}
163
164
/**
165
 * Alias para obtener las locales de un dominio
166
 *
167
 * @param string $domain
168
 * @param string $message
169
 * @param bool $translate
170
 *
171
 * @return string
172
 */
173
function _t($domain, $message, $translate = true)
174
{
175
    return $translate === true && $message !== '' && mb_strlen($message) < 4096 ? dgettext($domain, $message) : $message;
176
}
177
178
/**
179
 * Capitalización de cadenas multi byte
180
 *
181
 * @param $string
182
 *
183
 * @return string
184
 */
185
function mb_ucfirst($string)
186
{
187
    return mb_strtoupper(mb_substr($string, 0, 1));
188
}
189
190
/**
191
 * Devuelve el tiempo actual en coma flotante.
192
 * Esta función se utiliza para calcular el tiempo de renderizado con coma flotante
193
 *
194
 * @param float $from
195
 *
196
 * @returns float con el tiempo actual
197
 * @return float
198
 */
199
function getElapsedTime($from)
200
{
201
    if ($from === 0) {
0 ignored issues
show
introduced by
The condition $from === 0 is always false.
Loading history...
202
        return 0;
203
    }
204
205
    return microtime(true) - floatval($from);
206
}
207
208
/**
209
 * Inicializar módulo
210
 *
211
 * @param $module
212
 */
213
function initModule($module)
214
{
215
    $dir = dir(MODULES_PATH);
216
217
    while (false !== ($entry = $dir->read())) {
218
        $moduleFile = MODULES_PATH . DIRECTORY_SEPARATOR . $entry . DIRECTORY_SEPARATOR . 'module.php';
219
220
        if ($entry === $module && file_exists($moduleFile)) {
221
            require $moduleFile;
222
        }
223
    }
224
225
    $dir->close();
226
}
227
228
/**
229
 * @param $dir
230
 * @param $levels
231
 *
232
 * @return bool|string
233
 */
234
function nDirname($dir, $levels)
235
{
236
    if (version_compare(PHP_VERSION, '7.0') === -1) {
237
        logger(realpath(dirname($dir) . str_repeat('../', $levels)));
238
239
        return realpath(dirname($dir) . str_repeat('../', $levels));
240
    }
241
242
    return dirname($dir, $levels);
243
}
244
245
/**
246
 * Prints a fancy trace info using Xdebug extension
247
 */
248
function printTraceInfo()
249
{
250
    if (DEBUG && extension_loaded('xdebug')) {
251
        xdebug_print_function_stack();
252
    }
253
}
254