]> git.datanom.net - qtadmin.git/blob - lib/utils.inc.php
add more debug info
[qtadmin.git] / lib / utils.inc.php
1 <?php
2 /* vim: set ts=4 tw=0 sw=4 noet: */
3 require_once $CFG->root .'config.php';
4 require_once $CFG->root . 'lib/session_handler.inc.php';
5
6 class Utils {
7
8 private $timeout = false;
9 private $settings;
10 private $log_level;
11 private $log_method;
12 private $header = '<!DOCTYPE html>
13 <html>
14 <head>
15 <meta charset="utf-8">
16 <link rel="stylesheet" href="css/styles.css">
17 <script>
18 var timeout = __TIMEOUT__;
19 </script>
20 <script src="__ROOT__js/timer.js"></script>
21 <script src="__ROOT__js/checkbox.js"></script>
22 <script src="__ROOT__js/forms.js"></script>
23 <title>__TITLE__</title>
24 </head>
25 <body>
26 <!--
27 <nav>
28 <ul>
29 <li><a href="index.php">Home</a></li>
30 <li>
31 <a href="#">Sections <span class="caret"></span></a>
32 <div>
33 <ul>
34 <li><a href="qtadmin.php">Quarantine admin</a></li>
35 <li><a href="wblist.php">WB list admin</a></li>
36 </ul>
37 </div>
38 </li>
39 <li><a href="about.html">About</a></li>
40 <li><a href="auth.php?op=logout">Logout</a></li>
41 </ul>
42 </nav>
43 -->
44 <nav>
45 <ul>
46 <li><a href="index.php">Home</a></li>
47 <li>
48 <a href="#">Sections <span class="caret"></span></a>
49 <div>
50 <ul>
51 <li>
52 <a href="qtadmin.php">Quarantine admin</span></a>
53 </li>
54 <li><a href="#">WB list admin <span class="caret"></a>
55 <div>
56 <ul>
57 <li><a href="wblist.php?p=show&amp;s=all">Show All</a></li>
58 <li><a href="wblist.php?p=show&amp;s=blacklist">Show Blacklist</a></li>
59 <li><a href="wblist.php?p=show&amp;s=whitelist">Show Whitelist</a></li>
60 <li><a href="wblist.php?p=add">Add Rule</a></li>
61 <li><a href="wblist.php?p=del">Delete Rule</a></li>
62 </ul>
63 </div>
64 </li>
65 </ul>
66 </div>
67 </li>
68 <li><a href="about.html">About</a></li>
69 <li><a href="auth.php?op=logout">Logout</a></li>
70 </ul>
71 </nav>
72 <div id="container">';
73 private $footer = '</div><div id="footer"><p>Powered by <a href="https://qtadmin.datanom.net"
74 title="Goto QtAdmin homepage">QtAdmin</a>. &copy; 2015 by Michael Rasmussen</p>
75 </div></body></html>';
76 private $heading = '<p id="time" class="time">Session timeout:
77 <span id="timer"></span></p><h1 class="h1">__TITLE__</h1>';
78
79 public function __construct() {
80 global $CFG;
81
82 if (isset($CFG->log_level)) {
83 $this->log_level = $CFG->log_level;
84 } else {
85 $this->log_level = 1;
86 }
87
88 if (isset($CFG->log_method)) {
89 $this->log_method = $CFG->log_method;
90 } else {
91 $this->log_level = 'syslog';
92 }
93
94 $this->log("Init Utils", 4);
95
96 $this->log("__construct[1]: user ".var_export($this->settings['user'], true), 3);
97 $this->startSession();
98 $this->log("__construct[2]: user ".var_export($this->settings['user'], true), 3);
99
100 if (! isset($_SESSION['settings'])) {
101 $this->initSettings();
102 }
103 $this->log("__construct[3]: user ".var_export($this->settings['user'], true), 3);
104 $this->settings = $_SESSION['settings'];
105 $this->log("__construct[4]: user ".var_export($this->settings['user'], true), 3);
106
107 if ($CFG->auth_method == 'HTTP_AUTH') {
108 if (isset($_SERVER['PHP_AUTH_USER'])) {
109 $this->settings['user'] = $_SERVER['PHP_AUTH_USER'];
110 $this->settings['loginStatus'] = 'OK';
111 if ($CFG->admin_user == $this->settings['user'])
112 $this->settings['admin'] = true;
113 }
114 }
115 }
116
117 private function log($message, $level = 1) {
118 global $CFG;
119
120 if ($level > $this->log_level)
121 return;
122
123 $time = date('c');
124
125 $priority = LOG_INFO;
126 switch ($level) {
127 case 1: $priority = LOG_ERR; break;
128 case 2: $priority = LOG_WARNING; break;
129 case 3: $priority = LOG_INFO; break;
130 case 4: $priority = LOG_DEBUG; break;
131 }
132
133 switch ($this->log_method) {
134 case 'file':
135 if (isset($CFG->log_file)) {
136 if ($CFG->log_file[0] == '/') {
137 $file = $CFG->log_file;
138 } else {
139 $file = $CFG->root.$CFG->log_file;
140 }
141 } else {
142 $file = $CFG->root.'qtadmin.log';
143 }
144 file_put_contents($file, "[$time]: $message\n", FILE_APPEND | LOCK_EX);
145 chmod($file, 0600);
146 break;
147 case 'stderr':
148 file_put_contents('php://stderr', "[$time]: $message\n");
149 break;
150 case 'syslog':
151 syslog($priority, $message);
152 break;
153 }
154 }
155
156 private function initSettings() {
157 $this->log("InitSettings", 4);
158
159 if ('' == session_id()) {
160 $this->startSession();
161 }
162
163 if (false !== $this->timeout) {
164 $timeout = $this->timeout;
165 } else {
166 $timeout = 0;
167 }
168
169 $this->settings = array(
170 'user' => null,
171 'admin' => false,
172 'loginStatus' => 'Not logged in',
173 'timeout' => $timeout
174 );
175
176 $_SESSION['settings'] = $this->settings;
177 }
178
179 private function startSession() {
180 global $CFG;
181
182 $this->log("startSession", 4);
183
184 if (isset($CFG->session_timeout)) {
185 $this->timeout = $CFG->session_timeout * 60;
186 } else {
187 $this->timeout = 20 * 60;
188 }
189
190 if (ini_get('session.gc_maxlifetime') != $this->timeout)
191 ini_set('session.gc_maxlifetime', $this->timeout);
192 //if (ini_get('session.cookie_lifetime') != $this->timeout)
193 // ini_set('session.cookie_lifetime', $this->timeout);
194 ini_set('session.cookie_lifetime', 0);
195
196 session_start();
197 }
198
199 private function checkSession() {
200 global $CFG;
201
202 $this->log("checkSession", 4);
203
204 if ('' == session_id()) {
205 $this->startSession();
206 }
207
208 $time = $_SERVER['REQUEST_TIME'];
209 if (isset($_SESSION['LAST_ACTIVITY']) &&
210 ($time - $_SESSION['LAST_ACTIVITY']) >= $this->settings['timeout']) {
211 $this->log('R_TIME: '.date('c', $time).' L_ACT: '.date('c', $_SESSION['LAST_ACTIVITY'].
212 'Test: '.($time - $_SESSION['LAST_ACTIVITY'])).' >= '.$this->settings['timeout'], 3);
213 $this->logout();
214 } else {
215 $_SESSION['LAST_ACTIVITY'] = $time;
216 }
217 }
218
219 private function getCSRFPreventionToken($ticket) {
220 return array('CSRFPreventionToken: ' . $ticket->CSRFPreventionToken);
221 }
222
223 private function getRestTicket($username, $password) {
224 global $CFG;
225
226 $result = false;
227 $url = $CFG->wblistadm_url . '/ticket';
228
229 $data = "username=$username&password=$password";
230 $response = $this->RESTCall($url, $data, $cookiesIn = '');
231 if ($response['http_code'] >= 200 && $response['http_code'] <= 204) {
232 $data = json_decode($response['content']);
233 $_SESSION['ticket'] = $data->data;
234 $_SESSION['cookies'] = $response['cookies'];
235 $result = true;
236 }
237
238 return $result;
239 }
240
241 public function makeRestCall($method, $data = null) {
242 global $CFG;
243
244 $result;
245
246 $url = $CFG->wblistadm_url . "$method";
247 $token = $this->getCSRFPreventionToken($_SESSION['ticket']);
248 $response = $this->RESTCall($url, $data, $_SESSION['cookies'], $token);
249
250 if ($response['http_code'] >= 200 && $response['http_code'] <= 204) {
251 if ($data) {
252 // HTTP POST
253 $result = true;
254 } else {
255 // HTTP GET
256 $data = json_decode($response['content']);
257 if (is_object($data)) {
258 $result = $data->data;
259 } else {
260 $result = array('No result');
261 }
262 }
263 } else {
264 $result = ($data) ? false : array();
265 }
266
267 return $result;
268 }
269
270 private function RESTCall($url, $data = null, $cookiesIn = '', $headers = null) {
271 $options = array(
272 CURLOPT_RETURNTRANSFER => true, // return web page
273 CURLOPT_HEADER => true, //return headers in addition to content
274 CURLOPT_FOLLOWLOCATION => true, // follow redirects
275 CURLOPT_ENCODING => "", // handle all encodings
276 CURLOPT_AUTOREFERER => true, // set referer on redirect
277 CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
278 CURLOPT_TIMEOUT => 120, // timeout on response
279 CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
280 CURLINFO_HEADER_OUT => true,
281 CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
282 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
283 CURLOPT_COOKIE => $cookiesIn
284 );
285
286 if ($data) {
287 $options[CURLOPT_POST] = 1;
288 $options[CURLOPT_POSTFIELDS] = $data;
289 }
290
291 if ($headers) {
292 $options[CURLOPT_HTTPHEADER] = $headers;
293 }
294
295 $ch = curl_init($url);
296 curl_setopt_array($ch, $options);
297 $rough_content = curl_exec($ch);
298 $err = curl_errno($ch);
299 $errmsg = curl_error($ch);
300 $header = curl_getinfo($ch);
301 curl_close($ch);
302
303 $header_content = substr($rough_content, 0, $header['header_size']);
304 $body_content = trim(str_replace($header_content, '', $rough_content));
305 $pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
306 preg_match_all($pattern, $header_content, $matches);
307 $cookiesOut = implode("; ", $matches['cookie']);
308
309 $header['errno'] = $err;
310 $header['errmsg'] = $errmsg;
311 $header['headers'] = $header_content;
312 $header['content'] = $body_content;
313 $header['cookies'] = $cookiesOut;
314
315 return $header;
316 }
317
318 public function logout() {
319 $this->log("logout", 4);
320
321 if (ini_get('session.use_cookies')) {
322 $params = session_get_cookie_params();
323 setcookie(session_name(), '', time() - 42000,
324 $params['path'], $params['domain'],
325 $params['secure'], $params['httponly']);
326 }
327
328 if ('' != session_id()) {
329 $_SESSION = array();
330 session_unset();
331 session_destroy();
332 }
333 $this->settings = array();
334 }
335
336 public function isAdmin() {
337 $admin = false;
338
339 $this->log("isAdmin", 4);
340
341 if (isset($this->settings['admin'])) {
342 $admin = $this->settings['admin'];
343 }
344
345 return $admin;
346 }
347
348 public function login($user, $pw) {
349 global $CFG;
350 $result = false;
351
352 $this->log("login", 4);
353
354 if ('' == session_id()) {
355 $this->startSession();
356 }
357
358 $this->settings['user'] = null;
359 $this->settings['admin'] = false;
360
361 $p = explode('@', $user);
362 if (count($p) != 2) {
363 $this->settings['loginStatus'] = 'Bad username';
364 } else {
365 $domain = $p[1];
366 $dn = "mail=$user,ou=Users,domainName=$domain,$CFG->ldap_base_dn";
367 $this->log('dn: '.var_export($dn, true), 4);
368 $filter = "(&(objectclass=mailUser)(accountStatus=active)(mail=$user))";
369 $this->log('filter: '.var_export($filter, true), 4);
370 $ds = @ldap_connect($CFG->ldap_dsn);
371 if ($ds) {
372 @ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
373 $r = @ldap_bind($ds, $dn, $pw);
374 if ($r) {
375 $sr = @ldap_search($ds, $CFG->ldap_base_dn, $filter, array('mail','domainglobaladmin'));
376 $this->log('sr: '.var_export($sr, true), 4);
377 $info = @ldap_get_entries($ds, $sr); // array
378 $this->log('info: '.var_export($info, true), 4);
379 if ($info['count'] > 0) {
380 // Log in to wblistadm server and get CSRFPreventionToken
381 if ($this->getRestTicket($user, $pw)) {
382 $this->settings['user'] = $user;
383 $result = true;
384 $this->settings['loginStatus'] = 'OK';
385 $admin = 'NO';
386 if (isset($info[0]['domainglobaladmin'])) {
387 $admin = $info[0]['domainglobaladmin'][0];
388 $admin = strtoupper($admin);
389 }
390 $this->settings['admin'] = ($admin == 'YES') ? true : false;
391 } else {
392 $this->settings['loginStatus'] = 'Login to wblistadm REST server failed';
393 }
394 } else {
395 $this->settings['loginStatus'] = 'Login failed';
396 }
397 } else {
398 $this->settings['loginStatus'] = ldap_error($ds);
399 }
400 @ldap_close($ds);
401 } else {
402 $this->settings['loginStatus'] = 'Connect to LDAP server failed';
403 }
404 }
405
406 $_SESSION['settings'] = $this->settings;
407
408 return $result;
409 }
410
411 public function getLoginStatus() {
412 $status = 'Not logged in';
413
414 $this->log("getLoginStatus", 4);
415
416 if (isset($this->settings['loginStatus'])) {
417 $status = $this->settings['loginStatus'];
418 }
419
420 return $status;
421 }
422
423 public function isLoggedIn() {
424 global $CFG;
425 $loggedIn = false;
426
427 $this->log("isLoggedIn[1]: user ".var_export($this->settings['user'], true), 3);
428
429 if ('' == session_id()) {
430 $this->startSession();
431 }
432
433 $this->log("isLoggedIn[2]: user ".var_export($this->settings['user'], true), 3);
434 $this->checkSession();
435 $this->log("isLoggedIn[3]: user ".var_export($this->settings['user'], true), 3);
436
437 if (isset($this->settings['user'])) {
438 if ($this->settings['user'] != null) {
439 $loggedIn = true;
440 } else {
441 if ($CFG->auth_method == 'HTTP_AUTH') {
442 if (isset($_SERVER['PHP_AUTH_USER'])) {
443 $this->settings['user'] = $_SERVER['PHP_AUTH_USER'];
444 $loggedIn = true;
445 }
446 }
447 }
448 }
449
450 if ($loggedIn == false) {
451 $this->log('$this->settings: '.var_export($this->settings, true), 3);
452 $this->log('R_TIME: '.date('c', $_SERVER['REQUEST_TIME']).' L_ACT: '.date('c', $_SESSION['LAST_ACTIVITY']), 3);
453 }
454
455 $_SESSION['settings'] = $this->settings;
456
457 return $loggedIn;
458 }
459
460 public function getUser() {
461 $user = null;
462
463 $this->log("getUser", 4);
464
465 if ($this->isLoggedIn()) {
466 $user = $this->settings['user'];
467 }
468
469 return $user;
470 }
471
472 public function authorized($recipient) {
473 $authorized = false;
474
475 $this->log("authorized '$recipient'", 3);
476
477 if ($this->isAdmin() || $this->getUser() == $recipient) {
478 $authorized = true;
479 }
480 $msg = ($authorized) ? 'authorize' : 'not authorize';
481 $this->log("$msg '".$this->getUser()."' rcpt '$recipient'", 3);
482
483 return $authorized;
484 }
485
486 public function getHeader() {
487 $this->log("getHeader", 4);
488
489 return $this->header;
490 }
491
492 public function getFooter() {
493 $this->log("getFooter", 4);
494
495 return $this->footer;
496 }
497
498 public function getHeading() {
499 $this->log("getHeading", 4);
500
501 return $this->heading;
502 }
503
504 public function setHeading($heading) {
505 global $CFG;
506
507 $this->log("setHeading", 4);
508
509 $timeout = $CFG->session_timeout * 60 * 1000;
510 $this->heading = str_replace('__TITLE__', $heading, $this->heading);
511 $this->header = str_replace('__TITLE__', $heading, $this->header);
512 $this->header = str_replace('__ROOT__', $CFG->wwwroot, $this->header);
513 $this->header = str_replace('__TIMEOUT__', $timeout, $this->header);
514 }
515
516 public function convertContent($code) {
517 $this->log("convertContent", 4);
518
519 $table = array(
520 'V' => 'Virus',
521 'B' => 'Banned',
522 'U' => 'Unchecked',
523 'S' => 'Spam',
524 'Y' => 'Spammy',
525 'M' => 'Bad Mime',
526 'H' => 'Bad Header',
527 'O' => 'Over sized',
528 'T' => 'MTA err',
529 'C' => 'Clean'
530 );
531
532 $string = $table[$code];
533 if (empty($string))
534 $string = 'Unknown';
535
536 return $string;
537 }
538
539 }
This page took 0.126394 seconds and 6 git commands to generate.