Passed
Push — master ( 8dcc68...34e8da )
by
unknown
23:44 queued 20:40
created

zpush_error_handler()   C

Complexity

Conditions 12
Paths 22

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 21
nc 22
nop 4
dl 0
loc 31
rs 6.9666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * SPDX-License-Identifier: AGPL-3.0-only
4
 * SPDX-FileCopyrightText: Copyright 2007-2016 Zarafa Deutschland GmbH
5
 * SPDX-FileCopyrightText: Copyright 2020-2022 grommunio GmbH
6
 *
7
 * Debug and logging
8
 */
9
10
class ZLog {
11
    static private $wbxmlDebug = '';
12
    static private $lastLogs = array();
13
14
    /**
15
     * @var Log $logger
16
     */
17
    static private $logger = null;
18
19
    /**
20
     * Initializes the logging.
21
     *
22
     * @access public
23
     * @return boolean
24
     */
25
    static public function Initialize() {
26
        // define some constants for the logging
27
        if (!defined('LOGUSERLEVEL'))
28
            define('LOGUSERLEVEL', LOGLEVEL_OFF);
29
30
        if (!defined('LOGLEVEL'))
31
            define('LOGLEVEL', LOGLEVEL_OFF);
32
33
        $logger = self::getLogger();
0 ignored issues
show
Unused Code introduced by
The assignment to $logger is dead and can be removed.
Loading history...
34
35
        return true;
36
    }
37
38
    /**
39
     * Check if WBXML logging is enabled in current LOG(USER)LEVEL.
40
     *
41
     * @access public
42
     * @return boolean
43
     */
44
    static public function IsWbxmlDebugEnabled() {
45
        return LOGLEVEL >= LOGLEVEL_WBXML || (LOGUSERLEVEL >= LOGLEVEL_WBXML && self::getLogger()->HasSpecialLogUsers());
46
    }
47
48
    /**
49
     * Writes a log line.
50
     *
51
     * @param int       $loglevel           one of the defined LOGLEVELS
52
     * @param string    $message
53
     * @param boolean   $truncate           indicate if the message should be truncated, default true
54
     *
55
     * @access public
56
     * @return void
57
     */
58
    static public function Write($loglevel, $message, $truncate = true) {
59
        // truncate messages longer than 10 KB
60
        $messagesize = strlen($message);
61
        if ($truncate && $messagesize > 10240)
62
            $message = substr($message, 0, 10240) . sprintf(" <log message with %d bytes truncated>", $messagesize);
63
64
        self::$lastLogs[$loglevel] = $message;
65
66
        try {
67
            self::getLogger()->Log($loglevel, $message);
68
        }
69
        catch (\Exception $e) {
70
            //@TODO How should we handle logging error ?
71
            // Ignore any error.
72
        }
73
74
        if ($loglevel & LOGLEVEL_WBXMLSTACK) {
75
            self::$wbxmlDebug .= $message . PHP_EOL;
76
        }
77
    }
78
79
    /**
80
     * Returns logged information about the WBXML stack.
81
     *
82
     * @access public
83
     * @return string
84
     */
85
    static public function GetWBXMLDebugInfo() {
86
        return trim(self::$wbxmlDebug);
87
    }
88
89
    /**
90
     * Returns the last message logged for a log level.
91
     *
92
     * @param int       $loglevel           one of the defined LOGLEVELS
93
     *
94
     * @access public
95
     * @return string/false     returns false if there was no message logged in that level
0 ignored issues
show
Documentation Bug introduced by
The doc comment string/false at position 0 could not be parsed: Unknown type name 'string/false' at position 0 in string/false.
Loading history...
96
     */
97
    static public function GetLastMessage($loglevel) {
98
        return (isset(self::$lastLogs[$loglevel]))?self::$lastLogs[$loglevel]:false;
99
    }
100
101
    /**
102
     * If called, the authenticated current user gets an extra log-file.
103
     *
104
     * If called until the user is authenticated (e.g. at the end of IBackend->Logon()) all log
105
     * messages that happened until this point will also be logged.
106
     *
107
     * @access public
108
     * @return void
109
     */
110
    static public function SpecialLogUser() {
111
        self::getLogger()->SpecialLogUser();
112
    }
113
114
    /**
115
     * Returns the logger object. If no logger has been initialized, FileLog will be initialized and returned.
116
     *
117
     * @access private
118
     * @return Log
119
     * @throws Exception thrown if the logger class cannot be instantiated.
120
     */
121
    static private function getLogger() {
122
        if (!self::$logger) {
123
            global $specialLogUsers; // This variable comes from the configuration file (config.php)
124
125
            $logger = LOGBACKEND_CLASS;
126
            if (!class_exists($logger)) {
127
                $errmsg = 'The configured logging class `'.$logger.'` does not exist. Check your configuration.';
128
                error_log($errmsg);
129
                throw new \Exception($errmsg);
130
            }
131
132
            // if there is an impersonated user it's used instead of the GET user
133
            if (Request::GetImpersonatedUser()) {
134
                $user = Request::GetImpersonatedUser();
135
            }
136
            else {
137
                list($user) = Utils::SplitDomainUser(strtolower(Request::GetGETUser()));
138
            }
139
140
            self::$logger = new $logger();
141
            self::$logger->SetUser($user);
142
            self::$logger->SetAuthUser(Request::GetAuthUser());
143
            self::$logger->SetSpecialLogUsers($specialLogUsers);
144
            self::$logger->SetDevid(Request::GetDeviceID());
145
            self::$logger->SetPid(@getmypid());
146
            self::$logger->AfterInitialize();
147
        }
148
        return self::$logger;
149
    }
150
151
    /**----------------------------------------------------------------------------------------------------------
152
     * private log stuff
153
     */
154
}
155
156
/**----------------------------------------------------------------------------------------------------------
157
 * Legacy debug stuff
158
 */
