]> git.mxchange.org Git - ctracker.git/blob - libs/lib_general.php
Also block request methods such as CONNECT as they can be used for proxying
[ctracker.git] / libs / lib_general.php
1 <?php
2 /**
3  * General functions library
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             3.0.0
7  * @copyright   Copyright (c) 2009 - 2011 Cracker Tracker Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24
25 if (!function_exists('implode_r')) {
26         // Implode recursive a multi-dimension array, taken from www.php.net
27         function implode_r ($glue, $array, $array_name = NULL) {
28                 $return = array();
29                 while(list($key,$value) = @each($array)) {
30                         if(is_array($value)) {
31                                 // Is an array again, so call recursive
32                                 $return[] = implode_r($glue, $value, (string) $key);
33                         } else {
34                                 if($array_name != NULL) {
35                                         $return[] = $array_name . '[' . (string) $key . ']=' . $value . "\n";
36                                 } else {
37                                         $return[] = $key . '=' . $value."\n";
38                                 }
39                         }
40                 } // END - while
41
42                 // Return resulting array
43                 return(implode($glue, $return));
44         } // END - function
45 } // END - if
46
47 if (!function_exists('implode_secure')) {
48         // Implode a simple array with a 'call-back' to our escaper function
49         function implode_secure ($array) {
50                 // Return string
51                 $return = '';
52
53                 // Implode all data
54                 foreach ($array as $entry) {
55                         // Don't escape some
56                         if (in_array($entry, array('NOW()'))) {
57                                 // Add it with non-string glue
58                                 $return .= $entry . ',';
59                         } elseif (empty($entry)) {
60                                 // Empty strings need no escaping
61                                 $return .= '"",';
62                         } else {
63                                 // Secure this string and add it
64                                 $return .= '"' . crackerTrackerEscapeString($entry) . '",';
65                         }
66                 } // END - foreach
67
68                 // Remove last char
69                 $return = substr($return, 0, -1);
70
71                 // Return this string
72                 return $return;
73         } // END - function
74 } // END - if
75
76 // Load configuration, if found
77 function crackerTrackerLoadConfiguration () {
78         // FQFN
79         $fqfn = sprintf('%s/config/db_config.php', $GLOBALS['ctracker_base_path']);
80
81         // Is the file readable?
82         if (!isCrackerTrackerFileFound($fqfn)) {
83                 // No config file found
84                 die(__FUNCTION__.': No configuration file found.');
85         } // END - if
86
87         // Load it
88         require($fqfn);
89
90         // Load email header
91         $GLOBALS['ctracker_header'] = crackerTrackerLoadEmailTemplate('header');
92 }
93
94 // Getter for ctracker_debug_enabled
95 function isCrackerTrackerDebug () {
96         // Is it set?
97         $result = ((isset($GLOBALS['ctracker_debug_enabled'])) && ($GLOBALS['ctracker_debug_enabled'] === TRUE));
98
99         // Debug message
100         //* DEBUG: */ error_log('result=' . intval($result));
101
102         // Return it
103         return $result;
104 }
105
106 // Determines the real remote address
107 function determineCrackerTrackerRealRemoteAddress () {
108         // Initial value
109         $address = '0.0.0.0';
110
111         // Is a proxy in use?
112         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
113                 // Proxy was used
114                 $address = trim($_SERVER['HTTP_X_FORWARDED_FOR']);
115         } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
116                 // Yet, another proxy
117                 $address = trim($_SERVER['HTTP_CLIENT_IP']);
118         } elseif (isset($_SERVER['REMOTE_ADDR'])) {
119                 // The regular address when no proxy was used
120                 $address = trim(getenv('REMOTE_ADDR'));
121         }
122
123         if ($address == 'unknown') {
124                 // Invalid IP somehow given
125                 $address = '0.0.0.0';
126         } elseif (strstr($address, ',')) {
127                 // This strips out the real address from proxy output
128                 $addressArray = explode(',', $address);
129                 $address = $addressArray[0];
130         }
131
132         // Return the result
133         return $address;
134 }
135
136 // Determine if a proxy was used
137 function isCrackerTrackerProxyUsed () {
138         // Check if specific entries are set
139         $proxyUsed = ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) || (isset($_SERVER['HTTP_CLIENT_IP'])));
140
141         // Return result
142         return $proxyUsed;
143 }
144
145 // Detects the user-agent string
146 function crackerTrackerUserAgent ($sanitize = FALSE) {
147         // Default is 'unknown'
148         $ua = 'unknown';
149
150         // Is the entry there?
151         if (isset($_SERVER['HTTP_USER_AGENT'])) {
152                 // Then use it securely
153                 $ua = crackerTrackerSecureString(urldecode($_SERVER['HTTP_USER_AGENT']));
154         } // END - if
155
156         // Sanitize it?
157         if ($sanitize === TRUE) {
158                 // Sanitize ...
159                 $ua = crackerTrackerSanitize($ua);
160         } // END - if
161
162         // Return it
163         return $ua;
164 }
165
166 // Detects the script name
167 function crackerTrackerScriptName ($sanitize = FALSE) {
168         // Default is NULL
169         $scriptName = NULL;
170
171         // Is it there?
172         if (!empty($_SERVER['SCRIPT_NAME'])) {
173                 // Return NULL
174                 $scriptName = crackerTrackerSecureString($_SERVER['SCRIPT_NAME']);
175         } // END - if
176
177         // Sanitize it?
178         if ($sanitize === TRUE) {
179                 // Sanitize ...
180                 $scriptName = crackerTrackerSanitize($scriptName);
181         } // END - if
182
183         // Return
184         return $scriptName;
185 }
186
187 // Detects the query string
188 function crackerTrackerQueryString ($sanitize = FALSE) {
189         // Default is NULL
190         $query = NULL;
191
192         // Is it there?
193         if (!empty($_SERVER['QUERY_STRING'])) {
194                 // Return NULL
195                 $query = crackerTrackerEscapeString(urldecode($_SERVER['QUERY_STRING']));
196         } // END - if
197
198         // Sanitize it?
199         if ($sanitize === TRUE) {
200                 // Sanitize ...
201                 $query = crackerTrackerSanitize($query);
202         } // END - if
203
204         // Return it
205         return $query;
206 }
207
208 // Detects the server's name
209 function crackerTrackerServerName ($sanitize = FALSE) {
210         // Default is NULL
211         $serverName = NULL;
212
213         // Is it there?
214         if (!empty($_SERVER['SERVER_NAME'])) {
215                 // Return NULL
216                 $serverName = crackerTrackerSecureString($_SERVER['SERVER_NAME']);
217         } // END - if
218
219         // Sanitize it?
220         if ($sanitize === TRUE) {
221                 // Sanitize ...
222                 $serverName = crackerTrackerSanitize($serverName);
223         } // END - if
224
225         // Return it
226         return $serverName;
227 }
228
229 // Detects the referer
230 function crackerTrackerReferer ($sanitize = FALSE) {
231         // Default is a dash
232         $referer = '-';
233
234         // Is it there?
235         if (!empty($_SERVER['HTTP_REFERER'])) {
236                 // Then use it securely
237                 $referer = crackerTrackerSecureString(urldecode($_SERVER['HTTP_REFERER']));
238         } // END - if
239
240         // Sanitize it?
241         if ($sanitize === TRUE) {
242                 // Sanitize ...
243                 $referer = crackerTrackerSanitize($referer);
244         } // END - if
245
246         // Return it
247         return $referer;
248 }
249
250 // Detects request method
251 function crackerTrackerRequestMethod () {
252         // Default is NULL
253         $method = NULL;
254
255         // Is it set?
256         if (!empty($_SERVER['REQUEST_METHOD'])) {
257                 // Then use it
258                 $method = $_SERVER['REQUEST_METHOD'];
259         } // END - if
260
261         // Return it
262         return $method;
263 }
264
265 // Detects the scripts path
266 function crackerTrackerScriptPath () {
267         // Should always be there!
268         $path = dirname(crackerTrackerScriptName()) . '/';
269
270         // Return detected path
271         return $path;
272 }
273
274 // Detects wether we have SSL
275 function crackerTrackerSecured () {
276         // Detect it
277         $ssl = ((isset($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != 'off'));
278
279         // Return result
280         return $ssl;
281 }
282
283 // Secures a string by escaping it and passing it through strip_tags,htmlentities-chain
284 function crackerTrackerSecureString ($str) {
285         // First escape it
286         $str = crackerTrackerEscapeString($str);
287
288         // Then pass it through the functions
289         $str = htmlentities(strip_tags($str), ENT_QUOTES);
290
291         // Return it
292         return $str;
293 }
294
295 // Is the file there and readable?
296 function isCrackerTrackerFileFound ($FQFN) {
297         // Simply check it
298         return ((file_exists($FQFN)) && (is_readable($FQFN)));
299 }
300
301 // Loads a given "template" (this is more an include file)
302 function crackerTrackerLoadTemplate ($template) {
303         // Create the full-qualified filename (FQFN)
304         $FQFN = sprintf('%s/libs/templates/%s.tpl.php',
305                 $GLOBALS['ctracker_base_path'],
306                 $template
307         );
308
309         // Is this template found?
310         if (isCrackerTrackerFileFound($FQFN)) {
311                 // Detect language
312                 crackerTrackerLanguage();
313
314                 // Load it
315                 require_once($FQFN);
316         } else {
317                 // Not found, so die here
318                 crackerTrackerDie();
319         }
320 }
321
322 // Loads a given "template" (this is more an include file)
323 function crackerTrackerLoadLocalizedTemplate ($template) {
324         // Create the full-qualified filename (FQFN)
325         $FQFN = sprintf('%s/libs/templates/%s/%s.tpl.php',
326                 $GLOBALS['ctracker_base_path'],
327                 getCrackerTrackerLanguage(),
328                 $template
329         );
330
331         // Is this template found?
332         if (isCrackerTrackerFileFound($FQFN)) {
333                 // Load it
334                 require_once($FQFN);
335         } else {
336                 // Not found, so die here
337                 crackerTrackerDie();
338         }
339 }
340
341 // Detects the browser's language file and tries to load it, fall-back on english!
342 function crackerTrackerLanguage () {
343         // Default is English
344         $GLOBALS['ctracker_language'] = 'en';
345         $weight = 1;
346
347         // Is the language string there?
348         if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
349                 // Then detect it
350                 foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
351                         // Split it again for q=x.x value
352                         $langArray = explode(';', $lang);
353
354                         // If there is an entry, we have a weight
355                         if ((isset($langArray[1])) && ($langArray[1] > $weight)) {
356                                 // Use this language/weight instead
357                                 $GLOBALS['ctracker_language'] = $langArray[0];
358                                 $weight   = $langArray[1];
359                         } // END - if
360                 } // END - foreach
361         } // END - if
362
363         // Construct FQFN
364         $FQFN = sprintf('%s/libs/language/%s.php',
365                 $GLOBALS['ctracker_base_path'],
366                 getCrackerTrackerLanguage()
367         );
368
369         // Is it not there, switch to "en"
370         if ((getCrackerTrackerLanguage() != 'en') && (!isCrackerTrackerFileFound($FQFN))) {
371                 // English is default!
372                 $GLOBALS['ctracker_language'] = 'en';
373
374                 // Construct FQFN again
375                 $FQFN = sprintf('%s/libs/language/en.php', $GLOBALS['ctracker_base_path']);
376         } // END - if
377
378         // Load the language file
379         require($FQFN);
380 }
381
382 // Loads a given email template and passes through $content
383 function crackerTrackerLoadEmailTemplate ($template, array $content = array(), $language = NULL) {
384         // Init language
385         crackerTrackerLanguage();
386
387         // Generate the FQFN
388         $FQFN = sprintf('%s/libs/mails/%s/%s.tpl',
389                 $GLOBALS['ctracker_base_path'],
390                 getCrackerTrackerLanguage($language),
391                 $template
392         );
393
394         // So is the file there?
395         if (isCrackerTrackerFileFound($FQFN)) {
396                 // Init result
397                 $result = 'No result from template ' . $template . '. Please report this at http://forum.shipsimu.org Thank you.';
398
399                 // Then load it
400                 //* DEBUG-DIE: */ die('<pre>$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";</pre>');
401                 eval('$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";');
402
403                 // Return the result
404                 return $result;
405         } else {
406                 // Not found
407                 crackerTrackerDie();
408         }
409 }
410
411 // Getter for message
412 function getCrackerTrackerLocalized ($message) {
413         // Default message
414         $output = '!' . $message . '!';
415
416         // Is the language string there?
417         if (isset($GLOBALS['ctracker_localized'][$message])) {
418                 // Use this instead
419                 $output = $GLOBALS['ctracker_localized'][$message];
420         } // END - if
421
422         // Return it
423         return $output;
424 }
425
426 // Tries to find a message and outputs it
427 function crackerTrackerOutputLocalized ($message) {
428         // Output it
429         print getCrackerTrackerLocalized($message);
430 }
431
432 // Compiles the given code
433 function crackerTrackerCompileCode ($code) {
434         // Find all $content[foo]
435         preg_match_all('/\$(content|GLOBALS)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
436
437         // Replace " with {QUOTE}
438         $code = str_replace('"', '{QUOTE}', $code);
439
440         // Replace all
441         foreach ($matches[0] as $key=>$match) {
442                 // Replace it
443                 if (substr($match, 0, 8) == '$GLOBALS') {
444                         // $GLOBALS
445                         $code = str_replace($match, "\" . \$GLOBALS['" . $matches[4][$key] . "'] . \"", $code);
446                 } elseif (substr($match, 0, 8) == '$content') {
447                         // $content
448                         $code = str_replace($match, "\" . \$content['" . $matches[4][$key] . "'] . \"", $code);
449                 }
450         } // END - foreach
451
452         // Return it
453         return $code;
454 }
455
456 // "Getter" for language
457 function getCrackerTrackerLanguage ($lang = NULL) {
458         // Default is from browser
459         $language = $GLOBALS['ctracker_language'];
460
461         // Is $lang set?
462         if (!is_null($lang)) {
463                 // Then use this instead
464                 $language = $lang;
465         } // END - if
466
467         // Return it
468         return $language;
469 }
470
471 // "Getter" for ticket id
472 function getCrackerTrackerTicketId () {
473         // Default is zero
474         $id = 0;
475
476         // Is it set?
477         if (isset($GLOBALS['ctracker_last_ticket']['ctracker_ticket'])) {
478                 // Then use it
479                 $id = $GLOBALS['ctracker_last_ticket']['ctracker_ticket'];
480         } // END - if
481
482         // Return the number
483         return $id;
484 }
485
486 // Sends a cookie to the user that he would not see this security warning again
487 function sendCrackerTrackerCookie () {
488         // Set the cookie
489         // @TODO Why can't domain be set to value from crackerTrackerServerName() ?
490         setcookie('ctracker_ticket', getCrackerTrackerTicketId(), (time() + 60*60*24), '/', '', crackerTrackerSecured(), TRUE);
491         $_COOKIE['ctracker_ticket'] = getCrackerTrackerTicketId();
492 }
493
494 // Is the cookie set?
495 function ifCrackerTrackerCookieIsSet () {
496         // Is it set and valid?
497         return ((isset($_COOKIE['ctracker_ticket'])) && ($_COOKIE['ctracker_ticket'] > 0));
498 }
499
500 // Redirects to the same URL
501 function crackerTrackerRedirectSameUrl () {
502         // Construct the url
503         $url = '://' . crackerTrackerServerName() . crackerTrackerScriptName() . '?' . crackerTrackerQueryString();
504
505         // Do we have SSL?
506         if (crackerTrackerSecured()) {
507                 // HTTPS
508                 $url = 'https' . $url;
509         } else {
510                 // HTTP
511                 $url = 'http' . $url;
512         }
513
514         // And redirect
515         crackerTrackerSendRawRedirect($url);
516 }
517
518 /**
519  * Send a HTTP redirect to the browser. This function was taken from DokuWiki
520  * (GNU GPL 2; http://www.dokuwiki.org) and modified to fit into this script.
521  *
522  * Works arround Microsoft IIS cookie sending bug. Does exit the script.
523  *
524  * @link    http://support.microsoft.com/kb/q176113/
525  * @author  Andreas Gohr <andi@splitbrain.org>
526  * @access  private
527  */
528 function crackerTrackerSendRawRedirect ($url) {
529         // Better remove any data by ctracker
530         unsetCtrackerData();
531
532         // always close the session
533         session_write_close();
534
535         // Revert entity &amp;
536         $url = str_replace('&amp;', '&', $url);
537
538         // check if running on IIS < 6 with CGI-PHP
539         if ((isset($_SERVER['SERVER_SOFTWARE'])) && (isset($_SERVER['GATEWAY_INTERFACE'])) &&
540                 (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== FALSE) &&
541                 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
542                 ($matches[1] < 6)) {
543                 // Send the IIS header
544                 header('Refresh: 0;url=' . $url);
545         } else {
546                 // Send generic header
547                 header('Location: ' . $url);
548         }
549         exit();
550 }
551
552 // Removes all ctracker-related data from global space
553 function unsetCtrackerData () {
554         // Debug message
555         //* DEBUG: */ error_log(__FUNCTION__ . ': CALLED!');
556
557         // Unset all ctracker data
558         foreach (array(
559                         'ctracker_base_path',
560                         'ctracker_host',
561                         'ctracker_dbname',
562                         'ctracker_user',
563                         'ctracker_password',
564                         'ctracker_debug_enabled',
565                         'ctracker_email',
566                         'ctracker_whitelist',
567                         'ctracker_get_blacklist',
568                         'ctracker_post_blacklist',
569                         'ctracker_header',
570                         'ctracker_post_track',
571                         'ctracker_checked_get',
572                         'ctracker_checked_post',
573                         'ctracker_checked_ua',
574                         'ctracker_last_sql',
575                         'ctracker_last_result',
576                         'ctracker_config',
577                         'ctracker_updates',
578                         'ctracker_language',
579                         'ctracker_localized',
580                         'ctracker_link',
581                         'ctracker_blocked_requests',
582                 ) as $key) {
583                         // Unset it
584                         unset($GLOBALS[$key]);
585         } // END - foreach
586 }
587
588 // Sanitizes string
589 function crackerTrackerSanitize ($str) {
590         return str_replace(array('//', '/./'), array('/', '/'), $str);
591 }