]> git.mxchange.org Git - ctracker.git/blob - libs/lib_general.php
e2d0005b27679af9d1c9a05bd421455e85785782
[ctracker.git] / libs / lib_general.php
1 <?php
2 /**
3  * General functions library
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.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.ship-simu.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 // Getter for ctracker_debug_enabled
77 function isCrackerTrackerDebug () {
78         // Is it set?
79         return ((isset($GLOBALS['ctracker_debug_enabled'])) && ($GLOBALS['ctracker_debug_enabled'] === true));
80 }
81
82 // Determines the real remote address
83 function determineCrackerTrackerRealRemoteAddress () {
84         // Initial value
85         $address = '0.0.0.0';
86
87         // Is a proxy in use?
88         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
89                 // Proxy was used
90                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
91         } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
92                 // Yet, another proxy
93                 $address = $_SERVER['HTTP_CLIENT_IP'];
94         } elseif (isset($_SERVER['REMOTE_ADDR'])) {
95                 // The regular address when no proxy was used
96                 $address = $_SERVER['REMOTE_ADDR'];
97         }
98
99         // This strips out the real address from proxy output
100         if (strstr($address, ',')) {
101                 $addressArray = explode(',', $address);
102                 $address = $addressArray[0];
103         } // END - if
104
105         // Return the result
106         return $address;
107 }
108
109 // Determine if a proxy was used
110 function isCrackerTrackerProxyUsed () {
111         // Check if specific entries are set
112         $proxyUsed = ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) || (isset($_SERVER['HTTP_CLIENT_IP'])));
113
114         // Return result
115         return $proxyUsed;
116 }
117
118 // Detects the user-agent string
119 function crackerTrackerUserAgent () {
120         // Default is 'unknown'
121         $ua = 'unknown';
122
123         // Is the entry there?
124         if (isset($_SERVER['HTTP_USER_AGENT'])) {
125                 // Then use it securely
126                 $ua = crackerTrackerSecureString($_SERVER['HTTP_USER_AGENT']);
127         } // END - if
128
129         // Return it
130         return $ua;
131 }
132
133 // Detects the script name
134 function crackerTrackerScriptName () {
135         // Is it there?
136         if (!isset($_SERVER['SCRIPT_NAME'])) {
137                 // Return NULL
138                 return NULL;
139         } // END - if
140
141         // Should always be there!
142         return crackerTrackerSecureString($_SERVER['SCRIPT_NAME']);
143 }
144
145 // Detects the query string
146 function crackerTrackerQueryString () {
147         // Is it there?
148         if (!isset($_SERVER['QUERY_STRING'])) {
149                 // Return NULL
150                 return NULL;
151         } // END - if
152
153         // Should always be there!
154         return crackerTrackerEscapeString($_SERVER['QUERY_STRING']);
155 }
156
157 // Detects the server's name
158 function crackerTrackerServerName () {
159         // Is it there?
160         if (!isset($_SERVER['SERVER_NAME'])) {
161                 // Return NULL
162                 return NULL;
163         } // END - if
164
165         // Should always be there!
166         return crackerTrackerSecureString($_SERVER['SERVER_NAME']);
167 }
168
169 // Detects the referer
170 function crackerTrackerReferer () {
171         // Default is a dash
172         $referer = '-';
173
174         // Is it there?
175         if (isset($_SERVER['HTTP_REFERER'])) {
176                 // Then use it securely
177                 $referer = crackerTrackerSecureString($_SERVER['HTTP_REFERER']);
178         } // END - if
179
180         // Return it
181         return $referer;
182 }
183
184 // Detects the scripts path
185 function crackerTrackerScriptPath () {
186         // Should always be there!
187         $path = dirname(crackerTrackerScriptName()) . '/';
188
189         // Return detected path
190         return $path;
191 }
192
193 // Detects wether we have SSL
194 function crackerTrackerSecured () {
195         // Detect it
196         $ssl = ((isset($_SERVER['HTTPS'])) && ($_SERVER['HTTPS'] != 'off'));
197
198         // Return result
199         return $ssl;
200 }
201
202 // Secures a string by escaping it and passing it through strip_tags,htmlentities-chain
203 function crackerTrackerSecureString ($str) {
204         // First escape it
205         $str = crackerTrackerEscapeString($str);
206
207         // Then pass it through the functions
208         $str = htmlentities(strip_tags($str), ENT_QUOTES);
209
210         // Return it
211         return $str;
212 }
213
214 // Is the file there and readable?
215 function isCrackerTrackerFileFound ($FQFN) {
216         // Simply check it
217         return ((file_exists($FQFN)) && (is_readable($FQFN)));
218 }
219
220 // Loads a given "template" (this is more an include file)
221 function crackerTrackerLoadTemplate ($template) {
222         // Create the full-qualified filename (FQFN)
223         $FQFN = sprintf("%s/templates/%s.tpl.php",
224                 dirname(__FILE__),
225                 $template
226         );
227
228         // Is this template found?
229         if (isCrackerTrackerFileFound($FQFN)) {
230                 // Detect language
231                 crackerTrackerLanguage();
232
233                 // Load it
234                 require_once($FQFN);
235         } else {
236                 // Not found, so die here
237                 crackerTrackerDie();
238         }
239 }
240
241 // Loads a given "template" (this is more an include file)
242 function crackerTrackerLoadLocalizedTemplate ($template) {
243         // Create the full-qualified filename (FQFN)
244         $FQFN = sprintf("%s/templates/%s/%s.tpl.php",
245                 dirname(__FILE__),
246                 getCrackerTrackerLanguage(),
247                 $template
248         );
249
250         // Is this template found?
251         if (isCrackerTrackerFileFound($FQFN)) {
252                 // Load it
253                 require_once($FQFN);
254         } else {
255                 // Not found, so die here
256                 crackerTrackerDie();
257         }
258 }
259
260 // Detects the browser's language file and tries to load it, fall-back on english!
261 function crackerTrackerLanguage () {
262         // Default is English
263         $GLOBALS['ctracker_language'] = 'en';
264         $weight = 1;
265
266         // Is the language string there?
267         if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
268                 // Then detect it
269                 foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
270                         // Split it again for q=x.x value
271                         $langArray = explode(';', $lang);
272
273                         // If there is an entry, we have a weight
274                         if ((isset($langArray[1])) && ($langArray[1] > $weight)) {
275                                 // Use this language/weight instead
276                                 $GLOBALS['ctracker_language'] = $langArray[0];
277                                 $weight   = $langArray[1];
278                         } // END - if
279                 } // END - foreach
280         } // END - if
281
282         // Construct FQFN
283         $FQFN = sprintf("%s/language/%s.php",
284                 dirname(__FILE__),
285                 getCrackerTrackerLanguage()
286         );
287
288         // Is it not there, switch to "en"
289         if ((getCrackerTrackerLanguage() != 'en') && (!isCrackerTrackerFileFound($FQFN))) {
290                 // English is default!
291                 $GLOBALS['ctracker_language'] = 'en';
292
293                 // Construct FQFN again
294                 $FQFN = sprintf("%s/language/en.php",
295                         dirname(__FILE__)
296                 );
297         } // END - if
298
299         // Load the language file
300         require($FQFN);
301 }
302
303 // Loads a given email template and passes through $content
304 function crackerTrackerLoadEmailTemplate ($template, array $content = array(), $language = null) {
305         // Init language
306         crackerTrackerLanguage();
307
308         // Generate the FQFN
309         $FQFN = sprintf("%s/mails/%s/%s.tpl",
310                 dirname(__FILE__),
311                 getCrackerTrackerLanguage($language),
312                 $template
313         );
314
315         // So is the file there?
316         if (isCrackerTrackerFileFound($FQFN)) {
317                 // Init result
318                 $result = 'No result from template ' . $template . '. Please report this at http://forum.ship-simu.org Thank you.';
319
320                 // Then load it
321                 eval('$result = "' . crackerTrackerCompileCode(file_get_contents($FQFN)) . '";');
322
323                 // Return the result
324                 return $result;
325         } else {
326                 // Not found
327                 crackerTrackerDie();
328         }
329 }
330
331 // Getter for message
332 function getCrackerTrackerLocalized ($message) {
333         // Default message
334         $output = '!' . $message . '!';
335
336         // Is the language string there?
337         if (isset($GLOBALS['ctracker_localized'][$message])) {
338                 // Use this instead
339                 $output = $GLOBALS['ctracker_localized'][$message];
340         } // END - if
341
342         // Return it
343         return $output;
344 }
345
346 // Tries to find a message and outputs it
347 function crackerTrackerOutputLocalized ($message) {
348         // Output it
349         print getCrackerTrackerLocalized($message);
350 }
351
352 // Compiles the given code
353 function crackerTrackerCompileCode ($code) {
354         // Find all $content[foo]
355         preg_match_all('/\$(content|GLOBALS)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
356
357         // Replace " with {QUOTE}
358         $code = str_replace('"', '{QUOTE}', $code);
359
360         // Replace all
361         foreach ($matches[0] as $key=>$match) {
362                 // Replace it
363                 if (substr($match, 0, 8) == '$GLOBALS') {
364                         // $GLOBALS
365                         $code = str_replace($match, "\" . \$GLOBALS['" . $matches[4][$key] . "'] . \"", $code);
366                 } elseif (substr($match, 0, 8) == '$content') {
367                         // $content
368                         $code = str_replace($match, "\" . \$content['" . $matches[4][$key] . "'] . \"", $code);
369                 }
370         } // END - foreach
371
372         // Return it
373         return $code;
374 }
375
376 // "Getter" for language
377 function getCrackerTrackerLanguage ($lang = null) {
378         // Default is from browser
379         $language = $GLOBALS['ctracker_language'];
380
381         // Is $lang set?
382         if (!is_null($lang)) {
383                 // Then use this instead
384                 $language = $lang;
385         } // END - if
386
387         // Return it
388         return $language;
389 }
390
391 // "Getter" for ticket id
392 function getCrackerTrackerTicketId () {
393         // Default is zero
394         $id = 0;
395
396         // Is it set?
397         if (isset($GLOBALS['ctracker_last_ticket']['ctracker_ticket'])) {
398                 // Then use it
399                 $id = $GLOBALS['ctracker_last_ticket']['ctracker_ticket'];
400         } // END - if
401
402         // Return the number
403         return $id;
404 }
405
406 // Sends a cookie to the user that he would not see this security warning again
407 function sendCrackerTrackerCookie () {
408         // Set the cookie
409         // @TODO Why can't domain be set to value from crackerTrackerServerName() ?
410         setcookie('ctracker_ticket', getCrackerTrackerTicketId(), (time() + 60*60*24), '/', '', crackerTrackerSecured(), true);
411         $_COOKIE['ctracker_ticket'] = getCrackerTrackerTicketId();
412 }
413
414 // Is the cookie set?
415 function ifCrackerTrackerCookieIsSet () {
416         // Is it set and valid?
417         return ((isset($_COOKIE['ctracker_ticket'])) && ($_COOKIE['ctracker_ticket'] > 0));
418 }
419
420 // Redirects to the same URL
421 function crackerTrackerRedirectSameUrl () {
422         // Construct the url
423         $url = '://' . crackerTrackerServerName() . crackerTrackerScriptName() . '?' . crackerTrackerQueryString();
424
425         // Do we have SSL?
426         if (crackerTrackerSecured()) {
427                 // HTTPS
428                 $url = 'https' . $url;
429         } else {
430                 // HTTP
431                 $url = 'http' . $url;
432         }
433
434         // And redirect
435         crackerTrackerSendRawRedirect($url);
436 }
437
438 /**
439  * Send a HTTP redirect to the browser. This function was taken from DokuWiki
440  * (GNU GPL 2; http://www.dokuwiki.org) and modified to fit into this script.
441  *
442  * Works arround Microsoft IIS cookie sending bug. Does exit the script.
443  *
444  * @link    http://support.microsoft.com/kb/q176113/
445  * @author  Andreas Gohr <andi@splitbrain.org>
446  * @access  private
447  */
448 function crackerTrackerSendRawRedirect ($url) {
449         // Better remove any data by ctracker
450         unsetCtrackerData();
451
452         // always close the session
453         session_write_close();
454
455         // Revert entity &amp;
456         $url = str_replace('&amp;', '&', $url);
457
458         // check if running on IIS < 6 with CGI-PHP
459         if ((isset($_SERVER['SERVER_SOFTWARE'])) && (isset($_SERVER['GATEWAY_INTERFACE'])) &&
460                 (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
461                 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
462                 ($matches[1] < 6)) {
463                 // Send the IIS header
464                 header('Refresh: 0;url=' . $url);
465         } else {
466                 // Send generic header
467                 header('Location: ' . $url);
468         }
469         exit();
470 }
471
472 // Removes all ctracker-related data from global space
473 function unsetCtrackerData () {
474         // Unset all
475         foreach (array(
476                         'ctracker_host',
477                         'ctracker_dbname',
478                         'ctracker_user',
479                         'ctracker_password',
480                         'ctracker_debug_enabled',
481                         'ctracker_email',
482                         'ctracker_whitelist',
483                         'ctracker_get_blacklist',
484                         'ctracker_post_blacklist',
485                         'ctracker_header',
486                         'ctracker_post_track',
487                         'ctracker_checkworm',
488                         'ctracker_check_post',
489                         'ctracker_last_sql',
490                         'ctracker_last_result',
491                         'ctracker_config',
492                         'ctracker_updates',
493                 ) as $key) {
494                         // Unset it
495                         unset($GLOBALS[$key]);
496         } // END - foreach
497 }
498
499 // [EOF]
500 ?>