]> git.mxchange.org Git - ctracker.git/blob - libs/lib_general.php
Updated a lot:
[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($_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 (isset($_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 the scripts path
212 function crackerTrackerScriptPath () {
213         // Should always be there!
214         $path = dirname(crackerTrackerScriptName()) . '/';
215
216         // Return detected path
217         return $path;
218 }
219
220 // Detects wether we have SSL
221 function crackerTrackerSecured () {
222         // Detect it
223         $ssl = ((isset($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != 'off'));
224
225         // Return result
226         return $ssl;
227 }
228
229 // Secures a string by escaping it and passing it through strip_tags,htmlentities-chain
230 function crackerTrackerSecureString ($str) {
231         // First escape it
232         $str = crackerTrackerEscapeString($str);
233
234         // Then pass it through the functions
235         $str = htmlentities(strip_tags($str), ENT_QUOTES);
236
237         // Return it
238         return $str;
239 }
240
241 // Is the file there and readable?
242 function isCrackerTrackerFileFound ($FQFN) {
243         // Simply check it
244         return ((file_exists($FQFN)) && (is_readable($FQFN)));
245 }
246
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'],
252                 $template
253         );
254
255         // Is this template found?
256         if (isCrackerTrackerFileFound($FQFN)) {
257                 // Detect language
258                 crackerTrackerLanguage();
259
260                 // Load it
261                 require_once($FQFN);
262         } else {
263                 // Not found, so die here
264                 crackerTrackerDie();
265         }
266 }
267
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(),
274                 $template
275         );
276
277         // Is this template found?
278         if (isCrackerTrackerFileFound($FQFN)) {
279                 // Load it
280                 require_once($FQFN);
281         } else {
282                 // Not found, so die here
283                 crackerTrackerDie();
284         }
285 }
286
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';
291         $weight = 1;
292
293         // Is the language string there?
294         if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
295                 // Then detect it
296                 foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
297                         // Split it again for q=x.x value
298                         $langArray = explode(';', $lang);
299
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];
305                         } // END - if
306                 } // END - foreach
307         } // END - if
308
309         // Construct FQFN
310         $FQFN = sprintf('%s/libs/language/%s.php',
311                 $GLOBALS['ctracker_base_path'],
312                 getCrackerTrackerLanguage()
313         );
314
315         // Is it not there, switch to "en"
316         if ((getCrackerTrackerLanguage() != 'en') && (!isCrackerTrackerFileFound($FQFN))) {
317                 // English is default!
318                 $GLOBALS['ctracker_language'] = 'en';
319
320                 // Construct FQFN again
321                 $FQFN = sprintf('%s/libs/language/en.php', $GLOBALS['ctracker_base_path']);
322         } // END - if
323
324         // Load the language file
325         require($FQFN);
326 }
327
328 // Loads a given email template and passes through $content
329 function crackerTrackerLoadEmailTemplate ($template, array $content = array(), $language = NULL) {
330         // Init language
331         crackerTrackerLanguage();
332
333         // Generate the FQFN
334         $FQFN = sprintf('%s/libs/mails/%s/%s.tpl',
335                 $GLOBALS['ctracker_base_path'],
336                 getCrackerTrackerLanguage($language),
337                 $template
338         );
339
340         // So is the file there?
341         if (isCrackerTrackerFileFound($FQFN)) {
342                 // Init result
343                 $result = 'No result from template ' . $template . '. Please report this at http://forum.shipsimu.org Thank you.';
344
345                 // Then load it
346                 //* DEBUG-DIE: */ die('<pre>$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";</pre>');
347                 eval('$result = "' . crackerTrackerCompileCode(trim(file_get_contents($FQFN))) . '";');
348
349                 // Return the result
350                 return $result;
351         } else {
352                 // Not found
353                 crackerTrackerDie();
354         }
355 }
356
357 // Getter for message
358 function getCrackerTrackerLocalized ($message) {
359         // Default message
360         $output = '!' . $message . '!';
361
362         // Is the language string there?
363         if (isset($GLOBALS['ctracker_localized'][$message])) {
364                 // Use this instead
365                 $output = $GLOBALS['ctracker_localized'][$message];
366         } // END - if
367
368         // Return it
369         return $output;
370 }
371
372 // Tries to find a message and outputs it
373 function crackerTrackerOutputLocalized ($message) {
374         // Output it
375         print getCrackerTrackerLocalized($message);
376 }
377
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);
382
383         // Replace " with {QUOTE}
384         $code = str_replace('"', '{QUOTE}', $code);
385
386         // Replace all
387         foreach ($matches[0] as $key=>$match) {
388                 // Replace it
389                 if (substr($match, 0, 8) == '$GLOBALS') {
390                         // $GLOBALS
391                         $code = str_replace($match, "\" . \$GLOBALS['" . $matches[4][$key] . "'] . \"", $code);
392                 } elseif (substr($match, 0, 8) == '$content') {
393                         // $content
394                         $code = str_replace($match, "\" . \$content['" . $matches[4][$key] . "'] . \"", $code);
395                 }
396         } // END - foreach
397
398         // Return it
399         return $code;
400 }
401
402 // "Getter" for language
403 function getCrackerTrackerLanguage ($lang = NULL) {
404         // Default is from browser
405         $language = $GLOBALS['ctracker_language'];
406
407         // Is $lang set?
408         if (!is_null($lang)) {
409                 // Then use this instead
410                 $language = $lang;
411         } // END - if
412
413         // Return it
414         return $language;
415 }
416
417 // "Getter" for ticket id
418 function getCrackerTrackerTicketId () {
419         // Default is zero
420         $id = 0;
421
422         // Is it set?
423         if (isset($GLOBALS['ctracker_last_ticket']['ctracker_ticket'])) {
424                 // Then use it
425                 $id = $GLOBALS['ctracker_last_ticket']['ctracker_ticket'];
426         } // END - if
427
428         // Return the number
429         return $id;
430 }
431
432 // Sends a cookie to the user that he would not see this security warning again
433 function sendCrackerTrackerCookie () {
434         // Set the cookie
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();
438 }
439
440 // Is the cookie set?
441 function ifCrackerTrackerCookieIsSet () {
442         // Is it set and valid?
443         return ((isset($_COOKIE['ctracker_ticket'])) && ($_COOKIE['ctracker_ticket'] > 0));
444 }
445
446 // Redirects to the same URL
447 function crackerTrackerRedirectSameUrl () {
448         // Construct the url
449         $url = '://' . crackerTrackerServerName() . crackerTrackerScriptName() . '?' . crackerTrackerQueryString();
450
451         // Do we have SSL?
452         if (crackerTrackerSecured()) {
453                 // HTTPS
454                 $url = 'https' . $url;
455         } else {
456                 // HTTP
457                 $url = 'http' . $url;
458         }
459
460         // And redirect
461         crackerTrackerSendRawRedirect($url);
462 }
463
464 /**
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.
467  *
468  * Works arround Microsoft IIS cookie sending bug. Does exit the script.
469  *
470  * @link    http://support.microsoft.com/kb/q176113/
471  * @author  Andreas Gohr <andi@splitbrain.org>
472  * @access  private
473  */
474 function crackerTrackerSendRawRedirect ($url) {
475         // Better remove any data by ctracker
476         unsetCtrackerData();
477
478         // always close the session
479         session_write_close();
480
481         // Revert entity &amp;
482         $url = str_replace('&amp;', '&', $url);
483
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)) &&
488                 ($matches[1] < 6)) {
489                 // Send the IIS header
490                 header('Refresh: 0;url=' . $url);
491         } else {
492                 // Send generic header
493                 header('Location: ' . $url);
494         }
495         exit();
496 }
497
498 // Removes all ctracker-related data from global space
499 function unsetCtrackerData () {
500         // Debug message
501         //* DEBUG: */ error_log(__FUNCTION__ . ': CALLED!');
502
503         // Unset all ctracker data
504         foreach (array(
505                         'ctracker_base_path',
506                         'ctracker_host',
507                         'ctracker_dbname',
508                         'ctracker_user',
509                         'ctracker_password',
510                         'ctracker_debug_enabled',
511                         'ctracker_email',
512                         'ctracker_whitelist',
513                         'ctracker_get_blacklist',
514                         'ctracker_post_blacklist',
515                         'ctracker_header',
516                         'ctracker_post_track',
517                         'ctracker_checkworm',
518                         'ctracker_check_post',
519                         'ctracker_last_sql',
520                         'ctracker_last_result',
521                         'ctracker_config',
522                         'ctracker_updates',
523                         'ctracker_language',
524                         'ctracker_localized',
525                         'ctracker_link',
526                 ) as $key) {
527                         // Unset it
528                         unset($GLOBALS[$key]);
529         } // END - foreach
530 }
531
532 // [EOF]
533 ?>