]> git.mxchange.org Git - ctracker.git/blob - libs/lib_general.php
Renaming season has started:
[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 () {
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         // Return it
157         return $ua;
158 }
159
160 // Detects the script name
161 function crackerTrackerScriptName () {
162         // Is it there?
163         if (!isset($_SERVER['SCRIPT_NAME'])) {
164                 // Return NULL
165                 return NULL;
166         } // END - if
167
168         // Should always be there!
169         return crackerTrackerSecureString($_SERVER['SCRIPT_NAME']);
170 }
171
172 // Detects the query string
173 function crackerTrackerQueryString () {
174         // Is it there?
175         if (!isset($_SERVER['QUERY_STRING'])) {
176                 // Return NULL
177                 return NULL;
178         } // END - if
179
180         // Should always be there!
181         return crackerTrackerEscapeString(urldecode($_SERVER['QUERY_STRING']));
182 }
183
184 // Detects the server's name
185 function crackerTrackerServerName () {
186         // Is it there?
187         if (!isset($_SERVER['SERVER_NAME'])) {
188                 // Return NULL
189                 return NULL;
190         } // END - if
191
192         // Should always be there!
193         return crackerTrackerSecureString($_SERVER['SERVER_NAME']);
194 }
195
196 // Detects the referer
197 function crackerTrackerReferer () {
198         // Default is a dash
199         $referer = '-';
200
201         // Is it there?
202         if (!empty($_SERVER['HTTP_REFERER'])) {
203                 // Then use it securely
204                 $referer = crackerTrackerSecureString(urldecode($_SERVER['HTTP_REFERER']));
205         } // END - if
206
207         // Return it
208         return $referer;
209 }
210
211 // Detects request method
212 function crackerTrackerRequestMethod () {
213         // Default is NULL
214         $method = NULL;
215
216         // Is it set?
217         if (!empty($_SERVER['REQUEST_METHOD'])) {
218                 // Then use it
219                 $method = $_SERVER['REQUEST_METHOD'];
220         } // END - if
221
222         // Return it
223         return $method;
224 }
225
226 // Detects the scripts path
227 function crackerTrackerScriptPath () {
228         // Should always be there!
229         $path = dirname(crackerTrackerScriptName()) . '/';
230
231         // Return detected path
232         return $path;
233 }
234
235 // Detects wether we have SSL
236 function crackerTrackerSecured () {
237         // Detect it
238         $ssl = ((isset($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != 'off'));
239
240         // Return result
241         return $ssl;
242 }
243
244 // Secures a string by escaping it and passing it through strip_tags,htmlentities-chain
245 function crackerTrackerSecureString ($str) {
246         // First escape it
247         $str = crackerTrackerEscapeString($str);
248
249         // Then pass it through the functions
250         $str = htmlentities(strip_tags($str), ENT_QUOTES);
251
252         // Return it
253         return $str;
254 }
255
256 // Is the file there and readable?
257 function isCrackerTrackerFileFound ($FQFN) {
258         // Simply check it
259         return ((file_exists($FQFN)) && (is_readable($FQFN)));
260 }
261
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'],
267                 $template
268         );
269
270         // Is this template found?
271         if (isCrackerTrackerFileFound($FQFN)) {
272                 // Detect language
273                 crackerTrackerLanguage();
274
275                 // Load it
276                 require_once($FQFN);
277         } else {
278                 // Not found, so die here
279                 crackerTrackerDie();
280         }
281 }
282
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(),
289                 $template
290         );
291
292         // Is this template found?
293         if (isCrackerTrackerFileFound($FQFN)) {
294                 // Load it
295                 require_once($FQFN);
296         } else {
297                 // Not found, so die here
298                 crackerTrackerDie();
299         }
300 }
301
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';
306         $weight = 1;
307
308         // Is the language string there?
309         if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
310                 // Then detect it
311                 foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
312                         // Split it again for q=x.x value
313                         $langArray = explode(';', $lang);
314
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];
320                         } // END - if
321                 } // END - foreach
322         } // END - if
323
324         // Construct FQFN
325         $FQFN = sprintf('%s/libs/language/%s.php',
326                 $GLOBALS['ctracker_base_path'],
327                 getCrackerTrackerLanguage()
328         );
329
330         // Is it not there, switch to "en"
331         if ((getCrackerTrackerLanguage() != 'en') && (!isCrackerTrackerFileFound($FQFN))) {
332                 // English is default!
333                 $GLOBALS['ctracker_language'] = 'en';
334
335                 // Construct FQFN again
336                 $FQFN = sprintf('%s/libs/language/en.php', $GLOBALS['ctracker_base_path']);
337         } // END - if
338
339         // Load the language file
340         require($FQFN);
341 }
342
343 // Loads a given email template and passes through $content
344 function crackerTrackerLoadEmailTemplate ($template, array $content = array(), $language = NULL) {
345         // Init language
346         crackerTrackerLanguage();
347
348         // Generate the FQFN
349         $FQFN = sprintf('%s/libs/mails/%s/%s.tpl',
350                 $GLOBALS['ctracker_base_path'],
351                 getCrackerTrackerLanguage($language),
352                 $template
353         );
354
355         // So is the file there?
356         if (isCrackerTrackerFileFound($FQFN)) {
357                 // Init result
358                 $result = 'No result from template ' . $template . '. Please report this at http://forum.shipsimu.org Thank you.';
359
360                 // Then load it
361                 //* DEBUG-DIE: */ die('<pre>$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";</pre>');
362                 eval('$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";');
363
364                 // Return the result
365                 return $result;
366         } else {
367                 // Not found
368                 crackerTrackerDie();
369         }
370 }
371
372 // Getter for message
373 function getCrackerTrackerLocalized ($message) {
374         // Default message
375         $output = '!' . $message . '!';
376
377         // Is the language string there?
378         if (isset($GLOBALS['ctracker_localized'][$message])) {
379                 // Use this instead
380                 $output = $GLOBALS['ctracker_localized'][$message];
381         } // END - if
382
383         // Return it
384         return $output;
385 }
386
387 // Tries to find a message and outputs it
388 function crackerTrackerOutputLocalized ($message) {
389         // Output it
390         print getCrackerTrackerLocalized($message);
391 }
392
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);
397
398         // Replace " with {QUOTE}
399         $code = str_replace('"', '{QUOTE}', $code);
400
401         // Replace all
402         foreach ($matches[0] as $key=>$match) {
403                 // Replace it
404                 if (substr($match, 0, 8) == '$GLOBALS') {
405                         // $GLOBALS
406                         $code = str_replace($match, "\" . \$GLOBALS['" . $matches[4][$key] . "'] . \"", $code);
407                 } elseif (substr($match, 0, 8) == '$content') {
408                         // $content
409                         $code = str_replace($match, "\" . \$content['" . $matches[4][$key] . "'] . \"", $code);
410                 }
411         } // END - foreach
412
413         // Return it
414         return $code;
415 }
416
417 // "Getter" for language
418 function getCrackerTrackerLanguage ($lang = NULL) {
419         // Default is from browser
420         $language = $GLOBALS['ctracker_language'];
421
422         // Is $lang set?
423         if (!is_null($lang)) {
424                 // Then use this instead
425                 $language = $lang;
426         } // END - if
427
428         // Return it
429         return $language;
430 }
431
432 // "Getter" for ticket id
433 function getCrackerTrackerTicketId () {
434         // Default is zero
435         $id = 0;
436
437         // Is it set?
438         if (isset($GLOBALS['ctracker_last_ticket']['ctracker_ticket'])) {
439                 // Then use it
440                 $id = $GLOBALS['ctracker_last_ticket']['ctracker_ticket'];
441         } // END - if
442
443         // Return the number
444         return $id;
445 }
446
447 // Sends a cookie to the user that he would not see this security warning again
448 function sendCrackerTrackerCookie () {
449         // Set the cookie
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();
453 }
454
455 // Is the cookie set?
456 function ifCrackerTrackerCookieIsSet () {
457         // Is it set and valid?
458         return ((isset($_COOKIE['ctracker_ticket'])) && ($_COOKIE['ctracker_ticket'] > 0));
459 }
460
461 // Redirects to the same URL
462 function crackerTrackerRedirectSameUrl () {
463         // Construct the url
464         $url = '://' . crackerTrackerServerName() . crackerTrackerScriptName() . '?' . crackerTrackerQueryString();
465
466         // Do we have SSL?
467         if (crackerTrackerSecured()) {
468                 // HTTPS
469                 $url = 'https' . $url;
470         } else {
471                 // HTTP
472                 $url = 'http' . $url;
473         }
474
475         // And redirect
476         crackerTrackerSendRawRedirect($url);
477 }
478
479 /**
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.
482  *
483  * Works arround Microsoft IIS cookie sending bug. Does exit the script.
484  *
485  * @link    http://support.microsoft.com/kb/q176113/
486  * @author  Andreas Gohr <andi@splitbrain.org>
487  * @access  private
488  */
489 function crackerTrackerSendRawRedirect ($url) {
490         // Better remove any data by ctracker
491         unsetCtrackerData();
492
493         // always close the session
494         session_write_close();
495
496         // Revert entity &amp;
497         $url = str_replace('&amp;', '&', $url);
498
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)) &&
503                 ($matches[1] < 6)) {
504                 // Send the IIS header
505                 header('Refresh: 0;url=' . $url);
506         } else {
507                 // Send generic header
508                 header('Location: ' . $url);
509         }
510         exit();
511 }
512
513 // Removes all ctracker-related data from global space
514 function unsetCtrackerData () {
515         // Debug message
516         //* DEBUG: */ error_log(__FUNCTION__ . ': CALLED!');
517
518         // Unset all ctracker data
519         foreach (array(
520                         'ctracker_base_path',
521                         'ctracker_host',
522                         'ctracker_dbname',
523                         'ctracker_user',
524                         'ctracker_password',
525                         'ctracker_debug_enabled',
526                         'ctracker_email',
527                         'ctracker_whitelist',
528                         'ctracker_get_blacklist',
529                         'ctracker_post_blacklist',
530                         'ctracker_header',
531                         'ctracker_post_track',
532                         'ctracker_checked_get',
533                         'ctracker_checked_post',
534                         'ctracker_checked_ua',
535                         'ctracker_last_sql',
536                         'ctracker_last_result',
537                         'ctracker_config',
538                         'ctracker_updates',
539                         'ctracker_language',
540                         'ctracker_localized',
541                         'ctracker_link',
542                 ) as $key) {
543                         // Unset it
544                         unset($GLOBALS[$key]);
545         } // END - foreach
546 }
547
548 // [EOF]
549 ?>