-
Notifications
You must be signed in to change notification settings - Fork 44
/
utils.php
499 lines (454 loc) · 14.5 KB
/
utils.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
<?php
if (!function_exists('http_build_url'))
{
define('HTTP_URL_REPLACE', 1); // Replace every part of the first URL when there's one of the second URL
define('HTTP_URL_JOIN_PATH', 2); // Join relative paths
define('HTTP_URL_JOIN_QUERY', 4); // Join query strings
define('HTTP_URL_STRIP_USER', 8); // Strip any user authentication information
define('HTTP_URL_STRIP_PASS', 16); // Strip any password authentication information
define('HTTP_URL_STRIP_AUTH', 32); // Strip any authentication information
define('HTTP_URL_STRIP_PORT', 64); // Strip explicit port numbers
define('HTTP_URL_STRIP_PATH', 128); // Strip complete path
define('HTTP_URL_STRIP_QUERY', 256); // Strip query string
define('HTTP_URL_STRIP_FRAGMENT', 512); // Strip any fragments (#identifier)
define('HTTP_URL_STRIP_ALL', 1024); // Strip anything but scheme and host
// Build an URL
// The parts of the second URL will be merged into the first according to the flags argument.
//
// @param mixed (Part(s) of) an URL in form of a string or associative array like parse_url() returns
// @param mixed Same as the first argument
// @param int A bitmask of binary or'ed HTTP_URL constants (Optional)HTTP_URL_REPLACE is the default
// @param array If set, it will be filled with the parts of the composed url like parse_url() would return
function http_build_url($url, $parts=array(), $flags=HTTP_URL_REPLACE, &$new_url=false)
{
$keys = array('user','pass','port','path','query','fragment');
// HTTP_URL_STRIP_ALL becomes all the HTTP_URL_STRIP_Xs
if ($flags & HTTP_URL_STRIP_ALL)
{
$flags |= HTTP_URL_STRIP_USER;
$flags |= HTTP_URL_STRIP_PASS;
$flags |= HTTP_URL_STRIP_PORT;
$flags |= HTTP_URL_STRIP_PATH;
$flags |= HTTP_URL_STRIP_QUERY;
$flags |= HTTP_URL_STRIP_FRAGMENT;
}
// HTTP_URL_STRIP_AUTH becomes HTTP_URL_STRIP_USER and HTTP_URL_STRIP_PASS
else if ($flags & HTTP_URL_STRIP_AUTH)
{
$flags |= HTTP_URL_STRIP_USER;
$flags |= HTTP_URL_STRIP_PASS;
}
// Parse the original URL
$parse_url = parse_url($url);
// Scheme and Host are always replaced
if (isset($parts['scheme']))
$parse_url['scheme'] = $parts['scheme'];
if (isset($parts['host']))
$parse_url['host'] = $parts['host'];
// (If applicable) Replace the original URL with it's new parts
if ($flags & HTTP_URL_REPLACE)
{
foreach ($keys as $key)
{
if (isset($parts[$key]))
$parse_url[$key] = $parts[$key];
}
}
else
{
// Join the original URL path with the new path
if (isset($parts['path']) && ($flags & HTTP_URL_JOIN_PATH))
{
if (isset($parse_url['path']))
$parse_url['path'] = rtrim(str_replace(basename($parse_url['path']), '', $parse_url['path']), '/') . '/' . ltrim($parts['path'], '/');
else
$parse_url['path'] = $parts['path'];
}
// Join the original query string with the new query string
if (isset($parts['query']) && ($flags & HTTP_URL_JOIN_QUERY))
{
if (isset($parse_url['query']))
$parse_url['query'] .= '&' . $parts['query'];
else
$parse_url['query'] = $parts['query'];
}
}
// Strips all the applicable sections of the URL
// Note: Scheme and Host are never stripped
foreach ($keys as $key)
{
if ($flags & (int)constant('HTTP_URL_STRIP_' . strtoupper($key)))
unset($parse_url[$key]);
}
$new_url = $parse_url;
return
((isset($parse_url['scheme'])) ? $parse_url['scheme'] . '://' : '')
.((isset($parse_url['user'])) ? $parse_url['user'] . ((isset($parse_url['pass'])) ? ':' . $parse_url['pass'] : '') .'@' : '')
.((isset($parse_url['host'])) ? $parse_url['host'] : '')
.((isset($parse_url['port'])) ? ':' . $parse_url['port'] : '')
.((isset($parse_url['path'])) ? $parse_url['path'] : '')
.((isset($parse_url['query'])) ? '?' . $parse_url['query'] : '')
.((isset($parse_url['fragment'])) ? '#' . $parse_url['fragment'] : '')
;
}
}
/**
* Finally, a light, permissions-checking logging class.
*
* Originally written for use with wpSearch
*
* Usage:
* $log = new KLogger('/var/log/', KLogger::INFO );
* $log->logInfo('Returned a million search results'); //Prints to the log file
* $log->logFatal('Oh dear.'); //Prints to the log file
* $log->logDebug('x = 5'); //Prints nothing due to current severity threshhold
*
* @author Kenny Katzgrau <katzgrau@gmail.com>
* @since July 26, 2008
* @link http://codefury.net
* @version 0.1
*/
/**
* Class documentation
*/
class KLogger
{
/**
* Error severity, from low to high. From BSD syslog RFC, secion 4.1.1
* @link http://www.faqs.org/rfcs/rfc3164.html
*/
const EMERG = 0; // Emergency: system is unusable
const ALERT = 1; // Alert: action must be taken immediately
const CRIT = 2; // Critical: critical conditions
const ERR = 3; // Error: error conditions
const WARN = 4; // Warning: warning conditions
const NOTICE = 5; // Notice: normal but significant condition
const INFO = 6; // Informational: informational messages
const DEBUG = 7; // Debug: debug messages
//custom logging level
/**
* Log nothing at all
*/
const OFF = 8;
/**
* Alias for CRIT
* @deprecated
*/
const FATAL = 2;
/**
* Internal status codes
*/
const STATUS_LOG_OPEN = 1;
const STATUS_OPEN_FAILED = 2;
const STATUS_LOG_CLOSED = 3;
/**
* Current status of the log file
* @var integer
*/
private $_logStatus = self::STATUS_LOG_CLOSED;
/**
* Holds messages generated by the class
* @var array
*/
private $_messageQueue = array();
/**
* Path to the log file
* @var string
*/
private $_logFilePath = null;
/**
* Current minimum logging threshold
* @var integer
*/
private $_severityThreshold = self::INFO;
/**
* This holds the file handle for this instance's log file
* @var resource
*/
private $_fileHandle = null;
/**
* Standard messages produced by the class. Can be modified for il8n
* @var array
*/
private $_messages = array(
//'writefail' => 'The file exists, but could not be opened for writing. Check that appropriate permissions have been set.',
'writefail' => 'The file could not be written to. Check that appropriate permissions have been set.',
'opensuccess' => 'The log file was opened successfully.',
'openfail' => 'The file could not be opened. Check permissions.',
);
/**
* Default severity of log messages, if not specified
* @var integer
*/
private static $_defaultSeverity = self::DEBUG;
/**
* Valid PHP date() format string for log timestamps
* @var string
*/
private static $_dateFormat = 'Y-m-d G:i:s';
/**
* Octal notation for default permissions of the log file
* @var integer
*/
private static $_defaultPermissions = 0777;
/**
* Array of KLogger instances, part of Singleton pattern
* @var array
*/
private static $instances = array();
/**
* Partially implements the Singleton pattern. Each $logDirectory gets one
* instance.
*
* @param string $logDirectory File path to the logging directory
* @param integer $severity One of the pre-defined severity constants
* @return KLogger
*/
public static function instance($logDirectory = false, $severity = false)
{
if ($severity === false) {
$severity = self::$_defaultSeverity;
}
if ($logDirectory === false) {
if (count(self::$instances) > 0) {
return current(self::$instances);
} else {
$logDirectory = dirname(__FILE__);
}
}
if (in_array($logDirectory, self::$instances)) {
return self::$instances[$logDirectory];
}
self::$instances[$logDirectory] = new self($logDirectory, $severity);
return self::$instances[$logDirectory];
}
/**
* Class constructor
*
* @param string $logDirectory File path to the logging directory
* @param integer $severity One of the pre-defined severity constants
* @return void
*/
public function __construct($logDirectory, $severity)
{
$logDirectory = rtrim($logDirectory, '\\/');
if ($severity === self::OFF) {
return;
}
$this->_logFilePath = $logDirectory
. DIRECTORY_SEPARATOR
. 'log_'
. date('Y-m-d')
. '.txt';
$this->_severityThreshold = $severity;
if (!file_exists($logDirectory)) {
mkdir($logDirectory, self::$_defaultPermissions, true);
}
if (file_exists($this->_logFilePath) && !is_writable($this->_logFilePath)) {
$this->_logStatus = self::STATUS_OPEN_FAILED;
$this->_messageQueue[] = $this->_messages['writefail'];
return;
}
if (($this->_fileHandle = fopen($this->_logFilePath, 'a'))) {
$this->_logStatus = self::STATUS_LOG_OPEN;
$this->_messageQueue[] = $this->_messages['opensuccess'];
} else {
$this->_logStatus = self::STATUS_OPEN_FAILED;
$this->_messageQueue[] = $this->_messages['openfail'];
}
}
/**
* Class destructor
*/
public function __destruct()
{
if ($this->_fileHandle) {
fclose($this->_fileHandle);
}
}
/**
* Writes a $line to the log with a severity level of DEBUG
*
* @param string $line Information to log
* @return void
*/
public function logDebug($line)
{
$this->log($line, self::DEBUG);
}
/**
* Returns (and removes) the last message from the queue.
* @return string
*/
public function getMessage()
{
return array_pop($this->_messageQueue);
}
/**
* Returns the entire message queue (leaving it intact)
* @return array
*/
public function getMessages()
{
return $this->_messageQueue;
}
/**
* Empties the message queue
* @return void
*/
public function clearMessages()
{
$this->_messageQueue = array();
}
/**
* Sets the date format used by all instances of KLogger
*
* @param string $dateFormat Valid format string for date()
*/
public static function setDateFormat($dateFormat)
{
self::$_dateFormat = $dateFormat;
}
/**
* Writes a $line to the log with a severity level of INFO. Any information
* can be used here, or it could be used with E_STRICT errors
*
* @param string $line Information to log
* @return void
*/
public function logInfo($line)
{
$this->log($line, self::INFO);
}
/**
* Writes a $line to the log with a severity level of NOTICE. Generally
* corresponds to E_STRICT, E_NOTICE, or E_USER_NOTICE errors
*
* @param string $line Information to log
* @return void
*/
public function logNotice($line)
{
$this->log($line, self::NOTICE);
}
/**
* Writes a $line to the log with a severity level of WARN. Generally
* corresponds to E_WARNING, E_USER_WARNING, E_CORE_WARNING, or
* E_COMPILE_WARNING
*
* @param string $line Information to log
* @return void
*/
public function logWarn($line)
{
$this->log($line, self::WARN);
}
/**
* Writes a $line to the log with a severity level of ERR. Most likely used
* with E_RECOVERABLE_ERROR
*
* @param string $line Information to log
* @return void
*/
public function logError($line)
{
$this->log($line, self::ERR);
}
/**
* Writes a $line to the log with a severity level of FATAL. Generally
* corresponds to E_ERROR, E_USER_ERROR, E_CORE_ERROR, or E_COMPILE_ERROR
*
* @param string $line Information to log
* @return void
* @deprecated Use logCrit
*/
public function logFatal($line)
{
$this->log($line, self::FATAL);
}
/**
* Writes a $line to the log with a severity level of ALERT.
*
* @param string $line Information to log
* @return void
*/
public function logAlert($line)
{
$this->log($line, self::ALERT);
}
/**
* Writes a $line to the log with a severity level of CRIT.
*
* @param string $line Information to log
* @return void
*/
public function logCrit($line)
{
$this->log($line, self::CRIT);
}
/**
* Writes a $line to the log with a severity level of EMERG.
*
* @param string $line Information to log
* @return void
*/
public function logEmerg($line)
{
$this->log($line, self::EMERG);
}
/**
* Writes a $line to the log with the given severity
*
* @param string $line Text to add to the log
* @param integer $severity Severity level of log message (use constants)
*/
public function log($line, $severity)
{
if ($this->_severityThreshold >= $severity) {
$status = $this->_getTimeLine($severity);
$this->writeFreeFormLine("$status $line \n");
}
}
/**
* Writes a line to the log without prepending a status or timestamp
*
* @param string $line Line to write to the log
* @return void
*/
public function writeFreeFormLine($line)
{
if ($this->_logStatus == self::STATUS_LOG_OPEN
&& $this->_severityThreshold != self::OFF) {
if (fwrite($this->_fileHandle, $line) === false) {
$this->_messageQueue[] = $this->_messages['writefail'];
}
}
}
private function _getTimeLine($level)
{
$time = date(self::$_dateFormat);
switch ($level) {
case self::EMERG:
return "$time - EMERG -->";
case self::ALERT:
return "$time - ALERT -->";
case self::CRIT:
return "$time - CRIT -->";
case self::FATAL: # FATAL is an alias of CRIT
return "$time - FATAL -->";
case self::NOTICE:
return "$time - NOTICE -->";
case self::INFO:
return "$time - INFO -->";
case self::WARN:
return "$time - WARN -->";
case self::DEBUG:
return "$time - DEBUG -->";
case self::ERR:
return "$time - ERROR -->";
default:
return "$time - LOG -->";
}
}
}
?>