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 () {
147 // Default is 'unknown'
150 // Is the entry there?
151 if (isset($_SERVER['HTTP_USER_AGENT'])) {
152 // Then use it securely
153 $ua = crackerTrackerSecureString($_SERVER['HTTP_USER_AGENT']);
160 // Detects the script name
161 function crackerTrackerScriptName () {
163 if (!isset($_SERVER['SCRIPT_NAME'])) {
168 // Should always be there!
169 return crackerTrackerSecureString($_SERVER['SCRIPT_NAME']);
172 // Detects the query string
173 function crackerTrackerQueryString () {
175 if (!isset($_SERVER['QUERY_STRING'])) {
180 // Should always be there!
181 return crackerTrackerEscapeString(urldecode($_SERVER['QUERY_STRING']));
184 // Detects the server's name
185 function crackerTrackerServerName () {
187 if (!isset($_SERVER['SERVER_NAME'])) {
192 // Should always be there!
193 return crackerTrackerSecureString($_SERVER['SERVER_NAME']);
196 // Detects the referer
197 function crackerTrackerReferer () {
202 if (isset($_SERVER['HTTP_REFERER'])) {
203 // Then use it securely
204 $referer = crackerTrackerSecureString(urldecode($_SERVER['HTTP_REFERER']));
211 // Detects the scripts path
212 function crackerTrackerScriptPath () {
213 // Should always be there!
214 $path = dirname(crackerTrackerScriptName()) . '/';
216 // Return detected path
220 // Detects wether we have SSL
221 function crackerTrackerSecured () {
223 $ssl = ((isset($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != 'off'));
229 // Secures a string by escaping it and passing it through strip_tags,htmlentities-chain
230 function crackerTrackerSecureString ($str) {
232 $str = crackerTrackerEscapeString($str);
234 // Then pass it through the functions
235 $str = htmlentities(strip_tags($str), ENT_QUOTES);
241 // Is the file there and readable?
242 function isCrackerTrackerFileFound ($FQFN) {
244 return ((file_exists($FQFN)) && (is_readable($FQFN)));
247 // Loads a given "template" (this is more an include file)
248 function crackerTrackerLoadTemplate ($template) {
249 // Create the full-qualified filename (FQFN)
250 $FQFN = sprintf('%s/libs/templates/%s.tpl.php',
251 $GLOBALS['ctracker_base_path'],
255 // Is this template found?
256 if (isCrackerTrackerFileFound($FQFN)) {
258 crackerTrackerLanguage();
263 // Not found, so die here
268 // Loads a given "template" (this is more an include file)
269 function crackerTrackerLoadLocalizedTemplate ($template) {
270 // Create the full-qualified filename (FQFN)
271 $FQFN = sprintf('%s/libs/templates/%s/%s.tpl.php',
272 $GLOBALS['ctracker_base_path'],
273 getCrackerTrackerLanguage(),
277 // Is this template found?
278 if (isCrackerTrackerFileFound($FQFN)) {
282 // Not found, so die here
287 // Detects the browser's language file and tries to load it, fall-back on english!
288 function crackerTrackerLanguage () {
289 // Default is English
290 $GLOBALS['ctracker_language'] = 'en';
293 // Is the language string there?
294 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
296 foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
297 // Split it again for q=x.x value
298 $langArray = explode(';', $lang);
300 // If there is an entry, we have a weight
301 if ((isset($langArray[1])) && ($langArray[1] > $weight)) {
302 // Use this language/weight instead
303 $GLOBALS['ctracker_language'] = $langArray[0];
304 $weight = $langArray[1];
310 $FQFN = sprintf('%s/libs/language/%s.php',
311 $GLOBALS['ctracker_base_path'],
312 getCrackerTrackerLanguage()
315 // Is it not there, switch to "en"
316 if ((getCrackerTrackerLanguage() != 'en') && (!isCrackerTrackerFileFound($FQFN))) {
317 // English is default!
318 $GLOBALS['ctracker_language'] = 'en';
320 // Construct FQFN again
321 $FQFN = sprintf('%s/libs/language/en.php', $GLOBALS['ctracker_base_path']);
324 // Load the language file
328 // Loads a given email template and passes through $content
329 function crackerTrackerLoadEmailTemplate ($template, array $content = array(), $language = NULL) {
331 crackerTrackerLanguage();
334 $FQFN = sprintf('%s/libs/mails/%s/%s.tpl',
335 $GLOBALS['ctracker_base_path'],
336 getCrackerTrackerLanguage($language),
340 // So is the file there?
341 if (isCrackerTrackerFileFound($FQFN)) {
343 $result = 'No result from template ' . $template . '. Please report this at http://forum.shipsimu.org Thank you.';
346 //* DEBUG-DIE: */ die('<pre>$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";</pre>');
347 eval('$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";');
357 // Getter for message
358 function getCrackerTrackerLocalized ($message) {
360 $output = '!' . $message . '!';
362 // Is the language string there?
363 if (isset($GLOBALS['ctracker_localized'][$message])) {
365 $output = $GLOBALS['ctracker_localized'][$message];
372 // Tries to find a message and outputs it
373 function crackerTrackerOutputLocalized ($message) {
375 print getCrackerTrackerLocalized($message);
378 // Compiles the given code
379 function crackerTrackerCompileCode ($code) {
380 // Find all $content[foo]
381 preg_match_all('/\$(content|GLOBALS)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
383 // Replace " with {QUOTE}
384 $code = str_replace('"', '{QUOTE}', $code);
387 foreach ($matches[0] as $key=>$match) {
389 if (substr($match, 0, 8) == '$GLOBALS') {
391 $code = str_replace($match, "\" . \$GLOBALS['" . $matches[4][$key] . "'] . \"", $code);
392 } elseif (substr($match, 0, 8) == '$content') {
394 $code = str_replace($match, "\" . \$content['" . $matches[4][$key] . "'] . \"", $code);
402 // "Getter" for language
403 function getCrackerTrackerLanguage ($lang = NULL) {
404 // Default is from browser
405 $language = $GLOBALS['ctracker_language'];
408 if (!is_null($lang)) {
409 // Then use this instead
417 // "Getter" for ticket id
418 function getCrackerTrackerTicketId () {
423 if (isset($GLOBALS['ctracker_last_ticket']['ctracker_ticket'])) {
425 $id = $GLOBALS['ctracker_last_ticket']['ctracker_ticket'];
432 // Sends a cookie to the user that he would not see this security warning again
433 function sendCrackerTrackerCookie () {
435 // @TODO Why can't domain be set to value from crackerTrackerServerName() ?
436 setcookie('ctracker_ticket', getCrackerTrackerTicketId(), (time() + 60*60*24), '/', '', crackerTrackerSecured(), TRUE);
437 $_COOKIE['ctracker_ticket'] = getCrackerTrackerTicketId();
440 // Is the cookie set?
441 function ifCrackerTrackerCookieIsSet () {
442 // Is it set and valid?
443 return ((isset($_COOKIE['ctracker_ticket'])) && ($_COOKIE['ctracker_ticket'] > 0));
446 // Redirects to the same URL
447 function crackerTrackerRedirectSameUrl () {
449 $url = '://' . crackerTrackerServerName() . crackerTrackerScriptName() . '?' . crackerTrackerQueryString();
452 if (crackerTrackerSecured()) {
454 $url = 'https' . $url;
457 $url = 'http' . $url;
461 crackerTrackerSendRawRedirect($url);
465 * Send a HTTP redirect to the browser. This function was taken from DokuWiki
466 * (GNU GPL 2; http://www.dokuwiki.org) and modified to fit into this script.
468 * Works arround Microsoft IIS cookie sending bug. Does exit the script.
470 * @link http://support.microsoft.com/kb/q176113/
471 * @author Andreas Gohr <andi@splitbrain.org>
474 function crackerTrackerSendRawRedirect ($url) {
475 // Better remove any data by ctracker
478 // always close the session
479 session_write_close();
481 // Revert entity &
482 $url = str_replace('&', '&', $url);
484 // check if running on IIS < 6 with CGI-PHP
485 if ((isset($_SERVER['SERVER_SOFTWARE'])) && (isset($_SERVER['GATEWAY_INTERFACE'])) &&
486 (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== FALSE) &&
487 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
489 // Send the IIS header
490 header('Refresh: 0;url=' . $url);
492 // Send generic header
493 header('Location: ' . $url);
498 // Removes all ctracker-related data from global space
499 function unsetCtrackerData () {
501 //* DEBUG: */ error_log(__FUNCTION__ . ': CALLED!');
503 // Unset all ctracker data
505 'ctracker_base_path',
510 'ctracker_debug_enabled',
512 'ctracker_whitelist',
513 'ctracker_get_blacklist',
514 'ctracker_post_blacklist',
516 'ctracker_post_track',
517 'ctracker_checkworm',
518 'ctracker_check_post',
520 'ctracker_last_result',
524 'ctracker_localized',
528 unset($GLOBALS[$key]);