]> git.mxchange.org Git - ctracker.git/blob - libs/lib_general.php
84dd1bf0f7818a73db7c5189da467e2dc74f3260
[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 = getenv('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(urldecode($_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(urldecode($_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', dirname(__FILE__));
295         } // END - if
296
297         // Load the language file
298         require($FQFN);
299 }
300
301 // Loads a given email template and passes through $content
302 function crackerTrackerLoadEmailTemplate ($template, array $content = array(), $language = NULL) {
303         // Init language
304         crackerTrackerLanguage();
305
306         // Generate the FQFN
307         $FQFN = sprintf('%s/mails/%s/%s.tpl',
308                 dirname(__FILE__),
309                 getCrackerTrackerLanguage($language),
310                 $template
311         );
312
313         // So is the file there?
314         if (isCrackerTrackerFileFound($FQFN)) {
315                 // Init result
316                 $result = 'No result from template ' . $template . '. Please report this at http://forum.ship-simu.org Thank you.';
317
318                 // Then load it
319                 eval('$result = "' . crackerTrackerCompileCode(file_get_contents($FQFN)) . '";');
320
321                 // Return the result
322                 return $result;
323         } else {
324                 // Not found
325                 crackerTrackerDie();
326         }
327 }
328
329 // Getter for message
330 function getCrackerTrackerLocalized ($message) {
331         // Default message
332         $output = '!' . $message . '!';
333
334         // Is the language string there?
335         if (isset($GLOBALS['ctracker_localized'][$message])) {
336                 // Use this instead
337                 $output = $GLOBALS['ctracker_localized'][$message];
338         } // END - if
339
340         // Return it
341         return $output;
342 }
343
344 // Tries to find a message and outputs it
345 function crackerTrackerOutputLocalized ($message) {
346         // Output it
347         print getCrackerTrackerLocalized($message);
348 }
349
350 // Compiles the given code
351 function crackerTrackerCompileCode ($code) {
352         // Find all $content[foo]
353         preg_match_all('/\$(content|GLOBALS)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
354
355         // Replace " with {QUOTE}
356         $code = str_replace('"', '{QUOTE}', $code);
357
358         // Replace all
359         foreach ($matches[0] as $key=>$match) {
360                 // Replace it
361                 if (substr($match, 0, 8) == '$GLOBALS') {
362                         // $GLOBALS
363                         $code = str_replace($match, "\" . \$GLOBALS['" . $matches[4][$key] . "'] . \"", $code);
364                 } elseif (substr($match, 0, 8) == '$content') {
365                         // $content
366                         $code = str_replace($match, "\" . \$content['" . $matches[4][$key] . "'] . \"", $code);
367                 }
368         } // END - foreach
369
370         // Return it
371         return $code;
372 }
373
374 // "Getter" for language
375 function getCrackerTrackerLanguage ($lang = NULL) {
376         // Default is from browser
377         $language = $GLOBALS['ctracker_language'];
378
379         // Is $lang set?
380         if (!is_null($lang)) {
381                 // Then use this instead
382                 $language = $lang;
383         } // END - if
384
385         // Return it
386         return $language;
387 }
388
389 // "Getter" for ticket id
390 function getCrackerTrackerTicketId () {
391         // Default is zero
392         $id = 0;
393
394         // Is it set?
395         if (isset($GLOBALS['ctracker_last_ticket']['ctracker_ticket'])) {
396                 // Then use it
397                 $id = $GLOBALS['ctracker_last_ticket']['ctracker_ticket'];
398         } // END - if
399
400         // Return the number
401         return $id;
402 }
403
404 // Sends a cookie to the user that he would not see this security warning again
405 function sendCrackerTrackerCookie () {
406         // Set the cookie
407         // @TODO Why can't domain be set to value from crackerTrackerServerName() ?
408         setcookie('ctracker_ticket', getCrackerTrackerTicketId(), (time() + 60*60*24), '/', '', crackerTrackerSecured(), TRUE);
409         $_COOKIE['ctracker_ticket'] = getCrackerTrackerTicketId();
410 }
411
412 // Is the cookie set?
413 function ifCrackerTrackerCookieIsSet () {
414         // Is it set and valid?
415         return ((isset($_COOKIE['ctracker_ticket'])) && ($_COOKIE['ctracker_ticket'] > 0));
416 }
417
418 // Redirects to the same URL
419 function crackerTrackerRedirectSameUrl () {
420         // Construct the url
421         $url = '://' . crackerTrackerServerName() . crackerTrackerScriptName() . '?' . crackerTrackerQueryString();
422
423         // Do we have SSL?
424         if (crackerTrackerSecured()) {
425                 // HTTPS
426                 $url = 'https' . $url;
427         } else {
428                 // HTTP
429                 $url = 'http' . $url;
430         }
431
432         // And redirect
433         crackerTrackerSendRawRedirect($url);
434 }
435
436 /**
437  * Send a HTTP redirect to the browser. This function was taken from DokuWiki
438  * (GNU GPL 2; http://www.dokuwiki.org) and modified to fit into this script.
439  *
440  * Works arround Microsoft IIS cookie sending bug. Does exit the script.
441  *
442  * @link    http://support.microsoft.com/kb/q176113/
443  * @author  Andreas Gohr <andi@splitbrain.org>
444  * @access  private
445  */
446 function crackerTrackerSendRawRedirect ($url) {
447         // Better remove any data by ctracker
448         unsetCtrackerData();
449
450         // always close the session
451         session_write_close();
452
453         // Revert entity &amp;
454         $url = str_replace('&amp;', '&', $url);
455
456         // check if running on IIS < 6 with CGI-PHP
457         if ((isset($_SERVER['SERVER_SOFTWARE'])) && (isset($_SERVER['GATEWAY_INTERFACE'])) &&
458                 (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== FALSE) &&
459                 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
460                 ($matches[1] < 6)) {
461                 // Send the IIS header
462                 header('Refresh: 0;url=' . $url);
463         } else {
464                 // Send generic header
465                 header('Location: ' . $url);
466         }
467         exit();
468 }
469
470 // Removes all ctracker-related data from global space
471 function unsetCtrackerData () {
472         // Unset all ctracker data
473         foreach (array(
474                         'ctracker_host',
475                         'ctracker_dbname',
476                         'ctracker_user',
477                         'ctracker_password',
478                         'ctracker_debug_enabled',
479                         'ctracker_email',
480                         'ctracker_whitelist',
481                         'ctracker_get_blacklist',
482                         'ctracker_post_blacklist',
483                         'ctracker_header',
484                         'ctracker_post_track',
485                         'ctracker_checkworm',
486                         'ctracker_check_post',
487                         'ctracker_last_sql',
488                         'ctracker_last_result',
489                         'ctracker_config',
490                         'ctracker_updates',
491                         'ctracker_language',
492                         'ctracker_localized',
493                         'ctracker_link',
494                 ) as $key) {
495                         // Unset it
496                         unset($GLOBALS[$key]);
497         } // END - foreach
498 }
499
500 // [EOF]
501 ?>