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(urldecode($_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 (!empty($_SERVER['HTTP_REFERER'])) {
203 // Then use it securely
204 $referer = crackerTrackerSecureString(urldecode($_SERVER['HTTP_REFERER']));
211 // Detects request method
212 function crackerTrackerRequestMethod () {
217 if (!empty($_SERVER['REQUEST_METHOD'])) {
219 $method = $_SERVER['REQUEST_METHOD'];
226 // Detects the scripts path
227 function crackerTrackerScriptPath () {
228 // Should always be there!
229 $path = dirname(crackerTrackerScriptName()) . '/';
231 // Return detected path
235 // Detects wether we have SSL
236 function crackerTrackerSecured () {
238 $ssl = ((isset($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != 'off'));
244 // Secures a string by escaping it and passing it through strip_tags,htmlentities-chain
245 function crackerTrackerSecureString ($str) {
247 $str = crackerTrackerEscapeString($str);
249 // Then pass it through the functions
250 $str = htmlentities(strip_tags($str), ENT_QUOTES);
256 // Is the file there and readable?
257 function isCrackerTrackerFileFound ($FQFN) {
259 return ((file_exists($FQFN)) && (is_readable($FQFN)));
262 // Loads a given "template" (this is more an include file)
263 function crackerTrackerLoadTemplate ($template) {
264 // Create the full-qualified filename (FQFN)
265 $FQFN = sprintf('%s/libs/templates/%s.tpl.php',
266 $GLOBALS['ctracker_base_path'],
270 // Is this template found?
271 if (isCrackerTrackerFileFound($FQFN)) {
273 crackerTrackerLanguage();
278 // Not found, so die here
283 // Loads a given "template" (this is more an include file)
284 function crackerTrackerLoadLocalizedTemplate ($template) {
285 // Create the full-qualified filename (FQFN)
286 $FQFN = sprintf('%s/libs/templates/%s/%s.tpl.php',
287 $GLOBALS['ctracker_base_path'],
288 getCrackerTrackerLanguage(),
292 // Is this template found?
293 if (isCrackerTrackerFileFound($FQFN)) {
297 // Not found, so die here
302 // Detects the browser's language file and tries to load it, fall-back on english!
303 function crackerTrackerLanguage () {
304 // Default is English
305 $GLOBALS['ctracker_language'] = 'en';
308 // Is the language string there?
309 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
311 foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
312 // Split it again for q=x.x value
313 $langArray = explode(';', $lang);
315 // If there is an entry, we have a weight
316 if ((isset($langArray[1])) && ($langArray[1] > $weight)) {
317 // Use this language/weight instead
318 $GLOBALS['ctracker_language'] = $langArray[0];
319 $weight = $langArray[1];
325 $FQFN = sprintf('%s/libs/language/%s.php',
326 $GLOBALS['ctracker_base_path'],
327 getCrackerTrackerLanguage()
330 // Is it not there, switch to "en"
331 if ((getCrackerTrackerLanguage() != 'en') && (!isCrackerTrackerFileFound($FQFN))) {
332 // English is default!
333 $GLOBALS['ctracker_language'] = 'en';
335 // Construct FQFN again
336 $FQFN = sprintf('%s/libs/language/en.php', $GLOBALS['ctracker_base_path']);
339 // Load the language file
343 // Loads a given email template and passes through $content
344 function crackerTrackerLoadEmailTemplate ($template, array $content = array(), $language = NULL) {
346 crackerTrackerLanguage();
349 $FQFN = sprintf('%s/libs/mails/%s/%s.tpl',
350 $GLOBALS['ctracker_base_path'],
351 getCrackerTrackerLanguage($language),
355 // So is the file there?
356 if (isCrackerTrackerFileFound($FQFN)) {
358 $result = 'No result from template ' . $template . '. Please report this at http://forum.shipsimu.org Thank you.';
361 //* DEBUG-DIE: */ die('<pre>$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";</pre>');
362 eval('$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";');
372 // Getter for message
373 function getCrackerTrackerLocalized ($message) {
375 $output = '!' . $message . '!';
377 // Is the language string there?
378 if (isset($GLOBALS['ctracker_localized'][$message])) {
380 $output = $GLOBALS['ctracker_localized'][$message];
387 // Tries to find a message and outputs it
388 function crackerTrackerOutputLocalized ($message) {
390 print getCrackerTrackerLocalized($message);
393 // Compiles the given code
394 function crackerTrackerCompileCode ($code) {
395 // Find all $content[foo]
396 preg_match_all('/\$(content|GLOBALS)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
398 // Replace " with {QUOTE}
399 $code = str_replace('"', '{QUOTE}', $code);
402 foreach ($matches[0] as $key=>$match) {
404 if (substr($match, 0, 8) == '$GLOBALS') {
406 $code = str_replace($match, "\" . \$GLOBALS['" . $matches[4][$key] . "'] . \"", $code);
407 } elseif (substr($match, 0, 8) == '$content') {
409 $code = str_replace($match, "\" . \$content['" . $matches[4][$key] . "'] . \"", $code);
417 // "Getter" for language
418 function getCrackerTrackerLanguage ($lang = NULL) {
419 // Default is from browser
420 $language = $GLOBALS['ctracker_language'];
423 if (!is_null($lang)) {
424 // Then use this instead
432 // "Getter" for ticket id
433 function getCrackerTrackerTicketId () {
438 if (isset($GLOBALS['ctracker_last_ticket']['ctracker_ticket'])) {
440 $id = $GLOBALS['ctracker_last_ticket']['ctracker_ticket'];
447 // Sends a cookie to the user that he would not see this security warning again
448 function sendCrackerTrackerCookie () {
450 // @TODO Why can't domain be set to value from crackerTrackerServerName() ?
451 setcookie('ctracker_ticket', getCrackerTrackerTicketId(), (time() + 60*60*24), '/', '', crackerTrackerSecured(), TRUE);
452 $_COOKIE['ctracker_ticket'] = getCrackerTrackerTicketId();
455 // Is the cookie set?
456 function ifCrackerTrackerCookieIsSet () {
457 // Is it set and valid?
458 return ((isset($_COOKIE['ctracker_ticket'])) && ($_COOKIE['ctracker_ticket'] > 0));
461 // Redirects to the same URL
462 function crackerTrackerRedirectSameUrl () {
464 $url = '://' . crackerTrackerServerName() . crackerTrackerScriptName() . '?' . crackerTrackerQueryString();
467 if (crackerTrackerSecured()) {
469 $url = 'https' . $url;
472 $url = 'http' . $url;
476 crackerTrackerSendRawRedirect($url);
480 * Send a HTTP redirect to the browser. This function was taken from DokuWiki
481 * (GNU GPL 2; http://www.dokuwiki.org) and modified to fit into this script.
483 * Works arround Microsoft IIS cookie sending bug. Does exit the script.
485 * @link http://support.microsoft.com/kb/q176113/
486 * @author Andreas Gohr <andi@splitbrain.org>
489 function crackerTrackerSendRawRedirect ($url) {
490 // Better remove any data by ctracker
493 // always close the session
494 session_write_close();
496 // Revert entity &
497 $url = str_replace('&', '&', $url);
499 // check if running on IIS < 6 with CGI-PHP
500 if ((isset($_SERVER['SERVER_SOFTWARE'])) && (isset($_SERVER['GATEWAY_INTERFACE'])) &&
501 (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== FALSE) &&
502 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
504 // Send the IIS header
505 header('Refresh: 0;url=' . $url);
507 // Send generic header
508 header('Location: ' . $url);
513 // Removes all ctracker-related data from global space
514 function unsetCtrackerData () {
516 //* DEBUG: */ error_log(__FUNCTION__ . ': CALLED!');
518 // Unset all ctracker data
520 'ctracker_base_path',
525 'ctracker_debug_enabled',
527 'ctracker_whitelist',
528 'ctracker_get_blacklist',
529 'ctracker_post_blacklist',
531 'ctracker_post_track',
532 'ctracker_checked_get',
533 'ctracker_checked_post',
534 'ctracker_checked_ua',
536 'ctracker_last_result',
540 'ctracker_localized',
544 unset($GLOBALS[$key]);