3 * General functions library
5 * @author Roland Haeder <webmaster@shipsimu.org>
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
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.
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.
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/>.
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) {
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);
34 if($array_name != NULL) {
35 $return[] = $array_name . '[' . (string) $key . ']=' . $value . "\n";
37 $return[] = $key . '=' . $value."\n";
42 // Return resulting array
43 return(implode($glue, $return));
47 if (!function_exists('implode_secure')) {
48 // Implode a simple array with a 'call-back' to our escaper function
49 function implode_secure ($array) {
54 foreach ($array as $entry) {
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
63 // Secure this string and add it
64 $return .= '"' . crackerTrackerEscapeString($entry) . '",';
69 $return = substr($return, 0, -1);
76 // Load configuration, if found
77 function crackerTrackerLoadConfiguration () {
79 $fqfn = sprintf('%s/config/db_config.php', $GLOBALS['ctracker_base_path']);
81 // Is the file readable?
82 if (!isCrackerTrackerFileFound($fqfn)) {
83 // No config file found
84 die(__FUNCTION__.': No configuration file found.');
91 $GLOBALS['ctracker_header'] = crackerTrackerLoadEmailTemplate('header');
94 // Getter for ctracker_debug_enabled
95 function isCrackerTrackerDebug () {
97 $result = ((isset($GLOBALS['ctracker_debug_enabled'])) && ($GLOBALS['ctracker_debug_enabled'] === TRUE));
100 //* DEBUG: */ error_log('result=' . intval($result));
106 // Determines the real remote address
107 function determineCrackerTrackerRealRemoteAddress () {
109 $address = '0.0.0.0';
111 // Is a proxy in use?
112 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
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'));
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];
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'])));
145 // Detects the user-agent string
146 function crackerTrackerUserAgent ($sanitize = FALSE) {
147 // Default is 'unknown'
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']));
157 if ($sanitize === TRUE) {
159 $ua = crackerTrackerSanitize($ua);
166 // Detects the script name
167 function crackerTrackerScriptName ($sanitize = FALSE) {
172 if (!empty($_SERVER['SCRIPT_NAME'])) {
174 $scriptName = crackerTrackerSecureString($_SERVER['SCRIPT_NAME']);
178 if ($sanitize === TRUE) {
180 $scriptName = crackerTrackerSanitize($scriptName);
187 // Detects the query string
188 function crackerTrackerQueryString ($sanitize = FALSE) {
193 if (!empty($_SERVER['QUERY_STRING'])) {
195 $query = crackerTrackerEscapeString(urldecode($_SERVER['QUERY_STRING']));
199 if ($sanitize === TRUE) {
201 $query = crackerTrackerSanitize($query);
208 // Detects the server's name
209 function crackerTrackerServerName ($sanitize = FALSE) {
214 if (!empty($_SERVER['SERVER_NAME'])) {
216 $serverName = crackerTrackerSecureString($_SERVER['SERVER_NAME']);
220 if ($sanitize === TRUE) {
222 $serverName = crackerTrackerSanitize($serverName);
229 // Detects the referer
230 function crackerTrackerReferer ($sanitize = FALSE) {
235 if (!empty($_SERVER['HTTP_REFERER'])) {
236 // Then use it securely
237 $referer = crackerTrackerSecureString(urldecode($_SERVER['HTTP_REFERER']));
241 if ($sanitize === TRUE) {
243 $referer = crackerTrackerSanitize($referer);
250 // Detects request method
251 function crackerTrackerRequestMethod () {
256 if (!empty($_SERVER['REQUEST_METHOD'])) {
258 $method = $_SERVER['REQUEST_METHOD'];
265 // Detects the scripts path
266 function crackerTrackerScriptPath () {
267 // Should always be there!
268 $path = dirname(crackerTrackerScriptName()) . '/';
270 // Return detected path
274 // Detects wether we have SSL
275 function crackerTrackerSecured () {
277 $ssl = ((isset($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != 'off'));
283 // Secures a string by escaping it and passing it through strip_tags,htmlentities-chain
284 function crackerTrackerSecureString ($str) {
286 $str = crackerTrackerEscapeString($str);
288 // Then pass it through the functions
289 $str = htmlentities(strip_tags($str), ENT_QUOTES);
295 // Is the file there and readable?
296 function isCrackerTrackerFileFound ($FQFN) {
298 return ((file_exists($FQFN)) && (is_readable($FQFN)));
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'],
309 // Is this template found?
310 if (isCrackerTrackerFileFound($FQFN)) {
312 crackerTrackerLanguage();
317 // Not found, so die here
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(),
331 // Is this template found?
332 if (isCrackerTrackerFileFound($FQFN)) {
336 // Not found, so die here
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';
347 // Is the language string there?
348 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
350 foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
351 // Split it again for q=x.x value
352 $langArray = explode(';', $lang);
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];
364 $FQFN = sprintf('%s/libs/language/%s.php',
365 $GLOBALS['ctracker_base_path'],
366 getCrackerTrackerLanguage()
369 // Is it not there, switch to "en"
370 if ((getCrackerTrackerLanguage() != 'en') && (!isCrackerTrackerFileFound($FQFN))) {
371 // English is default!
372 $GLOBALS['ctracker_language'] = 'en';
374 // Construct FQFN again
375 $FQFN = sprintf('%s/libs/language/en.php', $GLOBALS['ctracker_base_path']);
378 // Load the language file
382 // Loads a given email template and passes through $content
383 function crackerTrackerLoadEmailTemplate ($template, array $content = array(), $language = NULL) {
385 crackerTrackerLanguage();
388 $FQFN = sprintf('%s/libs/mails/%s/%s.tpl',
389 $GLOBALS['ctracker_base_path'],
390 getCrackerTrackerLanguage($language),
394 // So is the file there?
395 if (isCrackerTrackerFileFound($FQFN)) {
397 $result = 'No result from template ' . $template . '. Please report this at http://forum.shipsimu.org Thank you.';
400 //* DEBUG-DIE: */ die('<pre>$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";</pre>');
401 eval('$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";');
411 // Getter for message
412 function getCrackerTrackerLocalized ($message) {
414 $output = '!' . $message . '!';
416 // Is the language string there?
417 if (isset($GLOBALS['ctracker_localized'][$message])) {
419 $output = $GLOBALS['ctracker_localized'][$message];
426 // Tries to find a message and outputs it
427 function crackerTrackerOutputLocalized ($message) {
429 print getCrackerTrackerLocalized($message);
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);
437 // Replace " with {QUOTE}
438 $code = str_replace('"', '{QUOTE}', $code);
441 foreach ($matches[0] as $key=>$match) {
443 if (substr($match, 0, 8) == '$GLOBALS') {
445 $code = str_replace($match, "\" . \$GLOBALS['" . $matches[4][$key] . "'] . \"", $code);
446 } elseif (substr($match, 0, 8) == '$content') {
448 $code = str_replace($match, "\" . \$content['" . $matches[4][$key] . "'] . \"", $code);
456 // "Getter" for language
457 function getCrackerTrackerLanguage ($lang = NULL) {
458 // Default is from browser
459 $language = $GLOBALS['ctracker_language'];
462 if (!is_null($lang)) {
463 // Then use this instead
471 // "Getter" for ticket id
472 function getCrackerTrackerTicketId () {
477 if (isset($GLOBALS['ctracker_last_ticket']['ctracker_ticket'])) {
479 $id = $GLOBALS['ctracker_last_ticket']['ctracker_ticket'];
486 // Sends a cookie to the user that he would not see this security warning again
487 function sendCrackerTrackerCookie () {
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();
494 // Is the cookie set?
495 function ifCrackerTrackerCookieIsSet () {
496 // Is it set and valid?
497 return ((isset($_COOKIE['ctracker_ticket'])) && ($_COOKIE['ctracker_ticket'] > 0));
500 // Redirects to the same URL
501 function crackerTrackerRedirectSameUrl () {
503 $url = '://' . crackerTrackerServerName() . crackerTrackerScriptName() . '?' . crackerTrackerQueryString();
506 if (crackerTrackerSecured()) {
508 $url = 'https' . $url;
511 $url = 'http' . $url;
515 crackerTrackerSendRawRedirect($url);
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.
522 * Works arround Microsoft IIS cookie sending bug. Does exit the script.
524 * @link http://support.microsoft.com/kb/q176113/
525 * @author Andreas Gohr <andi@splitbrain.org>
528 function crackerTrackerSendRawRedirect ($url) {
529 // Better remove any data by ctracker
532 // always close the session
533 session_write_close();
535 // Revert entity &
536 $url = str_replace('&', '&', $url);
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)) &&
543 // Send the IIS header
544 header('Refresh: 0;url=' . $url);
546 // Send generic header
547 header('Location: ' . $url);
552 // Removes all ctracker-related data from global space
553 function unsetCtrackerData () {
555 //* DEBUG: */ error_log(__FUNCTION__ . ': CALLED!');
557 // Unset all ctracker data
559 'ctracker_base_path',
564 'ctracker_debug_enabled',
566 'ctracker_whitelist',
567 'ctracker_get_blacklist',
568 'ctracker_post_blacklist',
570 'ctracker_post_track',
571 'ctracker_checked_get',
572 'ctracker_checked_post',
573 'ctracker_checked_ua',
575 'ctracker_last_result',
579 'ctracker_localized',
581 'ctracker_blocked_requests',
584 unset($GLOBALS[$key]);
589 function crackerTrackerSanitize ($str) {
590 return str_replace(array('//', '/./'), array('/', '/'), $str);