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