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