159
160
// TODO review error handler
161
function zpush_error_handler($errno, $errstr, $errfile, $errline) {
162
    if (defined('LOG_ERROR_MASK')) $errno &= LOG_ERROR_MASK;
0 ignored issues
show
Bug introduced by
The constant LOG_ERROR_MASK was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
163
164
    switch ($errno) {
165
        case 0:
166
            // logging disabled by LOG_ERROR_MASK
167
            break;
168
169
        case E_DEPRECATED:
170
            // do not handle this message
171
            break;
172
173
        case E_NOTICE:
174
        case E_WARNING:
175
            // TODO check if there is a better way to avoid these messages
176
            if (stripos($errfile,'interprocessdata') !== false && stripos($errstr,'shm_get_var()') !== false)
177
                break;
178
            ZLog::Write(LOGLEVEL_WARN, "$errfile:$errline $errstr ($errno)");
179
            break;
180
181
        default:
182
            $bt = debug_backtrace();
183
            ZLog::Write(LOGLEVEL_ERROR, "trace error: $errfile:$errline $errstr ($errno) - backtrace: ". (count($bt)-1) . " steps");
184
            for($i = 1, $bt_length = count($bt); $i < $bt_length; $i++) {
185
                $file = $line = "unknown";
186
                if (isset($bt[$i]['file'])) $file = $bt[$i]['file'];
187
                if (isset($bt[$i]['line'])) $line = $bt[$i]['line'];
188
                ZLog::Write(LOGLEVEL_ERROR, "trace: $i:". $file . ":" . $line. " - " . ((isset($bt[$i]['class']))? $bt[$i]['class'] . $bt[$i]['type']:""). $bt[$i]['function']. "()");
189
            }
190
            //throw new Exception("An error occurred.");
191
            break;
192
    }
193
}
194
195
error_reporting(E_ALL);
196
set_error_handler("zpush_error_handler");
197
198
199
function zpush_fatal_handler() {
200
    $errfile = "unknown file";
0 ignored issues
show
Unused Code introduced by
The assignment to $errfile is dead and can be removed.
Loading history...
201
    $errstr  = "shutdown";
0 ignored issues
show
Unused Code introduced by
The assignment to $errstr is dead and can be removed.
Loading history...
202
    $errno   = E_CORE_ERROR;
0 ignored issues
show
Unused Code introduced by
The assignment to $errno is dead and can be removed.
Loading history...
203
    $errline = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $errline is dead and can be removed.
Loading history...
204
205
    $error = error_get_last();
206
207
    if( $error !== null) {
208
        $errno   = $error["type"];
209
        $errfile = $error["file"];
210
        $errline = $error["line"];
211
        $errstr  = $error["message"];
212
213
        // do NOT log PHP Notice, Warning, Deprecated or Strict as FATAL
214
        if ($errno & ~(E_NOTICE|E_WARNING|E_DEPRECATED|E_STRICT)) {
215
            ZLog::Write(LOGLEVEL_FATAL, sprintf("Fatal error: %s:%d - %s (%s)", $errfile, $errline, $errstr, $errno));
216
        }
217
    }
218
}
219
register_shutdown_function("zpush_fatal_handler");
220