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