New naming convention applied to many functions, see #118 for details
[mailer.git] / inc / functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 08/25/2003 *
4  * ===============                              Last change: 11/29/2005 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : functions.php                                    *
8  * -------------------------------------------------------------------- *
9  * Short description : Many non-MySQL functions (also file access)      *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
41         require($INC);
42 }
43
44 // Output HTML code directly or "render" it. You addionally switch the new-line character off
45 function OUTPUT_HTML ($HTML, $newLine = true) {
46         // Some global variables
47         global $OUTPUT;
48
49         // Do we have HTML-Code here?
50         if (!empty($HTML)) {
51                 // Yes, so we handle it as you have configured
52                 switch (constant('OUTPUT_MODE'))
53                 {
54                 case "render":
55                         // That's why you don't need any \n at the end of your HTML code... :-)
56                         if (constant('_OB_CACHING') == "on") {
57                                 // Output into PHP's internal buffer
58                                 outputRawCode($HTML);
59
60                                 // That's why you don't need any \n at the end of your HTML code... :-)
61                                 if ($newLine) echo "\n";
62                         } else {
63                                 // Render mode for old or lame servers...
64                                 $OUTPUT .= $HTML;
65
66                                 // That's why you don't need any \n at the end of your HTML code... :-)
67                                 if ($newLine) $OUTPUT .= "\n";
68                         }
69                         break;
70
71                 case 'direct':
72                         // If we are switching from render to direct output rendered code
73                         if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != "on")) { outputRawCode($OUTPUT); $OUTPUT = ''; }
74
75                         // The same as above... ^
76                         outputRawCode($HTML);
77                         if ($newLine) echo "\n";
78                         break;
79
80                 default:
81                         // Huh, something goes wrong or maybe you have edited config.php ???
82                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
83                         app_die(__FUNCTION__, __LINE__, "<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
84                         break;
85                 }
86         } elseif ((constant('_OB_CACHING') == "on") && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
87                 // Headers already sent?
88                 if (headers_sent()) {
89                         // Log this error
90                         DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
91
92                         // Trigger an user error
93                         debug_report_bug("Headers are already sent!");
94                 } // END - if
95
96                 // Output cached HTML code
97                 $OUTPUT = ob_get_contents();
98
99                 // Clear output buffer for later output if output is found
100                 if (!empty($OUTPUT)) {
101                         clearOutputBuffer();
102                 } // END - if
103
104                 // Send HTTP header
105                 header("HTTP/1.1 200");
106
107                 // Used later
108                 $now = gmdate('D, d M Y H:i:s') . ' GMT';
109
110                 // General headers for no caching
111                 header("Expired: " . $now); // RFC2616 - Section 14.21
112                 header("Last-Modified: " . $now);
113                 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
114                 header("Pragma: no-cache"); // HTTP/1.0
115                 header("Connection: Close");
116
117                 // Extension 'rewrite' installed?
118                 if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
119                         $OUTPUT = rewriteLinksInCode($OUTPUT);
120                 } // END - if
121
122                 // Compile and run finished rendered HTML code
123                 while (strpos($OUTPUT, '{!') > 0) {
124                         // Prepare the content and eval() it...
125                         $newContent = '';
126                         $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
127                         eval($eval);
128
129                         // Was that eval okay?
130                         if (empty($newContent)) {
131                                 // Something went wrong!
132                                 app_die(__FUNCTION__, __LINE__, "Evaluation error:<pre>".htmlentities($eval)."</pre>");
133                         } // END - if
134                         $OUTPUT = $newContent;
135                 } // END - while
136
137                 // Output code here, DO NOT REMOVE! ;-)
138                 outputRawCode($OUTPUT);
139         } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
140                 // Rewrite links when rewrite extension is active
141                 if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
142                         $OUTPUT = rewriteLinksInCode($OUTPUT);
143                 } // END - if
144
145                 // Compile and run finished rendered HTML code
146                 while (strpos($OUTPUT, '{!') > 0) {
147                         $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
148                         eval($eval);
149                 } // END - while
150
151                 // Output code here, DO NOT REMOVE! ;-)
152                 outputRawCode($OUTPUT);
153         }
154 }
155
156 // Output the raw HTML code
157 function outputRawCode ($HTML) {
158         // Output stripped HTML code to avoid broken JavaScript code, etc.
159         echo stripslashes(stripslashes($HTML));
160
161         // Flush the output if only constant('_OB_CACHING') is not "on"
162         if (constant('_OB_CACHING') != "on") {
163                 // Flush it
164                 flush();
165         } // END - if
166 }
167
168 // Init fatal message array
169 function initFatalMessages () {
170         $GLOBALS['fatal_messages'] = array();
171 }
172
173 // Getter for whole fatal error messages
174 function getFatalArray () {
175         return $GLOBALS['fatal_messages'];
176 }
177
178 // Add a fatal error message to the queue array
179 function addFatalMessage ($F, $L, $message, $extra='') {
180         if (is_array($extra)) {
181                 // Multiple extras for a message with masks
182                 $message = call_user_func_array('sprintf', $extra);
183         } elseif (!empty($extra)) {
184                 // $message is text with a mask plus extras to insert into the text
185                 $message = sprintf($message, $extra);
186         }
187
188         // Add message to $GLOBALS['fatal_messages']
189         $GLOBALS['fatal_messages'][] = $message;
190
191         // Log fatal messages away
192         DEBUG_LOG($F, $L, " message={$message}");
193 }
194
195 // Getter for total fatal message count
196 function getTotalFatalErrors () {
197         // Init coun
198         $count = 0;
199
200         // Do we have at least the first entry?
201         if (!empty($GLOBALS['fatal_messages'][0])) {
202                 // Get total count
203                 $count = count($GLOBALS['fatal_messages']);
204         } // END - if
205
206         // Return value
207         return $count;
208 }
209
210 // Load a template file and return it's content (only it's name; do not use ' or ")
211 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
212         // Add more variables which you want to use in your template files
213         global $DATA, $username;
214
215         // Get whole config array
216         $_CONFIG = getConfigArray();
217
218         // Make all template names lowercase
219         $template = strtolower($template);
220
221         // Count the template load
222         incrementConfigEntry('num_templates');
223
224         // Prepare IP number and User Agent
225         $REMOTE_ADDR     = detectRemoteAddr();
226         if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
227         $HTTP_USER_AGENT = detectUserAgent();
228
229         // Init some data
230         $ret = '';
231         if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
232
233         // @DEPRECATED Try to rewrite the if() condition
234         if ($template == "member_support_form") {
235                 // Support request of a member
236                 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
237                         array(getUserId()), __FUNCTION__, __LINE__);
238
239                 // Is content an array?
240                 if (is_array($content)) {
241                         // Merge data
242                         $content = merge_array($content, SQL_FETCHARRAY($result));
243
244                         // Translate gender
245                         $content['gender'] = translateGender($content['gender']);
246                 } else {
247                         // @DEPRECATED
248                         // @TODO Fine all templates which are using these direct variables and rewrite them.
249                         // @TODO After this step is done, this else-block is history
250                         list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
251
252                         // Translate gender
253                         $gender = translateGender($gender);
254                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
255                 }
256
257                 // Free result
258                 SQL_FREERESULT($result);
259         } // END - if
260
261         // Generate date/time string
262         $date_time = generateDateTime(time(), "1");
263
264         // Base directory
265         $basePath = sprintf("%stemplates/%s/html/", constant('PATH'), getLanguage());
266         $mode = '';
267
268         // Check for admin/guest/member templates
269         if (strpos($template, "admin_") > -1) {
270                 // Admin template found
271                 $mode = "admin/";
272         } elseif (strpos($template, "guest_") > -1) {
273                 // Guest template found
274                 $mode = "guest/";
275         } elseif (strpos($template, "member_") > -1) {
276                 // Member template found
277                 $mode = "member/";
278         } elseif (strpos($template, "install_") > -1) {
279                 // Installation template found
280                 $mode = "install/";
281         } elseif (strpos($template, "ext_") > -1) {
282                 // Extension template found
283                 $mode = "ext/";
284         } elseif (strpos($template, "la_") > -1) {
285                 // "Logical-area" template found
286                 $mode = "la/";
287         } else {
288                 // Test for extension
289                 $test = substr($template, 0, strpos($template, "_"));
290                 if (EXT_IS_ACTIVE($test)) {
291                         // Set extra path to extension's name
292                         $mode = $test.'/';
293                 }
294         }
295
296         ////////////////////////
297         // Generate file name //
298         ////////////////////////
299         $FQFN = $basePath.$mode.$template.".tpl";
300
301         if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($mode == "guest/") || ($mode == "member/") || ($mode == "admin/"))) {
302                 // Select what depended header/footer template file for admin/guest/member area
303                 $file2 = sprintf("%s%s%s_%s.tpl",
304                         $basePath,
305                         $mode,
306                         $template,
307                         SQL_ESCAPE($GLOBALS['what'])
308                 );
309
310                 // Probe for it...
311                 if (isFileReadable($file2)) $FQFN = $file2;
312
313                 // Remove variable from memory
314                 unset($file2);
315         }
316
317         // Does the special template exists?
318         if (!isFileReadable($FQFN)) {
319                 // Reset to default template
320                 $FQFN = $basePath.$template.".tpl";
321         } // END - if
322
323         // Now does the final template exists?
324         if (isFileReadable($FQFN)) {
325                 // The local file does exists so we load it. :)
326                 $tmpl_file = readFromFile($FQFN);
327
328                 // Replace ' to our own chars to preventing them being quoted
329                 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
330
331                 // Do we have to compile the code?
332                 $ret = '';
333                 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
334                         // Okay, compile it!
335                         $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
336                         eval($tmpl_file);
337                 } else {
338                         // Simply return loaded code
339                         $ret = $tmpl_file;
340                 }
341
342                 // Add surrounding HTML comments to help finding bugs faster
343                 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
344         } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
345                 // Only admins shall see this warning or when installation mode is active
346                 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
347 (".basename($FQFN).")<br />
348 <br />
349 ".TEMPLATE_CONTENT."
350 <pre>".print_r($content, true)."</pre>
351 ".TEMPLATE_DATA."
352 <pre>".print_r($DATA, true)."</pre>
353 <br /><br />";
354         }
355
356         // Remove content and data
357         unset($content);
358         unset($DATA);
359
360         // Do we have some content to output or return?
361         if (!empty($ret)) {
362                 // Not empty so let's put it out! ;)
363                 if ($return === true) {
364                         // Return the HTML code
365                         return $ret;
366                 } else {
367                         // Output direct
368                         OUTPUT_HTML($ret);
369                 }
370         } elseif (isDebugModeEnabled()) {
371                 // Warning, empty output!
372                 return "E:".$template."<br />\n";
373         }
374 }
375
376 // Send mail out to an email address
377 function sendEmail($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '') {
378         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />\n";
379
380         // Compile subject line (for POINTS constant etc.)
381         $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
382         eval($eval);
383
384         // Set from header
385         if ((!eregi("@", $toEmail)) && ($toEmail > 0)) {
386                 // Value detected, is the message extension installed?
387                 if (EXT_IS_ACTIVE("msg")) {
388                         ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
389                         return;
390                 } else {
391                         // Load email address
392                         $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($toEmail)), __FUNCTION__, __LINE__);
393                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
394
395                         // Does the user exist?
396                         if (SQL_NUMROWS($result_email)) {
397                                 // Load email address
398                                 list($toEmail) = SQL_FETCHROW($result_email);
399                         } else {
400                                 // Set webmaster
401                                 $toEmail = constant('WEBMASTER');
402                         }
403
404                         // Free result
405                         SQL_FREERESULT($result_email);
406                 }
407         } elseif ("$toEmail" == '0') {
408                 // Is the webmaster!
409                 $toEmail = constant('WEBMASTER');
410         }
411         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
412
413         // Check for PHPMailer or debug-mode
414         if (!CHECK_PHPMAILER_USAGE()) {
415                 // Not in PHPMailer-Mode
416                 if (empty($mailHeader)) {
417                         // Load email header template
418                         $mailHeader = LOAD_EMAIL_TEMPLATE("header");
419                 } else {
420                         // Append header
421                         $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
422                 }
423         } elseif (isDebugModeEnabled()) {
424                 if (empty($mailHeader)) {
425                         // Load email header template
426                         $mailHeader = LOAD_EMAIL_TEMPLATE("header");
427                 } else {
428                         // Append header
429                         $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
430                 }
431         }
432
433         // Compile "TO"
434         $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
435         eval($eval);
436
437         // Compile "MSG"
438         $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
439         eval($eval);
440
441         // Fix HTML parameter (default is no!)
442         if (empty($HTML)) $HTML = 'N';
443         if (isDebugModeEnabled()) {
444                 // In debug mode we want to display the mail instead of sending it away so we can debug this part
445                 print("<pre>
446 ".htmlentities(trim($mailHeader))."
447 To      : ".$toEmail."
448 Subject : ".$subject."
449 Message : ".$message."
450 </pre>\n");
451         } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE('html_mail'))) {
452                 // Send mail as HTML away
453                 SEND_HTML_EMAIL($toEmail, $subject, $message, $mailHeader);
454         } elseif (!empty($toEmail)) {
455                 // Send Mail away
456                 SEND_RAW_EMAIL($toEmail, $subject, $message, $mailHeader);
457         } elseif ($HTML == 'N') {
458                 // Problem found!
459                 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$subject, $message, $mailHeader);
460         }
461 }
462
463 // Check if legacy or PHPMailer command
464 // @TODO Rewrite this to an extension 'smtp'
465 // @private
466 function CHECK_PHPMAILER_USAGE() {
467         return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (constant('SMTP_HOSTNAME') != '') && (constant('SMTP_USER') != ''));
468 }
469
470 /*
471  * Send out a raw email with PHPMailer class or legacy mail() command
472  */
473 function SEND_RAW_EMAIL ($toEmail, $subject, $msg, $from) {
474         // Shall we use PHPMailer class or legacy mode?
475         if (CHECK_PHPMAILER_USAGE()) {
476                 // Use PHPMailer class with SMTP enabled
477                 loadIncludeOnce("inc/phpmailer/class.phpmailer.php");
478                 loadIncludeOnce("inc/phpmailer/class.smtp.php");
479
480                 // get new instance
481                 $mail = new PHPMailer();
482                 $mail->PluginDir  = sprintf("%sinc/phpmailer/", constant('PATH'));
483
484                 $mail->IsSMTP();
485                 $mail->SMTPAuth   = true;
486                 $mail->Host       = constant('SMTP_HOSTNAME');
487                 $mail->Port       = 25;
488                 $mail->Username   = constant('SMTP_USER');
489                 $mail->Password   = constant('SMTP_PASSWORD');
490                 if (empty($from)) {
491                         $mail->From = constant('WEBMASTER');
492                 } else {
493                         $mail->From = $from;
494                 }
495                 $mail->FromName   = constant('MAIN_TITLE');
496                 $mail->Subject    = $subject;
497                 if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($msg) != $msg)) {
498                         $mail->Body       = $msg;
499                         $mail->AltBody    = "Your mail program required HTML support to read this mail!";
500                         $mail->WordWrap   = 70;
501                         $mail->IsHTML(true);
502                 } else {
503                         $mail->Body       = decodeEntities($msg);
504                 }
505                 $mail->AddAddress($toEmail, '');
506                 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
507                 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
508                 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
509                 $mail->Send();
510         } else {
511                 // Use legacy mail() command
512                 @mail($toEmail, $subject, decodeEntities($msg), $from);
513         }
514 }
515
516 // Generate a password in a specified length or use default password length
517 function generatePassword ($LEN = 0) {
518         // Auto-fix invalid length of zero
519         if ($LEN == 0) $LEN = getConfig('pass_len');
520
521         // Initialize array with all allowed chars
522         $ABC = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,-,+,_,/');
523
524         // Start creating password
525         $PASS = '';
526         for ($i = 0; $i < $LEN; $i++) {
527                 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
528         } // END - for
529
530         // When the size is below 40 we can also add additional security by scrambling
531         // it. Otherwise we may corrupt hashes
532         if (strlen($PASS) <= 40) {
533                 // Also scramble the password
534                 $PASS = scrambleString($PASS);
535         } // END - if
536
537         // Return the password
538         return $PASS;
539 }
540
541 // Generates a human-readable timestamp from the Uni* stamp
542 function generateDateTime ($time, $mode = '0') {
543         // Filter out numbers
544         $time = bigintval($time);
545
546         // If the stamp is zero it mostly didn't "happen"
547         if ($time == 0) {
548                 // Never happend
549                 return getMessage('NEVER_HAPPENED');
550         } // END - if
551
552         switch (getLanguage())
553         {
554         case 'de': // German date / time format
555                 switch ($mode) {
556                         case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
557                         case '1': $ret = strtolower(date("d.m.Y - H:i", $time)); break;
558                         case '2': $ret = date("d.m.Y|H:i", $time); break;
559                         case '3': $ret = date("d.m.Y", $time); break;
560                         default:
561                                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
562                                 break;
563                 }
564                 break;
565
566         default: // Default is the US date / time format!
567                 switch ($mode) {
568                         case '0': $ret = date("r", $time); break;
569                         case '1': $ret = date("Y-m-d - g:i A", $time); break;
570                         case '2': $ret = date("y-m-d|H:i", $time); break;
571                         case '3': $ret = date("y-m-d", $time); break;
572                         default:
573                                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
574                                 break;
575                 }
576         }
577         return $ret;
578 }
579
580 // Translates Y/N to yes/no
581 function translateYesNo ($yn) {
582         // Default
583         $translated = "??? (".$yn.")";
584         switch ($yn) {
585                 case 'Y': $translated = getMessage('YES'); break;
586                 case 'N': $translated = getMessage('NO'); break;
587                 default:
588                         // Log unknown value
589                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
590                         break;
591         }
592
593         // Return it
594         return $translated;
595 }
596
597 // Translates the "pool type" into human-readable
598 function translatePoolType ($type) {
599         // Default?type is unknown
600         $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
601
602         // Generate constant
603         $constName = sprintf("POOL_TYPE_%s", $type);
604
605         // Does it exist?
606         if (defined($constName)) {
607                 // Then use it
608                 $translated = getMessage($constName);
609         } // END - if
610
611         // Return "translation"
612         return $translated;
613 }
614
615 // Translates the american decimal dot into a german comma
616 function translateComma ($dotted, $cut = true, $max = 0) {
617         // Default is 3 you can change this in admin area "Misc -> Misc Options"
618         if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
619
620         // Use from config is default
621         $maxComma = getConfig('max_comma');
622
623         // Use from parameter?
624         if ($max > 0) $maxComma = $max;
625
626         // Cut zeros off?
627         if (($cut) && ($max == 0)) {
628                 // Test for commata if in cut-mode
629                 $com = explode('.', $dotted);
630                 if (count($com) < 2) {
631                         // Don't display commatas even if there are none... ;-)
632                         $maxComma = 0;
633                 }
634         } // END - if
635
636         // Debug log
637         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
638
639         // Translate it now
640         switch (getLanguage()) {
641         case 'de':
642                 $dotted = number_format($dotted, $maxComma, ',', '.');
643                 break;
644
645         default:
646                 $dotted = number_format($dotted, $maxComma, '.', ',');
647                 break;
648         }
649
650         // Return translated value
651         return $dotted;
652 }
653
654 // Translate Uni*-like gender to human-readable
655 function translateGender ($gender) {
656         // Default
657         $ret = '!' . $gender . '!';
658
659         // Male/female or company?
660         switch ($gender) {
661                 case 'M': $ret = getMessage('GENDER_M'); break;
662                 case 'F': $ret = getMessage('GENDER_F'); break;
663                 case 'C': $ret = getMessage('GENDER_C'); break;
664                 default:
665                         // Log unknown gender
666                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
667                         break;
668         }
669
670         // Return translated gender
671         return $ret;
672 }
673
674 // "Translates" the user status
675 function translateUserStatus ($status) {
676         switch ($status)
677         {
678         case 'UNCONFIRMED':
679         case 'CONFIRMED':
680         case 'LOCKED':
681                 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
682                 break;
683
684         case '':
685         case null:
686                 $ret = getMessage('ACCOUNT_DELETED');
687                 break;
688
689         default:
690                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
691                 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
692                 break;
693         }
694
695         // Return it
696         return $ret;
697 }
698
699 // Generates an URL for the dereferer
700 function DEREFERER ($URL) {
701         // Don't de-refer our own links!
702         if (substr($URL, 0, strlen(constant('URL'))) != constant('URL')) {
703                 // De-refer this link
704                 $URL = 'modules.php?module=loader&amp;url=' . encodeString(compileUriCode($URL));
705         } // END - if
706
707         // Return link
708         return $URL;
709 }
710
711 // Generates an URL for the frametester
712 function FRAMETESTER ($URL) {
713         // Prepare frametester URL
714         $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&amp;url=%s",
715                 encodeString(compileUriCode($URL))
716         );
717         return $frametesterUrl;
718 }
719
720 // Count entries from e.g. a selection box
721 function countSelection ($array) {
722         $ret = 0;
723         if (is_array($array)) {
724                 foreach ($array as $key => $selected) {
725                         if (!empty($selected)) $ret++;
726                 }
727         }
728         return $ret;
729 }
730
731 // Wrapper for $_POST['sel']
732 function countPostSelection () {
733         return countSelection(REQUEST_POST('sel'));
734 }
735
736 // Generate XHTML code for the CAPTCHA
737 function generateCaptchaCode ($code, $type, $DATA, $uid) {
738         return '<IMG border="0" alt="Code" src="{!URL!}/mailid_top.php?uid=' . $uid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '" />';
739 }
740
741 // "Getter" for language
742 function getLanguage () {
743         // Set default return value to default language from config
744         $ret = constant('DEFAULT_LANG');
745
746         // Init variable
747         $lang = '';
748
749         // Is the variable set
750         if (REQUEST_ISSET_GET(('mx_lang'))) {
751                 // Accept only first 2 chars
752                 $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
753         } elseif (isset($GLOBALS['cache_array']['language'])) {
754                 // Use cached
755                 $ret = $GLOBALS['cache_array']['language'];
756         } elseif (!empty($lang)) {
757                 // Check if main language file does exist
758                 if (isFileReadable(constant('PATH').'inc/language/'.$lang.'.php')) {
759                         // Okay found, so let's update cookies
760                         setLanguage($lang);
761                 }
762         } elseif (!isSessionVariableSet('mx_lang')) {
763                 // Return stored value from cookie
764                 $ret = getSession('mx_lang');
765
766                 // Fixes a warning before the session has the mx_lang constant
767                 if (empty($ret)) $ret = constant('DEFAULT_LANG');
768         }
769
770         // Cache entry
771         $GLOBALS['cache_array']['language'] = $ret;
772
773         // Return value
774         return $ret;
775 }
776
777 // "Setter" for language
778 function setLanguage ($lang) {
779         // Accept only first 2 chars!
780         $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
781
782         // Set cookie
783         setSession('mx_lang', $lang);
784 }
785
786 // Loads an email template and compiles it
787 function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
788         global $DATA, $_CONFIG;
789
790         // Make sure all template names are lowercase!
791         $template = strtolower($template);
792
793         // Default 'nickname' if extension is not installed
794         $nick = '---';
795
796         // Prepare IP number and User Agent
797         $REMOTE_ADDR     = detectRemoteAddr();
798         $HTTP_USER_AGENT = detectUserAgent();
799
800         // Default admin
801         $ADMIN = constant('MAIN_TITLE');
802
803         // Is the admin logged in?
804         if (IS_ADMIN()) {
805                 // Get admin id
806                 $aid = getCurrentAdminId();
807
808                 // Load Admin data
809                 $ADMIN = getAdminEmail($aid);
810         } // END - if
811
812         // Neutral email address is default
813         $email = constant('WEBMASTER');
814
815         // Expiration in a nice output format
816         // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
817         if (getConfig('auto_purge') == 0) {
818                 // Will never expire!
819                 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
820         } else {
821                 // Create nice date string
822                 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
823         }
824
825         // Is content an array?
826         if (is_array($content)) {
827                 // Add expiration to array, $EXPIRATION is now deprecated!
828                 $content['expiration'] = $EXPIRATION;
829         } // END - if
830
831         // Load user's data
832         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
833         if (($UID > 0) && (is_array($content))) {
834                 // If nickname extension is installed, fetch nickname as well
835                 if (EXT_IS_ACTIVE('nickname')) {
836                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
837                         // Load nickname
838                         $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
839                                 array(bigintval($UID)), __FUNCTION__, __LINE__);
840                 } else {
841                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
842                         /// Load normal data
843                         $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
844                                 array(bigintval($UID)), __FUNCTION__, __LINE__);
845                 }
846
847                 // Fetch and merge data
848                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
849                 $content = merge_array($content, SQL_FETCHARRAY($result));
850                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
851
852                 // Free result
853                 SQL_FREERESULT($result);
854         } // END - if
855
856         // Translate M to male or F to female if present
857         if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
858
859         // Overwrite email from data if present
860         if (isset($content['email'])) $email = $content['email'];
861
862         // Store email for some functions in global data array
863         $DATA['email'] = $email;
864
865         // Base directory
866         $basePath = sprintf("%stemplates/%s/emails/", constant('PATH'), getLanguage());
867
868         // Check for admin/guest/member templates
869         if (strpos($template, 'admin_') > -1) {
870                 // Admin template found
871                 $FQFN = $basePath.'admin/'.$template.'.tpl';
872         } elseif (strpos($template, 'guest_') > -1) {
873                 // Guest template found
874                 $FQFN = $basePath.'guest/'.$template.'.tpl';
875         } elseif (strpos($template, 'member_') > -1) {
876                 // Member template found
877                 $FQFN = $basePath.'member/'.$template.'.tpl';
878         } else {
879                 // Test for extension
880                 $test = substr($template, 0, strpos($template, '_'));
881                 if (EXT_IS_ACTIVE($test)) {
882                         // Set extra path to extension's name
883                         $FQFN = $basePath.$test.'/'.$template.'.tpl';
884                 } else {
885                         // No special filename
886                         $FQFN = $basePath.$template.'.tpl';
887                 }
888         }
889
890         // Does the special template exists?
891         if (!isFileReadable($FQFN)) {
892                 // Reset to default template
893                 $FQFN = $basePath.$template.'.tpl';
894         } // END - if
895
896         // Now does the final template exists?
897         $newContent = '';
898         if (isFileReadable($FQFN)) {
899                 // The local file does exists so we load it. :)
900                 $tmpl_file = readFromFile($FQFN);
901                 $tmpl_file = SQL_ESCAPE($tmpl_file);
902
903                 // Run code
904                 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
905                 eval($tmpl_file);
906         } elseif (!empty($template)) {
907                 // Template file not found!
908                 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
909 {--TEMPLATE_CONTENT--}
910 <pre>".print_r($content, true)."</pre>
911 {--TEMPLATE_DATA--}
912 <pre>".print_r($DATA, true)."</pre>
913 <br /><br />";
914
915                 // Debug mode not active? Then remove the HTML tags
916                 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
917         } else {
918                 // No template name supplied!
919                 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
920         }
921
922         // Is there some content?
923         if (empty($newContent)) {
924                 // Compiling failed
925                 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
926                 // Add last error if the required function exists
927                 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
928         } // END - if
929
930         // Remove content and data
931         unset($content);
932         unset($DATA);
933
934         // Return compiled content
935         return COMPILE_CODE($newContent);
936 }
937
938 // Generates a timestamp (wrapper for mktime())
939 function makeTime ($H, $M, $S, $stamp) {
940         // Extract day, month and year from given timestamp
941         $day   = date('d', $stamp);
942         $month = date('m', $stamp);
943         $year  = date('Y', $stamp);
944
945         // Create timestamp for wished time which depends on extracted date
946         return mktime($H, $M, $S, $month, $day, $year);
947 }
948
949 // Redirects to an URL and if neccessarry extends it with own base URL
950 function redirectToUrl ($URL, $addUrlData=true) {
951         // Compile out URI codes
952         $URL = compileUriCode($URL);
953
954         // Check if http(s):// is there
955         if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
956                 // Make all URLs full-qualified
957                 $URL = constant('URL') . '/' . $URL;
958         } // END - if
959
960         // Three different debug ways...
961         //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
962         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
963         //* DEBUG: */ die($URL);
964
965         // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
966         $rel = ' rel="external"';
967
968         // Do we have internal or external URL?
969         if (substr($URL, 0, strlen(constant('URL'))) == constant('URL')) {
970                 // Own (=internal) URL
971                 $rel = '';
972         } // END - if
973
974         // Get output buffer
975         $OUTPUT = ob_get_contents();
976
977         // Clear it only if there is content
978         if (!empty($OUTPUT)) {
979                 clearOutputBuffer();
980         } // END - if
981
982         // Add some data to URL if cookies are not accepted
983         if ((!isBooleanConstantAndTrue('__COOKIES')) && ($addUrlData === true)) $URL = addUrlData($URL);
984
985         // Secure the URL against bad things such als HTML insertions and so on...
986         $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
987
988         // Simple probe for bots/spiders from search engines
989         if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
990                 // Output new location link as anchor
991                 OUTPUT_HTML('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
992         } elseif (!headers_sent()) {
993                 // Load URL when headers are not sent
994                 //* DEBUG: */ debug_report_bug("URL={$URL}");
995                 header ('Location: '.str_replace('&amp;', '&', $URL));
996         } else {
997                 // Output error message
998                 loadInclude('inc/header.php');
999                 LOAD_TEMPLATE('redirect_url', false, str_replace('&amp;', '&', $URL));
1000                 loadInclude('inc/footer.php');
1001         }
1002
1003         // Shut the mailer down here
1004         shutdown();
1005 }
1006
1007 // Wrapper for redirectToUrl but URL comes from a configuration entry
1008 function LOAD_CONFIGURED_URL ($configEntry) {
1009         // Get the URL
1010         $URL = getConfig($configEntry);
1011
1012         // Is this URL set?
1013         if (is_null($URL)) {
1014                 // Then abort here
1015                 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
1016         } // END - if
1017
1018         // Load the URL
1019         redirectToUrl($URL);
1020 }
1021
1022 //
1023 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
1024         // Is the code a string?
1025         if (!is_string($code)) {
1026                 // Silently return it
1027                 return $code;
1028         } // END - if
1029
1030         // Init replacement-array with full security characters
1031         $secChars = $GLOBALS['security_chars'];
1032
1033         // Select smaller set of chars to replace when we e.g. want to compile URLs
1034         if (!$full) $secChars = $GLOBALS['url_chars'];
1035
1036         // Compile constants
1037         if ($constants === true) {
1038                 // BEFORE 0.2.1 : Language and data constants
1039                 // WITH 0.2.1+  : Only language constants
1040                 $code = str_replace('{--','".', str_replace('--}','."', $code));
1041
1042                 // BEFORE 0.2.1 : Not used
1043                 // WITH 0.2.1+  : Data constants
1044                 $code = str_replace('{!','".', str_replace("!}", '."', $code));
1045         } // END - if
1046
1047         // Compile QUOT and other non-HTML codes
1048         foreach ($secChars['to'] as $k => $to) {
1049                 // Do the reversed thing as in inc/libs/security_functions.php
1050                 $code = str_replace($to, $secChars['from'][$k], $code);
1051         } // END - foreach
1052
1053         // But shall I keep simple quotes for later use?
1054         if ($simple) $code = str_replace("'", '{QUOT}', $code);
1055
1056         // Find $content[bla][blub] entries
1057         preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1058
1059         // Are some matches found?
1060         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1061                 // Replace all matches
1062                 $matchesFound = array();
1063                 foreach ($matches[0] as $key => $match) {
1064                         // Fuzzy look has failed by default
1065                         $fuzzyFound = false;
1066
1067                         // Fuzzy look on match if already found
1068                         foreach ($matchesFound as $found => $set) {
1069                                 // Get test part
1070                                 $test = substr($found, 0, strlen($match));
1071
1072                                 // Does this entry exist?
1073                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1074                                 if ($test == $match) {
1075                                         // Match found!
1076                                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1077                                         $fuzzyFound = true;
1078                                         break;
1079                                 } // END - if
1080                         } // END - foreach
1081
1082                         // Skip this entry?
1083                         if ($fuzzyFound) continue;
1084
1085                         // Take all string elements
1086                         if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1087                                 // Replace it in the code
1088                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1089                                 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1090                                 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1091                                 $matchesFound[$key."_".$matches[4][$key]] = 1;
1092                                 $matchesFound[$match] = 1;
1093                         } elseif (!isset($matchesFound[$match])) {
1094                                 // Not yet replaced!
1095                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1096                                 $code = str_replace($match, "\".".$match.".\"", $code);
1097                                 $matchesFound[$match] = 1;
1098                         }
1099                 } // END - foreach
1100         } // END - if
1101
1102         // Return compiled code
1103         return $code;
1104 }
1105
1106 /************************************************************************
1107  *                                                                      *
1108  * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!)       *
1109  * $a_sort sortiert:                                                    *
1110  *                                                                      *
1111  * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1112  * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben    *
1113  * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird   *
1114  * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a             *
1115  * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren   *
1116  *                                                                      *
1117  * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array    *
1118  * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1119  * Sie, dass es doch nicht so schwer ist! :-)                           *
1120  *                                                                      *
1121  ************************************************************************/
1122 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1123         $dummy = $array;
1124         while ($primary_key < count($a_sort)) {
1125                 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1126                         foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1127                                 $match = false;
1128                                 if (!$nums) {
1129                                         // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1130                                         if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1131                                 } elseif ($key != $key2) {
1132                                         // Sort numbers (E.g.: 9 < 10)
1133                                         if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1134                                         if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1))  $match = true;
1135                                 }
1136
1137                                 if ($match) {
1138                                         // We have found two different values, so let's sort whole array
1139                                         foreach ($dummy as $sort_key => $sort_val) {
1140                                                 $t                       = $dummy[$sort_key][$key];
1141                                                 $dummy[$sort_key][$key]  = $dummy[$sort_key][$key2];
1142                                                 $dummy[$sort_key][$key2] = $t;
1143                                                 unset($t);
1144                                         } // END - foreach
1145                                 } // END - if
1146                         } // END - foreach
1147                 } // END - foreach
1148
1149                 // Count one up
1150                 $primary_key++;
1151         } // END - while
1152
1153         // Write back sorted array
1154         $array = $dummy;
1155 }
1156
1157 //
1158 function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
1159         $OUT = '';
1160
1161         if ($type == 'yn') {
1162                 // This is a yes/no selection only!
1163                 if ($id > 0) $prefix .= "[".$id."]";
1164                 $OUT .= "    <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1165         } else {
1166                 // Begin with regular selection box here
1167                 if (!empty($prefix)) $prefix .= "_";
1168                 $type2 = $type;
1169                 if ($id > 0) $type2 .= "[".$id."]";
1170                 $OUT .= "    <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1171         }
1172
1173         switch ($type) {
1174         case "day": // Day
1175                 for ($idx = 1; $idx < 32; $idx++) {
1176                         $OUT .= "<option value=\"".$idx."\"";
1177                         if ($default == $idx) $OUT .= ' selected="selected"';
1178                         $OUT .= ">".$idx."</option>\n";
1179                 } // END - for
1180                 break;
1181
1182         case "month": // Month
1183                 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1184                         $OUT .= "<option value=\"".$month."\"";
1185                         if ($default == $month) $OUT .= ' selected="selected"';
1186                         $OUT .= ">".$descr."</option>\n";
1187                 } // END - for
1188                 break;
1189
1190         case "year": // Year
1191                 // Get current year
1192                 $year = date('Y', time());
1193
1194                 // Use configured min age or fixed?
1195                 if (GET_EXT_VERSION('other') >= '0.2.1') {
1196                         // Configured
1197                         $startYear = $year - getConfig('min_age');
1198                 } else {
1199                         // Fixed 16 years
1200                         $startYear = $year - 16;
1201                 }
1202
1203                 // Calculate earliest year (100 years old people can still enter Internet???)
1204                 $minYear = $year - 100;
1205
1206                 // Check if the default value is larger than minimum and bigger than actual year
1207                 if (($default > $minYear) && ($default >= $year)) {
1208                         for ($idx = $year; $idx < ($year + 11); $idx++) {
1209                                 $OUT .= "<option value=\"".$idx."\"";
1210                                 if ($default == $idx) $OUT .= ' selected="selected"';
1211                                 $OUT .= ">".$idx."</option>\n";
1212                         } // END - for
1213                 } elseif ($default == -1) {
1214                         // Current year minus 1
1215                         for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1216                         {
1217                                 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1218                         }
1219                 } else {
1220                         // Get current year and subtract the configured minimum age
1221                         $OUT .= "<option value=\"".($minYear - 1)."\">&lt;".$minYear."</option>\n";
1222                         // Calculate earliest year depending on extension version
1223                         if (GET_EXT_VERSION('other') >= '0.2.1') {
1224                                 // Use configured minimum age
1225                                 $year = date('Y', time()) - getConfig('min_age');
1226                         } else {
1227                                 // Use fixed 16 years age
1228                                 $year = date('Y', time()) - 16;
1229                         }
1230
1231                         // Construct year selection list
1232                         for ($idx = $minYear; $idx <= $year; $idx++) {
1233                                 $OUT .= "<option value=\"".$idx."\"";
1234                                 if ($default == $idx) $OUT .= ' selected="selected"';
1235                                 $OUT .= ">".$idx."</option>\n";
1236                         } // END - for
1237                 }
1238                 break;
1239
1240         case "sec":
1241         case "min":
1242                 for ($idx = 0; $idx < 60; $idx+=5) {
1243                         if (strlen($idx) == 1) $idx = '0'.$idx;
1244                         $OUT .= "<option value=\"".$idx."\"";
1245                         if ($default == $idx) $OUT .= ' selected="selected"';
1246                         $OUT .= ">".$idx."</option>\n";
1247                 } // END - for
1248                 break;
1249
1250         case "hour":
1251                 for ($idx = 0; $idx < 24; $idx++) {
1252                         if (strlen($idx) == 1) $idx = '0'.$idx;
1253                         $OUT .= "<option value=\"".$idx."\"";
1254                         if ($default == $idx) $OUT .= ' selected="selected"';
1255                         $OUT .= ">".$idx."</option>\n";
1256                 } // END - for
1257                 break;
1258
1259         case 'yn':
1260                 $OUT .= "<option value=\"Y\"";
1261                 if ($default == 'Y') $OUT .= ' selected="selected"';
1262                 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1263                 if ($default == 'N') $OUT .= ' selected="selected"';
1264                 $OUT .= ">{--NO--}</option>\n";
1265                 break;
1266         }
1267         $OUT .= "    </select>\n";
1268         return $OUT;
1269 }
1270
1271 //
1272 // Deprecated : $length
1273 // Optional   : $DATA
1274 //
1275 function generateRandomCodde ($length, $code, $uid, $DATA = '') {
1276         // Fix missing _MAX constant
1277         // @TODO Rewrite this unnice code
1278         if (!defined('_MAX')) define('_MAX', 15235);
1279
1280         // Build server string
1281         $server = $_SERVER['PHP_SELF'].constant('ENCRYPT_SEPERATOR').detectUserAgent().constant('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').constant('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH')."inc/databases.php");
1282
1283         // Build key string
1284         $keys = constant('SITE_KEY').constant('ENCRYPT_SEPERATOR').constant('DATE_KEY');
1285         if (isConfigEntrySet('secret_key'))  $keys .= constant('ENCRYPT_SEPERATOR').getConfig('secret_key');
1286         if (isConfigEntrySet('file_hash'))   $keys .= constant('ENCRYPT_SEPERATOR').getConfig('file_hash');
1287         $keys .= constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1288         if (isConfigEntrySet('master_salt')) $keys .= constant('ENCRYPT_SEPERATOR').getConfig('master_salt');
1289
1290         // Build string from misc data
1291         $data   = $code.constant('ENCRYPT_SEPERATOR').$uid.constant('ENCRYPT_SEPERATOR').$DATA;
1292
1293         // Add more additional data
1294         if (isSessionVariableSet('u_hash'))         $data .= constant('ENCRYPT_SEPERATOR').getSession('u_hash');
1295         if (isUserIdSet())                          $data .= constant('ENCRYPT_SEPERATOR').getUserId();
1296         if (isSessionVariableSet('mxchange_theme')) $data .= constant('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
1297         if (isSessionVariableSet('mx_lang'))        $data .= constant('ENCRYPT_SEPERATOR').getLanguage();
1298         if (isset($GLOBALS['refid']))               $data .= constant('ENCRYPT_SEPERATOR').$GLOBALS['refid'];
1299
1300         // Calculate number for generating the code
1301         $a = $code + constant('_ADD') - 1;
1302
1303         if (isConfigEntrySet('master_hash')) {
1304                 // Generate hash with master salt from modula of number with the prime number and other data
1305                 $saltedHash = generateHash(($a % constant('_PRIME')).constant('ENCRYPT_SEPERATOR').$server.constant('ENCRYPT_SEPERATOR').$keys.constant('ENCRYPT_SEPERATOR').$data.constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", time()).constant('ENCRYPT_SEPERATOR').$a, getConfig('master_salt'));
1306
1307                 // Create number from hash
1308                 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1309         } else {
1310                 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1311                 $saltedHash = generateHash(($a % constant('_PRIME')).constant('ENCRYPT_SEPERATOR').$server.constant('ENCRYPT_SEPERATOR').$keys.constant('ENCRYPT_SEPERATOR').$data.constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", time()).constant('ENCRYPT_SEPERATOR').$a, substr(sha1(constant('SITE_KEY')), 0, 8));
1312
1313                 // Create number from hash
1314                 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1315         }
1316
1317         // At least 10 numbers shall be secure enought!
1318         $len = getConfig('code_length');
1319         if ($len == 0) $len = $length;
1320         if ($len == 0) $len = 10;
1321
1322         // Cut off requested counts of number
1323         $return = substr(str_replace('.', '', $rcode), 0, $len);
1324
1325         // Done building code
1326         return $return;
1327 }
1328
1329 // Does only allow numbers
1330 function bigintval ($num, $castValue = true) {
1331         // Filter all numbers out
1332         $ret = preg_replace("/[^0123456789]/", '', $num);
1333
1334         // Shall we cast?
1335         if ($castValue) $ret = (double)$ret;
1336
1337         // Has the whole value changed?
1338         // @TODO Remove this if() block if all is working fine
1339         if ("".$ret."" != ''.$num."") {
1340                 // Log the values
1341                 debug_report_bug("{$ret}<>{$num}");
1342         } // END - if
1343
1344         // Return result
1345         return $ret;
1346 }
1347
1348 // Insert the code in $img_code into jpeg or PNG image
1349 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1350         if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1351                 // Stop execution of function here because of over-sized code length
1352                 return;
1353         } elseif (!$headerSent) {
1354                 // Return in an HTML code code
1355                 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1356         }
1357
1358         // Load image
1359         $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), getCurrentTheme(), getConfig('img_type'));
1360         if (isFileReadable($img)) {
1361                 // Switch image type
1362                 switch (getConfig('img_type'))
1363                 {
1364                 case "jpg":
1365                         // Okay, load image and hide all errors
1366                         $image = @imagecreatefromjpeg($img);
1367                         break;
1368
1369                 case "png":
1370                         // Okay, load image and hide all errors
1371                         $image = @imagecreatefrompng($img);
1372                         break;
1373                 }
1374         } else {
1375                 // Exit function here
1376                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1377                 return;
1378         }
1379
1380         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1381         $text_color = imagecolorallocate($image, 0, 0, 0);
1382
1383         // Insert code into image
1384         imagestring($image, 5, 14, 2, $img_code, $text_color);
1385
1386         // Return to browser
1387         header ("Content-Type: image/".getConfig('img_type'));
1388
1389         // Output image with matching image factory
1390         switch (getConfig('img_type')) {
1391                 case "jpg": imagejpeg($image); break;
1392                 case "png": imagepng($image);  break;
1393         }
1394
1395         // Remove image from memory
1396         imagedestroy($image);
1397 }
1398 // Create selection box or array of splitted timestamp
1399 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align="center", $return_array=false) {
1400         // Calculate 2-seconds timestamp
1401         $stamp = round($timestamp);
1402         //* DEBUG: */ print("*".$stamp.'/'.$timestamp."*<br />");
1403
1404         // Do we have a leap year?
1405         $SWITCH = 0;
1406         $TEST = date('Y', time()) / 4;
1407         $M1 = date('m', time());
1408         $M2 = date('m', (time() + $timestamp));
1409
1410         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1411         if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02"))  $SWITCH = getConfig('one_day');
1412
1413         // First of all years...
1414         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1415         //* DEBUG: */ print("Y={$Y}<br />\n");
1416         // Next months...
1417         $M = abs(floor($timestamp / 2628000 - $Y * 12));
1418         //* DEBUG: */ print("M={$M}<br />\n");
1419         // Next weeks
1420         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1421         //* DEBUG: */ print("W={$W}<br />\n");
1422         // Next days...
1423         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1424         //* DEBUG: */ print("D={$D}<br />\n");
1425         // Next hours...
1426         $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24) - $W * 7 * 24 - $D * 24));
1427         //* DEBUG: */ print("h={$h}<br />\n");
1428         // Next minutes..
1429         $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1430         //* DEBUG: */ print("m={$m}<br />\n");
1431         // And at last seconds...
1432         $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1433         //* DEBUG: */ print("s={$s}<br />\n");
1434
1435         // Is seconds zero and time is < 60 seconds?
1436         if (($s == 0) && ($timestamp < 60)) {
1437                 // Fix seconds
1438                 $s = round($timestamp);
1439         } // END - if
1440
1441         //
1442         // Now we convert them in seconds...
1443         //
1444         if ($return_array) {
1445                 // Just put all data in an array for later use
1446                 $OUT = array(
1447                         'YEARS'   => $Y,
1448                         'MONTHS'  => $M,
1449                         'WEEKS'   => $W,
1450                         'DAYS'    => $D,
1451                         'HOURS'   => $h,
1452                         'MINUTES' => $m,
1453                         'SECONDS' => $s
1454                 );
1455         } else {
1456                 // Generate table
1457                 $OUT  = "<div align=\"".$align."\">\n";
1458                 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1459                 $OUT .= "<tr>\n";
1460
1461                 if (ereg('Y', $display) || (empty($display))) {
1462                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1463                 }
1464
1465                 if (ereg("M", $display) || (empty($display))) {
1466                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1467                 }
1468
1469                 if (ereg("W", $display) || (empty($display))) {
1470                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1471                 }
1472
1473                 if (ereg("D", $display) || (empty($display))) {
1474                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1475                 }
1476
1477                 if (ereg("h", $display) || (empty($display))) {
1478                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1479                 }
1480
1481                 if (ereg('m', $display) || (empty($display))) {
1482                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1483                 }
1484
1485                 if (ereg("s", $display) || (empty($display))) {
1486                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1487                 }
1488
1489                 $OUT .= "</tr>\n";
1490                 $OUT .= "<tr>\n";
1491
1492                 if (ereg('Y', $display) || (empty($display))) {
1493                         // Generate year selection
1494                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1495                         for ($idx = 0; $idx <= 10; $idx++) {
1496                                 $OUT .= "    <option class=\"mini_select\" value=\"".$idx."\"";
1497                                 if ($idx == $Y) $OUT .= ' selected="selected"';
1498                                 $OUT .= ">".$idx."</option>\n";
1499                         }
1500                         $OUT .= "  </select></td>\n";
1501                 } else {
1502                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1503                 }
1504
1505                 if (ereg("M", $display) || (empty($display))) {
1506                         // Generate month selection
1507                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1508                         for ($idx = 0; $idx <= 11; $idx++)
1509                         {
1510                                         $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1511                                 if ($idx == $M) $OUT .= ' selected="selected"';
1512                                 $OUT .= ">".$idx."</option>\n";
1513                         }
1514                         $OUT .= "  </select></td>\n";
1515                 } else {
1516                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1517                 }
1518
1519                 if (ereg("W", $display) || (empty($display))) {
1520                         // Generate week selection
1521                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1522                         for ($idx = 0; $idx <= 4; $idx++) {
1523                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1524                                 if ($idx == $W) $OUT .= ' selected="selected"';
1525                                 $OUT .= ">".$idx."</option>\n";
1526                         }
1527                         $OUT .= "  </select></td>\n";
1528                 } else {
1529                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1530                 }
1531
1532                 if (ereg("D", $display) || (empty($display))) {
1533                         // Generate day selection
1534                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1535                         for ($idx = 0; $idx <= 31; $idx++) {
1536                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1537                                 if ($idx == $D) $OUT .= ' selected="selected"';
1538                                 $OUT .= ">".$idx."</option>\n";
1539                         }
1540                         $OUT .= "  </select></td>\n";
1541                 } else {
1542                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1543                 }
1544
1545                 if (ereg("h", $display) || (empty($display))) {
1546                         // Generate hour selection
1547                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1548                         for ($idx = 0; $idx <= 23; $idx++)      {
1549                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1550                                 if ($idx == $h) $OUT .= ' selected="selected"';
1551                                 $OUT .= ">".$idx."</option>\n";
1552                         }
1553                         $OUT .= "  </select></td>\n";
1554                 } else {
1555                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1556                 }
1557
1558                 if (ereg('m', $display) || (empty($display))) {
1559                         // Generate minute selection
1560                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1561                         for ($idx = 0; $idx <= 59; $idx++) {
1562                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1563                                 if ($idx == $m) $OUT .= ' selected="selected"';
1564                                 $OUT .= ">".$idx."</option>\n";
1565                         }
1566                         $OUT .= "  </select></td>\n";
1567                 } else {
1568                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1569                 }
1570
1571                 if (ereg("s", $display) || (empty($display))) {
1572                         // Generate second selection
1573                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1574                         for ($idx = 0; $idx <= 59; $idx++) {
1575                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1576                                 if ($idx == $s) $OUT .= ' selected="selected"';
1577                                 $OUT .= ">".$idx."</option>\n";
1578                         }
1579                         $OUT .= "  </select></td>\n";
1580                 } else {
1581                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1582                 }
1583                 $OUT .= "</tr>\n";
1584                 $OUT .= "</table>\n";
1585                 $OUT .= "</div>\n";
1586                 // Return generated HTML code
1587         }
1588         return $OUT;
1589 }
1590
1591 //
1592 function createTimestampFromSelections ($prefix, $POST) {
1593         // Initial return value
1594         $ret = 0;
1595
1596         // Do we have a leap year?
1597         $SWITCH = 0;
1598         $TEST = date('Y', time()) / 4;
1599         $M1   = date('m', time());
1600         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1601         if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02"))  $SWITCH = getConfig('one_day');
1602         // First add years...
1603         $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1604         // Next months...
1605         $ret += $POST[$prefix."_mo"] * 2628000;
1606         // Next weeks
1607         $ret += $POST[$prefix."_we"] * 604800;
1608         // Next days...
1609         $ret += $POST[$prefix."_da"] * 86400;
1610         // Next hours...
1611         $ret += $POST[$prefix."_ho"] * 3600;
1612         // Next minutes..
1613         $ret += $POST[$prefix."_mi"] * 60;
1614         // And at last seconds...
1615         $ret += $POST[$prefix."_se"];
1616         // Return calculated value
1617         return $ret;
1618 }
1619
1620 // Sends out mail to all administrators
1621 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1622 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1623         // Trim template name
1624         $template = trim($template);
1625
1626         // Load email template
1627         $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1628
1629         // Check which admin shall receive this mail
1630         $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1631                 array($template), __FUNCTION__, __LINE__);
1632         if (SQL_NUMROWS($result) == 0) {
1633                 // Create new entry (to all admins)
1634                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1635                         array($template), __FUNCTION__, __LINE__);
1636         } else {
1637                 // Load admin IDs...
1638                 // @TODO This can be, somehow, rewritten
1639                 $adminIds = array();
1640                 while ($content = SQL_FETCHARRAY($result)) {
1641                         $adminIds[] = $content['admin_id'];
1642                 } // END - while
1643
1644                 // Free memory
1645                 SQL_FREERESULT($result);
1646
1647                 // Init result
1648                 $result = false;
1649
1650                 // "implode" IDs and query string
1651                 $aid = implode(",", $adminIds);
1652                 if ($aid == "-1") {
1653                         if (EXT_IS_ACTIVE('events')) {
1654                                 // Add line to user events
1655                                 EVENTS_ADD_LINE($subj, $msg, $UID);
1656                         } else {
1657                                 // Log error for debug
1658                                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1659                                         $template,
1660                                         $subj,
1661                                         $UID
1662                                 ));
1663                         }
1664                 } elseif ($aid == '0') {
1665                         // Select all email adresses
1666                         $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1667                                 __FUNCTION__, __LINE__);
1668                 } else {
1669                         // If Admin-ID is not "to-all" select
1670                         $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1671                                 array($aid), __FUNCTION__, __LINE__);
1672                 }
1673         }
1674
1675         // Load email addresses and send away
1676         while ($content = SQL_FETCHARRAY($result)) {
1677                 sendEmail($content['email'], $subj, $msg);
1678         } // END - while
1679
1680         // Free memory
1681         SQL_FREERESULT($result);
1682 }
1683
1684 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1685 function createFancyTime ($stamp) {
1686         // Get data array with years/months/weeks/days/...
1687         $data = createTimeSelections($stamp, '', '', '', true);
1688         $ret = '';
1689         foreach($data as $k => $v) {
1690                 if ($v > 0) {
1691                         // Value is greater than 0 "eval" data to return string
1692                         $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1693                         eval($eval);
1694                         break;
1695                 } // END - if
1696         } // END - foreach
1697
1698         // Do we have something there?
1699         if (strlen($ret) > 0) {
1700                 // Remove leading commata and space
1701                 $ret = substr($ret, 2);
1702         } else {
1703                 // Zero seconds
1704                 $ret = "0 {--_SECONDS--}";
1705         }
1706
1707         // Return fancy time string
1708         return $ret;
1709 }
1710
1711 //
1712 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1713         $SEP = ''; $TOP = '';
1714         if (!$show_form) {
1715                 $TOP = " top2";
1716                 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\">&nbsp;</td></tr>";
1717         }
1718
1719         $NAV = '';
1720         for ($page = 1; $page <= $PAGES; $page++) {
1721                 // Is the page currently selected or shall we generate a link to it?
1722                 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == "1"))) {
1723                         // Is currently selected, so only highlight it
1724                         $NAV .= "<strong>-";
1725                 } else {
1726                         // Open anchor tag and add base URL
1727                         $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&amp;what=".$GLOBALS['what']."&amp;page=".$page."&amp;offset=".$offset;
1728
1729                         // Add userid when we shall show all mails from a single member
1730                         if ((REQUEST_ISSET_GET('uid')) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&amp;uid=".bigintval(REQUEST_GET('uid'));
1731
1732                         // Close open anchor tag
1733                         $NAV .= "\">";
1734                 }
1735                 $NAV .= $page;
1736                 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == "1"))) {
1737                         // Is currently selected, so only highlight it
1738                         $NAV .= "-</strong>";
1739                 } else {
1740                         // Close anchor tag
1741                         $NAV .= "</a>";
1742                 }
1743
1744                 // Add seperator if we have not yet reached total pages
1745                 if ($page < $PAGES) $NAV .= "&nbsp;|&nbsp;";
1746         } // END - for
1747
1748         // Define constants only once
1749         if (!defined('__NAV_OUTPUT')) {
1750                 define('__NAV_OUTPUT' , $NAV);
1751                 define('__NAV_COLSPAN', $colspan);
1752                 define('__NAV_TOP'    , $TOP);
1753                 define('__NAV_SEP'    , $SEP);
1754         } // END - if
1755
1756         // Load navigation template
1757         $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1758
1759         if ($return === true) {
1760                 // Return generated HTML-Code
1761                 return $OUT;
1762         } else {
1763                 // Output HTML-Code
1764                 OUTPUT_HTML($OUT);
1765         }
1766 }
1767
1768 // Extract host from script name
1769 function extractHostnameFromUrl (&$script) {
1770         // Use default SERVER_URL by default... ;) So?
1771         $url = constant('SERVER_URL');
1772
1773         // Is this URL valid?
1774         if (substr($script, 0, 7) == "http://") {
1775                 // Use the hostname from script URL as new hostname
1776                 $url = substr($script, 7);
1777                 $extract = explode('/', $url);
1778                 $url = $extract[0];
1779                 // Done extracting the URL :)
1780         } // END - if
1781
1782         // Extract host name
1783         $host = str_replace("http://", '', $url);
1784         if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1785
1786         // Generate relative URL
1787         //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1788         if (substr(strtolower($script), 0, 7) == "http://") {
1789                 // But only if http:// is in front!
1790                 $script = substr($script, (strlen($url) + 7));
1791         } elseif (substr(strtolower($script), 0, 8) == "https://") {
1792                 // Does this work?!
1793                 $script = substr($script, (strlen($url) + 8));
1794         }
1795
1796         //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1797         if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1798
1799         // Return host name
1800         return $host;
1801 }
1802
1803 // Send a GET request
1804 function sendGetRequest ($script) {
1805         // Compile the script name
1806         $script = COMPILE_CODE($script);
1807
1808         // Extract host name from script
1809         $host = extractHostnameFromUrl($script);
1810
1811         // Generate GET request header
1812         $request  = "GET /" . trim($script) . " HTTP/1.1\r\n";
1813         $request .= "Host: " . $host . "\r\n";
1814         $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1815         if (defined('FULL_VERSION')) {
1816                 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
1817         } else {
1818                 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?\r\n";
1819         }
1820         $request .= "Content-Type: text/plain\r\n";
1821         $request .= "Cache-Control: no-cache\r\n";
1822         $request .= "Connection: Close\r\n\r\n";
1823
1824         // Send the raw request
1825         $response = sendRawRequest($host, $request);
1826
1827         // Return the result to the caller function
1828         return $response;
1829 }
1830
1831 // Send a POST request
1832 function sendPostRequest ($script, $postData) {
1833         // Is postData an array?
1834         if (!is_array($postData)) {
1835                 // Abort here
1836                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1837                 return array('', '', '');
1838         } // END - if
1839
1840         // Compile the script name
1841         $script = COMPILE_CODE($script);
1842
1843         // Extract host name from script
1844         $host = extractHostnameFromUrl($script);
1845
1846         // Construct request
1847         $data = http_build_query($postData, '','&');
1848
1849         // Generate POST request header
1850         $request  = "POST /" . trim($script) . " HTTP/1.1\r\n";
1851         $request .= "Host: " . $host . "\r\n";
1852         $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1853         $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
1854         $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1855         $request .= "Content-length: " . strlen($data) . "\r\n";
1856         $request .= "Cache-Control: no-cache\r\n";
1857         $request .= "Connection: Close\r\n\r\n";
1858         $request .= $data;
1859
1860         // Send the raw request
1861         $response = sendRawRequest($host, $request);
1862
1863         // Return the result to the caller function
1864         return $response;
1865 }
1866
1867 // Sends a raw request to another host
1868 function sendRawRequest ($host, $request) {
1869         // Initialize array
1870         $response = array('', '', '');
1871
1872         // Default is not to use proxy
1873         $useProxy = false;
1874
1875         // Are proxy settins set?
1876         if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
1877                 // Then use it
1878                 $useProxy = true;
1879         } // END - if
1880
1881         // Open connection
1882         //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1883         if ($useProxy) {
1884                 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1885         } else {
1886                 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1887         }
1888
1889         // Is there a link?
1890         if (!is_resource($fp)) {
1891                 // Failed!
1892                 return $response;
1893         } // END - if
1894
1895         // Do we use proxy?
1896         if ($useProxy) {
1897                 // Generate CONNECT request header
1898                 $proxyTunnel  = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1899                 $proxyTunnel .= "Host: ".$host."\r\n";
1900
1901                 // Use login data to proxy? (username at least!)
1902                 if (getConfig('proxy_username') != '') {
1903                         // Add it as well
1904                         $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).constant('ENCRYPT_SEPERATOR').COMPILE_CODE(getConfig('proxy_password')));
1905                         $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1906                 } // END - if
1907
1908                 // Add last new-line
1909                 $proxyTunnel .= "\r\n";
1910                 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1911
1912                 // Write request
1913                 fputs($fp, $proxyTunnel);
1914
1915                 // Got response?
1916                 if (feof($fp)) {
1917                         // No response received
1918                         return $response;
1919                 } // END - if
1920
1921                 // Read the first line
1922                 $resp = trim(fgets($fp, 10240));
1923                 $respArray = explode(' ', $resp);
1924                 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1925                         // Invalid response!
1926                         return $response;
1927                 } // END - if
1928         } // END - if
1929
1930         // Write request
1931         fputs($fp, $request);
1932
1933         // Read response
1934         while (!feof($fp)) {
1935                 $response[] = trim(fgets($fp, 1024));
1936         } // END - while
1937
1938         // Close socket
1939         fclose($fp);
1940
1941         // Skip first empty lines
1942         $resp = $response;
1943         foreach ($resp as $idx => $line) {
1944                 // Trim space away
1945                 $line = trim($line);
1946
1947                 // Is this line empty?
1948                 if (empty($line)) {
1949                         // Then remove it
1950                         array_shift($response);
1951                 } else {
1952                         // Abort on first non-empty line
1953                         break;
1954                 }
1955         } // END - foreach
1956
1957         //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1958
1959         // Proxy agent found?
1960         if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy)) {
1961                 // Proxy header detected, so remove two lines
1962                 array_shift($response);
1963                 array_shift($response);
1964         } // END - if
1965
1966         // Was the request successfull?
1967         if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1968                 // Not found / access forbidden
1969                 $response = array('', '', '');
1970         } // END - if
1971
1972         // Return response
1973         return $response;
1974 }
1975
1976 // Taken from www.php.net eregi() user comments
1977 function VALIDATE_EMAIL ($email) {
1978         // Compile email
1979         $email = COMPILE_CODE($email);
1980
1981         // Check first part of email address
1982         $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1983
1984         //  Check domain
1985         $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1986
1987         // Generate pattern
1988         $regex = '^'.$first.'@'.$domain.'$';
1989
1990         // Return check result
1991         // @TODO eregi() should be rewritten here
1992         return eregi($regex, $email);
1993 }
1994
1995 // Function taken from user comments on www.php.net / function eregi()
1996 function isUrlValid ($URL, $compile=true) {
1997         // Trim URL a little
1998         $URL = trim(urldecode($URL));
1999         //* DEBUG: */ echo $URL."<br />";
2000
2001         // Compile some chars out...
2002         if ($compile) $URL = compileUriCode($URL, false, false, false);
2003         //* DEBUG: */ echo $URL."<br />";
2004
2005         // Check for the extension filter
2006         if (EXT_IS_ACTIVE('filter')) {
2007                 // Use the extension's filter set
2008                 return FILTER_isUrlValid($URL, false);
2009         } // END - if
2010
2011         // If not installed, perform a simple test. Just make it sure there is always a http:// or
2012         // https:// in front of the URLs
2013         return isUrlValid($URL);
2014 }
2015
2016 // Generate a list of administrative links to a given userid
2017 function generateMemberAdminActionLinks ($uid, $status = '') {
2018         // Define all main targets
2019         $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2020
2021         // Begin of navigation links
2022         $eval = "\$OUT = \"[&nbsp;";
2023
2024         foreach ($TARGETS as $tar) {
2025                 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&amp;what=".$tar."&amp;uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
2026                 //* DEBUG: */ echo "*".$tar.'/'.$status."*<br />\n";
2027                 if (($tar == "lock_user") && ($status == 'LOCKED')) {
2028                         // Locked accounts shall be unlocked
2029                         $eval .= "UNLOCK_USER";
2030                 } else {
2031                         // All other status is fine
2032                         $eval .= strtoupper($tar);
2033                 }
2034                 $eval .= "_TITLE--}\\\">{--ADMIN_";
2035                 if (($tar == "lock_user") && ($status == 'LOCKED')) {
2036                         // Locked accounts shall be unlocked
2037                         $eval .= "UNLOCK_USER";
2038                 } else {
2039                         // All other status is fine
2040                         $eval .= strtoupper($tar);
2041                 }
2042                 $eval .= "--}</a></span>&nbsp;|&nbsp;";
2043         }
2044
2045         // Finish navigation link
2046         $eval = substr($eval, 0, -7)."]\";";
2047         eval($eval);
2048
2049         // Return string
2050         return $OUT;
2051 }
2052
2053 // Generate an email link
2054 function generateMemberEmailLink ($email, $table = 'admins') {
2055         // Default email link (INSECURE! Spammer can read this by harvester programs)
2056         $EMAIL = 'mailto:' . $email;
2057
2058         // Check for several extensions
2059         if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
2060                 // Create email link for contacting admin in guest area
2061                 $EMAIL = adminsCreateEmailLink($email);
2062                 } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
2063                 // Create email link for contacting a member within admin area (or later in other areas, too?)
2064                 $EMAIL = USER_generateMemberEmailLink($email);
2065         } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
2066                 // Create email link to contact sponsor within admin area (or like the link above?)
2067                 $EMAIL = SPONSOR_generateMemberEmailLink($email);
2068         }
2069
2070         // Shall I close the link when there is no admin?
2071         if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2072
2073         // Return email link
2074         return $EMAIL;
2075 }
2076
2077 // Generate a hash for extra-security for all passwords
2078 function generateHash ($plainText, $salt = '') {
2079         // Is the required extension 'sql_patches' there and a salt is not given?
2080         if (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('sql_patches'))) && (empty($salt))) {
2081                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2082                 return md5($plainText);
2083         } // END - if
2084
2085         // Do we miss an arry element here?
2086         if (!isConfigEntrySet('file_hash')) {
2087                 // Stop here
2088                 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2089         } // END - if
2090
2091         // When the salt is empty build a new one, else use the first x configured characters as the salt
2092         if (empty($salt)) {
2093                 // Build server string (inc/databases.php is no longer updated with every commit)
2094                 $server = $_SERVER['PHP_SELF'].constant('ENCRYPT_SEPERATOR').detectUserAgent().constant('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').constant('ENCRYPT_SEPERATOR').detectRemoteAddr();
2095
2096                 // Build key string
2097                 $keys   = constant('SITE_KEY').constant('ENCRYPT_SEPERATOR').constant('DATE_KEY').constant('ENCRYPT_SEPERATOR').getConfig('secret_key').constant('ENCRYPT_SEPERATOR').getConfig('file_hash').constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).constant('ENCRYPT_SEPERATOR').getConfig('master_salt');
2098
2099                 // Additional data
2100                 $data = $plainText.constant('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).constant('ENCRYPT_SEPERATOR').time();
2101
2102                 // Calculate number for generating the code
2103                 $a = time() + constant('_ADD') - 1;
2104
2105                 // Generate SHA1 sum from modula of number and the prime number
2106                 $sha1 = sha1(($a % constant('_PRIME')).$server.constant('ENCRYPT_SEPERATOR').$keys.constant('ENCRYPT_SEPERATOR').$data.constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", time()).constant('ENCRYPT_SEPERATOR').$a);
2107                 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2108                 $sha1 = scrambleString($sha1);
2109                 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2110                 //* DEBUG: */ $sha1b = descrambleString($sha1);
2111                 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2112
2113                 // Generate the password salt string
2114                 $salt = substr($sha1, 0, getConfig('salt_length'));
2115                 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2116         } else {
2117                 // Use given salt
2118                 $salt = substr($salt, 0, getConfig('salt_length'));
2119                 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2120         }
2121
2122         // Return hash
2123         return $salt.sha1($salt.$plainText);
2124 }
2125
2126 // Scramble a string
2127 function scrambleString($str) {
2128         // Init
2129         $scrambled = '';
2130
2131         // Final check, in case of failture it will return unscrambled string
2132         if (strlen($str) > 40) {
2133                 // The string is to long
2134                 return $str;
2135         } elseif (strlen($str) == 40) {
2136                 // From database
2137                 $scrambleNums = explode(':', getConfig('pass_scramble'));
2138         } else {
2139                 // Generate new numbers
2140                 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2141         }
2142
2143         // Scramble string here
2144         //* DEBUG: */ echo "***Original=".$str."***<br />";
2145         for ($idx = 0; $idx < strlen($str); $idx++) {
2146                 // Get char on scrambled position
2147                 $char = substr($str, $scrambleNums[$idx], 1);
2148
2149                 // Add it to final output string
2150                 $scrambled .= $char;
2151         } // END - for
2152
2153         // Return scrambled string
2154         //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2155         return $scrambled;
2156 }
2157
2158 // De-scramble a string scrambled by scrambleString()
2159 function descrambleString($str) {
2160         // Scramble only 40 chars long strings
2161         if (strlen($str) != 40) return $str;
2162
2163         // Load numbers from config
2164         $scrambleNums = explode(':', getConfig('pass_scramble'));
2165
2166         // Validate numbers
2167         if (count($scrambleNums) != 40) return $str;
2168
2169         // Begin descrambling
2170         $orig = str_repeat(" ", 40);
2171         //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2172         for ($idx = 0; $idx < 40; $idx++) {
2173                 $char = substr($str, $idx, 1);
2174                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2175         } // END - for
2176
2177         // Return scrambled string
2178         //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2179         return $orig;
2180 }
2181
2182 // Generated a "string" for scrambling
2183 function genScrambleString ($len) {
2184         // Prepare array for the numbers
2185         $scrambleNumbers = array();
2186
2187         // First we need to setup randomized numbers from 0 to 31
2188         for ($idx = 0; $idx < $len; $idx++) {
2189                 // Generate number
2190                 $rand = mt_rand(0, ($len -1));
2191
2192                 // Check for it by creating more numbers
2193                 while (array_key_exists($rand, $scrambleNumbers)) {
2194                         $rand = mt_rand(0, ($len -1));
2195                 } // END - while
2196
2197                 // Add number
2198                 $scrambleNumbers[$rand] = $rand;
2199         } // END - for
2200
2201         // So let's create the string for storing it in database
2202         $scrambleString = implode(':', $scrambleNumbers);
2203         return $scrambleString;
2204 }
2205
2206 // Append data like session ID or referal ID to the given URL which would
2207 // normally be stored in cookies
2208 function addUrlData ($URL) {
2209         // Init add
2210         $add = '';
2211
2212         // Determine URL binder
2213         $BIND = '?';
2214         if (strpos($URL, '?') !== false) $BIND = '&amp;';
2215
2216         if ((!defined('__COOKIES')) || ((!constant('__COOKIES')))) {
2217                 // Cookies are not accepted
2218                 if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
2219                         // Cookie found in URL
2220                         $add .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
2221                 } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
2222                         // Not found! So let's set default here
2223                         $add .= $BIND."refid=".getConfig('def_refid');
2224                 }
2225         } // END - if
2226
2227         // Add all together and return it
2228         return $URL . $add;
2229 }
2230
2231 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2232 function generatePassString ($passHash) {
2233         // Return vanilla password hash
2234         $ret = $passHash;
2235
2236         // Is a secret key and master salt already initialized?
2237         if ((getConfig('secret_key') != '') && (getConfig('master_salt') != '')) {
2238                 // Only calculate when the secret key is generated
2239                 $newHash = ''; $start = 9;
2240                 for ($idx = 0; $idx < 10; $idx++) {
2241                         $part1 = hexdec(substr($passHash, $start, 4));
2242                         $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2243                         $mod = dechex($idx);
2244                         if ($part1 > $part2) {
2245                                 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2246                         } elseif ($part2 > $part1) {
2247                                 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2248                         }
2249                         $mod = substr(round($mod), 0, 4);
2250                         $mod = str_repeat('0', 4-strlen($mod)).$mod;
2251                         //* DEBUG: */ echo "*".$start.'='.$mod."*<br />";
2252                         $start += 4;
2253                         $newHash .= $mod;
2254                 } // END - for
2255
2256                 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2257                 $ret = generateHash($newHash, getConfig('master_salt'));
2258                 //* DEBUG: */ print($ret."<br />\n");
2259         } else {
2260                 // Hash it simple
2261                 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2262                 $ret = md5($passHash);
2263                 //* DEBUG: */ echo "++".$ret."++<br />\n";
2264         }
2265
2266         // Return result
2267         return $ret;
2268 }
2269
2270 // Fix "deleted" cookies
2271 function fixDeletedCookies ($cookies) {
2272         // Is this an array with entries?
2273         if ((is_array($cookies)) && (count($cookies) > 0)) {
2274                 // Then check all cookies if they are marked as deleted!
2275                 foreach ($cookies as $cookieName) {
2276                         // Is the cookie set to "deleted"?
2277                         if (getSession($cookieName) == 'deleted') {
2278                                 setSession($cookieName, '');
2279                         } // END - if
2280                 } // END - foreach
2281         } // END - if
2282 }
2283
2284 // Output error messages in a fasioned way and die...
2285 function app_die ($F, $L, $msg) {
2286         // Load header
2287         loadIncludeOnce('inc/header.php');
2288
2289         // Prepare message for output
2290         $msg = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $msg);
2291
2292         // Load the message template
2293         LOAD_TEMPLATE('admin_settings_saved', false, $msg);
2294
2295         // Load footer
2296         loadIncludeOnce('inc/footer.php');
2297
2298         // Exit explicitly
2299         shutdown();
2300 }
2301
2302 // Display parsing time and number of SQL queries in footer
2303 function displayParsingTime() {
2304         // Is the timer started?
2305         if (!isset($GLOBALS['startTime'])) {
2306                 // Abort here
2307                 return false;
2308         } // END - if
2309
2310         // Get end time
2311         $endTime = microtime(true);
2312
2313         // "Explode" both times
2314         $start = explode(' ', $GLOBALS['startTime']);
2315         $end = explode(' ', $endTime);
2316         $runTime = $end[0] - $start[0];
2317         if ($runTime < 0) $runTime = 0;
2318         $runTime = translateComma($runTime);
2319
2320         // Prepare output
2321         $content = array(
2322                 'runtime'               => $runTime,
2323                 'numSQLs'               => (getConfig('sql_count') + 1),
2324                 'numTemplates'  => (getConfig('num_templates') + 1)
2325         );
2326
2327         // Load the template
2328         LOAD_TEMPLATE('show_timings', false, $content);
2329 }
2330
2331 // Check wether a boolean constant is set
2332 // Taken from user comments in PHP documentation for function constant()
2333 function isBooleanConstantAndTrue ($constName) { // : Boolean
2334         // Failed by default
2335         $res = false;
2336
2337         // In cache?
2338         if (isset($GLOBALS['cache_array']['const'][$constName])) {
2339                 // Use cache
2340                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2341                 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2342         } else {
2343                 // Check constant
2344                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2345                 if (defined($constName)) {
2346                         // Found!
2347                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2348                         $res = (constant($constName) === true);
2349                 } // END - if
2350
2351                 // Set cache
2352                 $GLOBALS['cache_array']['const'][$constName] = $res;
2353         }
2354         //* DEBUG: */ var_dump($res);
2355
2356         // Return value
2357         return $res;
2358 }
2359
2360 // Checks if a given apache module is loaded
2361 function isApacheModuleLoaded ($apacheModule) {
2362         // Check it and return result
2363         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2364 }
2365
2366 // "Getter" for language strings
2367 // @TODO Rewrite all language constants to this function.
2368 function getMessage ($messageId) {
2369         // Default is not found!
2370         $return = '!'.$messageId.'!';
2371
2372         // Is the language string found?
2373         if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2374                 // Language array element found in small_letters
2375                 $return = $GLOBALS['msg'][$messageId];
2376         } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2377                 // @DEPRECATED Language array element found in BIG_LETTERS
2378                 $return = $GLOBALS['msg'][$messageId];
2379         } elseif (defined($messageId)) {
2380                 // @DEPRECATED Deprecated constant found
2381                 $return = constant($messageId);
2382         } else {
2383                 // Missing language constant
2384                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2385         }
2386
2387         // Return the string
2388         return $return;
2389 }
2390
2391 // Get current theme name
2392 function getCurrentTheme() {
2393         // The default theme is 'default'... ;-)
2394         $ret = 'default';
2395
2396         // Load default theme if not empty from configuration
2397         if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2398
2399         if (!isSessionVariableSet('mxchange_theme')) {
2400                 // Set default theme
2401                 setSession('mxchange_theme', $ret);
2402         } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
2403                 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2404                 // Get theme from cookie
2405                 $ret = getSession('mxchange_theme');
2406
2407                 // Is it valid?
2408                 if (getThemeId($ret) == 0) {
2409                         // Fix it to default
2410                         $ret = 'default';
2411                 } // END - if
2412         } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
2413                 // Prepare FQFN for checking
2414                 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
2415
2416                 // Installation mode active
2417                 if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
2418                         // Set cookie from URL data
2419                         setSession('mxchange_theme', REQUEST_GET('theme'));
2420                 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2421                         // Set cookie from posted data
2422                         setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2423                 }
2424
2425                 // Set return value
2426                 $ret = getSession('mxchange_theme');
2427         } else {
2428                 // Invalid design, reset cookie
2429                 setSession('mxchange_theme', $ret);
2430         }
2431
2432         // Add (maybe) found theme.php file to inclusion list
2433         $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2434
2435         // Try to load the requested include file
2436         if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
2437
2438         // Return theme value
2439         return $ret;
2440 }
2441
2442 // Get id from theme
2443 function getThemeId ($name) {
2444         // Is the extension 'theme' installed?
2445         if (!EXT_IS_ACTIVE('theme')) {
2446                 // Then abort here
2447                 return 0;
2448         } // END - if
2449
2450         // Default id
2451         $id = 0;
2452
2453         // Is the cache entry there?
2454         if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2455                 // Get the version from cache
2456                 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2457
2458                 // Count up
2459                 incrementConfigEntry('cache_hits');
2460         } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
2461                 // Check if current theme is already imported or not
2462                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2463                         array($name), __FUNCTION__, __LINE__);
2464
2465                 // Entry found?
2466                 if (SQL_NUMROWS($result) == 1) {
2467                         // Fetch data
2468                         list($id) = SQL_FETCHROW($result);
2469                 } // END - if
2470
2471                 // Free result
2472                 SQL_FREERESULT($result);
2473         }
2474
2475         // Return id
2476         return $id;
2477 }
2478
2479 // Read a given file
2480 function readFromFile ($FQFN, $sqlPrepare = false) {
2481         // Load the file
2482         if (function_exists('file_get_contents')) {
2483                 // Use new function
2484                 $content = file_get_contents($FQFN);
2485         } else {
2486                 // Fall-back to implode-file chain
2487                 $content = implode('', file($FQFN));
2488         }
2489
2490         // Prepare SQL queries?
2491         if ($sqlPrepare === true) {
2492                 // Remove some unwanted chars
2493                 $content = str_replace("\r", '', $content);
2494                 $content = str_replace("\n\n", "\n", $content);
2495         } // END - if
2496
2497         // Return the content
2498         return $content;
2499 }
2500
2501 // Writes content to a file
2502 function writeToFile ($FQFN, $content) {
2503         // Is the file writeable?
2504         if ((isFileReadable($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
2505                 // Not writeable!
2506                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
2507
2508                 // Failed! :(
2509                 return false;
2510         } // END - if
2511
2512         // By default all is failed...
2513         $return = false;
2514
2515         // Is the function there?
2516         if (function_exists('file_put_contents')) {
2517                 // Write it directly
2518                 $return = file_put_contents($FQFN, $content);
2519         } else {
2520                 // Write it with fopen
2521                 $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN).'!');
2522                 fwrite($fp, $content);
2523                 fclose($fp);
2524
2525                 // Set CHMOD rights
2526                 $return = chmod($FQFN, 0644);
2527         }
2528
2529         // Return status
2530         return $return;
2531 }
2532
2533 // Generates an error code from given account status
2534 function generateErrorCodeFromUserStatus ($status) {
2535         // Default error code if unknown account status
2536         $errorCode = getCode('UNKNOWN_STATUS');
2537
2538         // Generate constant name
2539         $constantName = sprintf("ID_%s", $status);
2540
2541         // Is the constant there?
2542         if (isCodeSet($constantName)) {
2543                 // Then get it!
2544                 $errorCode = getCode($constantName);
2545         } else {
2546                 // Unknown status
2547                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2548         }
2549
2550         // Return error code
2551         return $errorCode;
2552 }
2553
2554 // Clears the output buffer. This function does *NOT* backup sent content.
2555 function clearOutputBuffer () {
2556         // Trigger an error on failure
2557         if (!ob_end_clean()) {
2558                 // Failed!
2559                 debug_report_bug(__FUNCTION__.': Failed to clean output buffer.');
2560         } // END - if
2561 }
2562
2563 // Function to search for the last modifified file
2564 function searchDirsRecursive ($dir, &$last_changed) {
2565         // Get dir as array
2566         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=".$dir."<br />\n";
2567         // Does it match what we are looking for? (We skip a lot files already!)
2568     // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
2569         $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2570         $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
2571         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2572
2573         // Walk through all entries
2574         foreach ($ds as $d) {
2575                 // Generate proper FQFN
2576                 $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
2577
2578                 // Is it a file and readable?
2579                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2580                 if (isDirectory($FQFN)) {
2581                          // $FQFN is a directory so also crawl into this directory
2582                         $newDir = $d;
2583                         if (!empty($dir)) $newDir = $dir . '/'. $d;
2584                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: ".$newDir."<br />\n";
2585                         searchDirsRecursive($newDir, $last_changed);
2586                 } elseif (isFileReadable($FQFN)) {
2587                         // $FQFN is a filename and no directory
2588                         $time = filemtime($FQFN);
2589                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: ".$d." found. (".($last_changed['time'] - $time).")<br />\n";
2590                         if ($last_changed['time'] < $time) {
2591                                 // This file is newer as the file before
2592                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2593                                 $last_changed['path_name'] = $FQFN;
2594                                 $last_changed['time'] = $time;
2595                         } // END - if
2596                 }
2597         } // END - foreach
2598 }
2599
2600 // "Getter" for revision/version data
2601 function getActualVersion ($type = 'Revision') {
2602         // By default nothing is new... ;-)
2603         $new = false;
2604
2605         if (EXT_IS_ACTIVE('cache')) {
2606                 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2607                 if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') $new = true;
2608                 if (!isset($GLOBALS['cache_array']['revision'][$type])
2609                         || count($GLOBALS['cache_array']['revision']) < 3
2610                         || !$GLOBALS['cache_instance']->loadCacheFile('revision')) $new = true;
2611
2612                 // Is the cache file outdated/invalid?
2613                 if ($new === true){
2614                         $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
2615
2616                         // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2617                         unset($GLOBALS['cache_array']['revision']);
2618
2619                         // Reload load_cach-revison.php
2620                         loadInclude('inc/loader/load_cache-revision.php');
2621                 } // END - if
2622
2623                 // Return found value
2624                 return $GLOBALS['cache_array']['revision'][$type][0];
2625
2626         } else {
2627                 // Old Version without ext-cache active (deprecated ?)
2628
2629                 // FQFN of revision file
2630                 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2631
2632                 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2633                 if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
2634                         // Has changed!
2635                         $new = true;
2636                 } else {
2637                         // Check for revision file
2638                         if (!isFileReadable($FQFN)) {
2639                                 // Not found, so we need to create it
2640                                 $new = true;
2641                         } else {
2642                                 // Revision file found
2643                                 $ins_vers = explode("\n", readFromFile($FQFN));
2644
2645                                 // Get array for mapping information
2646                                 $mapper = array_flip(getSearchFor());
2647                                 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2648
2649                                 // Is the content valid?
2650                                 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
2651                                         // File needs update!
2652                                         $new = true;
2653                                 } else {
2654                                         // Return found value
2655                                         return trim($ins_vers[$mapper[$type]]);
2656                                 }
2657                         }
2658                 }
2659
2660                 // Has it been updated?
2661                 if ($new === true)  {
2662                         writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2663                 } // END - if
2664         }
2665 }
2666
2667 // Repares an array we are looking for
2668 // The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
2669 function getSearchFor () {
2670         // Add Revision, Date, Tag and Author
2671         $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2672
2673         // Return the created array
2674         return $searchFor;
2675 }
2676
2677 // @TODO Please describe this function
2678 function getArrayFromActualVersion () {
2679         // Init variables
2680         $next_dir = ''; // Directory to start with search
2681         $last_changed = array(
2682                 'path_name' => '',
2683                 'time'      => 0
2684         );
2685         $akt_vers = array(); // Init return array
2686         $res = 0; // Init value for counting the founded keywords
2687
2688         // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2689         searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2690
2691         // Get file
2692         $last_file = readFromFile($last_changed['path_name']);
2693
2694         // Get all the keywords to search for
2695         $searchFor = getSearchFor();
2696
2697         // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2698         foreach ($searchFor as $search) {
2699                 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2700                 $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
2701                 // This trimms the search-result and puts it in the $akt_vers-return array
2702                 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2703         } // END - foreach
2704
2705         // Save the last-changed filename for debugging
2706         $akt_vers['File'] = $last_changed['path_name'];
2707
2708         // at least 3 keyword-Tags are needed for propper values
2709         if ($res && $res >= 3
2710                 && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
2711                 && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
2712                 && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
2713                 // Prepare content witch need special treadment
2714
2715                 // Prepare timestamp for date
2716                 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2717                 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2718
2719                 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2720                 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2721                         $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2722                 } // END - if
2723
2724         } else {
2725                 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2726                 $version = sendGetRequest('check-updates3.php');
2727
2728                 // Prepare content
2729                 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2730                 if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
2731                 if (!isset($akt_vers['Date'])     || $akt_vers['Date']     == '') $akt_vers['Date']     = trim($version[9]);
2732                 if (!isset($akt_vers['Tag'])      || $akt_vers['Tag']      == '') $akt_vers['Tag']      = trim($version[8]);
2733                 if (!isset($akt_vers['Author'])   || $akt_vers['Author']   == '') $akt_vers['Author']   = "quix0r";
2734         }
2735
2736         // Return prepared array
2737         return $akt_vers;
2738 }
2739
2740
2741 // Loads an include file and logs any missing files for debug purposes
2742 function loadInclude ($INC) {
2743         // Add the path. This is why we need a trailing slash in config.php
2744         $FQFN = constant('PATH') . $INC;
2745
2746         // Is the include file there?
2747         if (!isIncludeReadable($INC)) {
2748                 // Not there so log it
2749                 debug_report_bug(sprintf("Include file %s not found.", $INC));
2750                 return false;
2751         } // END - if
2752
2753         // Try to load it
2754         require($FQFN);
2755 }
2756
2757 // Loads an include file once
2758 function loadIncludeOnce ($INC) {
2759         // Is it not loaded?
2760         if (!isset($GLOBALS['load_once'][$INC])) {
2761                 // Then try to load it
2762                 loadInclude($INC);
2763
2764                 // And mark it as loaded
2765                 $GLOBALS['load_once'][$INC] = "loaded";
2766         } // END - if
2767 }
2768
2769 // Back-ported from the new ship-simu engine. :-)
2770 function debug_get_printable_backtrace () {
2771         // Init variable
2772         $backtrace = "<ol>\n";
2773
2774         // Get and prepare backtrace for output
2775         $backtraceArray = debug_backtrace();
2776         foreach ($backtraceArray as $key => $trace) {
2777                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2778                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2779                 if (!isset($trace['args'])) $trace['args'] = array();
2780                 $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:".$trace['line'].", <span class=\"backtrace_function\">".$trace['function']."(".count($trace['args']).")</span></li>\n";
2781         } // END - foreach
2782
2783         // Close it
2784         $backtrace .= "</ol>\n";
2785
2786         // Return the backtrace
2787         return $backtrace;
2788 }
2789
2790 // Output a debug backtrace to the user
2791 function debug_report_bug ($message = '') {
2792         // Init message
2793         $debug = '';
2794         // Is the optional message set?
2795         if (!empty($message)) {
2796                 // Use and log it
2797                 $debug = sprintf("Note: %s<br />\n",
2798                         $message
2799                 );
2800
2801                 // @TODO Add a little more infos here
2802                 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2803         } // END - if
2804
2805         // Add output
2806         $debug .= "Please report this bug at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>";
2807         $debug .= debug_get_printable_backtrace();
2808         $debug .= "</pre>Request-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
2809         $debug .= "Thank you for finding bugs.";
2810
2811         // And abort here
2812         // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2813         die($debug);
2814 }
2815
2816 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2817 function generateSeed () {
2818         list($usec, $sec) = explode(" ", microtime());
2819         return ((float)$sec + (float)$usec);
2820 }
2821
2822 // Converts a message code to a human-readable message
2823 function convertCodeToMessage ($code) {
2824         $msg = '';
2825         switch ($code) {
2826                 case getCode('LOGOUT_DONE')      : $msg = getMessage('LOGOUT_DONE'); break;
2827                 case getCode('LOGOUT_FAILED')    : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2828                 case getCode('DATA_INVALID')     : $msg = getMessage('MAIL_DATA_INVALID'); break;
2829                 case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2830                 case getCode('ACCOUNT_LOCKED')   : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2831                 case getCode('USER_404')         : $msg = getMessage('USER_NOT_FOUND'); break;
2832                 case getCode('STATS_404')        : $msg = getMessage('MAIL_STATS_404'); break;
2833                 case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2834
2835                 case getCode('ERROR_MAILID'):
2836                         if (EXT_IS_ACTIVE($ext, true)) {
2837                                 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2838                         } else {
2839                                 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2840                         }
2841                         break;
2842
2843                 case getCode('EXTENSION_PROBLEM'):
2844                         if (REQUEST_ISSET_GET(('ext'))) {
2845                                 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
2846                         } else {
2847                                 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2848                         }
2849                         break;
2850
2851                 case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2852                 case getCode('BEG_SAME_AS_OWN')  : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2853                 case getCode('LOGIN_FAILED')     : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2854                 case getCode('MODULE_MEM_ONLY')  : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2855
2856                 default:
2857                         // Missing/invalid code
2858                         $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2859
2860                         // Log it
2861                         DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
2862                         break;
2863         } // END - switch
2864
2865         // Return the message
2866         return $msg;
2867 }
2868
2869 // Generate a "link" for the given admin id (aid)
2870 function generateAdminLink ($aid) {
2871         // No assigned admin is default
2872         $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2873
2874         // Zero? = Not assigned
2875         if (bigintval($aid) > 0) {
2876                 // Load admin's login
2877                 $login = getAdminLogin($aid);
2878
2879                 // Is the login valid?
2880                 if ($login != '***') {
2881                         // Is the extension there?
2882                         if (EXT_IS_ACTIVE('admins')) {
2883                                 // Admin found
2884                                 $admin = "<a href=\"".adminsCreateEmailLink(getAdminEmail($aid))."\">".$login."</a>";
2885                         } else {
2886                                 // Extension not found
2887                                 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2888                         }
2889                 } else {
2890                         // Maybe deleted?
2891                         $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2892                 }
2893         } // END - if
2894
2895         // Return result
2896         return $admin;
2897 }
2898
2899 // Checks wether an include file (non-FQFN better) is readable
2900 function isIncludeReadable ($INC) {
2901         // Construct FQFN
2902         $FQFN = constant('PATH') . $INC;
2903
2904         // Is it readable?
2905         return isFileReadable($FQFN);
2906 }
2907
2908 // Encode strings
2909 // @TODO Implement $compress
2910 function encodeString ($str, $compress=true) {
2911         $str = urlencode(base64_encode(compileUriCode($str)));
2912         return $str;
2913 }
2914
2915 // Decode strings encoded with encodeString()
2916 // @TODO Implement $decompress
2917 function decodeString ($str, $decompress=true) {
2918         $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
2919         return $str;
2920 }
2921
2922 // Compile characters which are allowed in URLs
2923 function compileUriCode ($code, $simple=true) {
2924         // Compile constants
2925         if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2926
2927         // Compile QUOT and other non-HTML codes
2928         $code = str_replace('{DOT}', '.',
2929                 str_replace('{SLASH}', '/',
2930                 str_replace('{QUOT}', "'",
2931                 str_replace('{DOLLAR}', '$',
2932                 str_replace('{OPEN_ANCHOR}', '(',
2933                 str_replace('{CLOSE_ANCHOR}', ')',
2934                 str_replace('{OPEN_SQR}', '[',
2935                 str_replace('{CLOSE_SQR}', ']',
2936                 str_replace('{PER}', '%',
2937                 $code
2938         )))))))));
2939
2940         // Return compiled code
2941         return $code;
2942 }
2943
2944 // Function taken from user comments on www.php.net / function eregi()
2945 function isUrlValid ($url) {
2946         // Prepare URL
2947         $url = strip_tags(str_replace("\\", '', compileUriCode(urldecode($url))));
2948
2949         // Allows http and https
2950         $http      = "(http|https)+(:\/\/)";
2951         // Test domain
2952         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2953         // Test double-domains (e.g. .de.vu)
2954         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2955         // Test IP number
2956         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2957         // ... directory
2958         $dir       = "((/)+([-_\.[:alnum:]])+)*";
2959         // ... page
2960         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2961         // ... and the string after and including question character
2962         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2963         // Pattern for URLs like http://url/dir/doc.html?var=value
2964         $pattern['d1dpg1']  = $http.$domain1.$dir.$page.$getstring1;
2965         $pattern['d2dpg1']  = $http.$domain2.$dir.$page.$getstring1;
2966         $pattern['ipdpg1']  = $http.$ip.$dir.$page.$getstring1;
2967         // Pattern for URLs like http://url/dir/?var=value
2968         $pattern['d1dg1']  = $http.$domain1.$dir.'/'.$getstring1;
2969         $pattern['d2dg1']  = $http.$domain2.$dir.'/'.$getstring1;
2970         $pattern['ipdg1']  = $http.$ip.$dir.'/'.$getstring1;
2971         // Pattern for URLs like http://url/dir/page.ext
2972         $pattern['d1dp']  = $http.$domain1.$dir.$page;
2973         $pattern['d1dp']  = $http.$domain2.$dir.$page;
2974         $pattern['ipdp']  = $http.$ip.$dir.$page;
2975         // Pattern for URLs like http://url/dir
2976         $pattern['d1d']  = $http.$domain1.$dir;
2977         $pattern['d2d']  = $http.$domain2.$dir;
2978         $pattern['ipd']  = $http.$ip.$dir;
2979         // Pattern for URLs like http://url/?var=value
2980         $pattern['d1g1']  = $http.$domain1.'/'.$getstring1;
2981         $pattern['d2g1']  = $http.$domain2.'/'.$getstring1;
2982         $pattern['ipg1']  = $http.$ip.'/'.$getstring1;
2983         // Pattern for URLs like http://url?var=value
2984         $pattern['d1g12']  = $http.$domain1.$getstring1;
2985         $pattern['d2g12']  = $http.$domain2.$getstring1;
2986         $pattern['ipg12']  = $http.$ip.$getstring1;
2987         // Test all patterns
2988         $reg = false;
2989         foreach ($pattern as $key=>$pat) {
2990                 // Debug regex?
2991                 if (defined('DEBUG_REGEX')) {
2992                         $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2993                         $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2994                         $pat = str_replace("[:digit:]", "0-9", $pat);
2995                         $pat = str_replace('.', "\.", $pat);
2996                         $pat = str_replace("@", "\@", $pat);
2997                         echo $key."=&nbsp;".$pat."<br />";
2998                 }
2999
3000                 // Check if expression matches
3001                 $reg = ($reg || preg_match(("^".$pat."^"), $url));
3002
3003                 // Does it match?
3004                 if ($reg === true) break;
3005         }
3006
3007         // Return true/false
3008         return $reg;
3009 }
3010
3011 // Smartly adds slashes
3012 function smartAddSlashes ($unquoted) {
3013         $unquoted = str_replace("\\", '', $unquoted);
3014         return addslashes($unquoted);
3015 }
3016
3017 // Decode entities in a nicer way
3018 function decodeEntities ($str) {
3019         // Decode the entities to UTF-8 now
3020         $decodedString = html_entity_decode($str, ENT_NOQUOTES, "UTF-8");
3021
3022         // Return decoded string
3023         return $decodedString;
3024 }
3025
3026 // Wtites data to a config.php-style file
3027 // @TODO Rewrite this function to use readFromFile() and writeToFile()
3028 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
3029         // Initialize some variables
3030         $done = false;
3031         $seek++;
3032         $next  = -1;
3033         $found = false;
3034
3035         // Is the file there and read-/write-able?
3036         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
3037                 $search = "CFG: ".$comment;
3038                 $tmp = $FQFN.".tmp";
3039
3040                 // Open the source file
3041                 $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
3042
3043                 // Is the resource valid?
3044                 if (is_resource($fp)) {
3045                         // Open temporary file
3046                         $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
3047
3048                         // Is the resource again valid?
3049                         if (is_resource($fp_tmp)) {
3050                                 while (!feof($fp)) {
3051                                         // Read from source file
3052                                         $line = fgets ($fp, 1024);
3053
3054                                         if (strpos($line, $search) > -1) { $next = 0; $found = true; }
3055
3056                                         if ($next > -1) {
3057                                                 if ($next === $seek) {
3058                                                         $next = -1;
3059                                                         $line = $prefix . $DATA . $suffix."\n";
3060                                                 } else {
3061                                                         $next++;
3062                                                 }
3063                                         }
3064
3065                                         // Write to temp file
3066                                         fputs($fp_tmp, $line);
3067                                 }
3068
3069                                 // Close temp file
3070                                 fclose($fp_tmp);
3071
3072                                 // Finished writing tmp file
3073                                 $done = true;
3074                         }
3075
3076                         // Close source file
3077                         fclose($fp);
3078
3079                         if (($done) && ($found)) {
3080                                 // Copy back tmp file and delete tmp :-)
3081                                 copy($tmp, $FQFN);
3082                                 return unlink($tmp);
3083                         } elseif (!$found) {
3084                                 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
3085                         } else {
3086                                 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
3087                         }
3088                 }
3089         } else {
3090                 // File not found, not readable or writeable
3091                 OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
3092         }
3093
3094         // An error was detected!
3095         return false;
3096 }
3097 // Send notification to admin
3098 function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
3099         if (GET_EXT_VERSION('admins') >= '0.4.1') {
3100                 // Send new way
3101                 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
3102         } else {
3103                 // Send out out-dated way
3104                 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
3105                 SEND_ADMIN_EMAILS($subject, $msg);
3106         }
3107 }
3108
3109 // Merges an array together but only if both are arrays
3110 function merge_array ($array1, $array2) {
3111         // Are both an array?
3112         if ((is_array($array1)) && (is_array($array2))) {
3113                 // Merge all together
3114                 return array_merge($array1, $array2);
3115         } elseif (is_array($array1)) {
3116                 // Return left array
3117                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
3118                 return $array1;
3119         } elseif (is_array($array2)) {
3120                 // Return right array
3121                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
3122                 return $array2;
3123         }
3124
3125         // Both are not arrays
3126         debug_report_bug(__FUNCTION__.": No arrays provided!");
3127 }
3128
3129 // Debug message logger
3130 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
3131         // Is debug mode enabled?
3132         if ((isDebugModeEnabled()) || ($force === true)) {
3133                 // Remove CRLF
3134                 $message = str_replace("\r", '', str_replace("\n", '', $message));
3135
3136                 // Log this message away
3137                 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
3138                 fwrite($fp, date("d.m.Y|H:i:s", time())."|".$GLOBALS['module']."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
3139                 fclose($fp);
3140         } // END - if
3141 }
3142
3143 // Load more reset scripts
3144 function runResetIncludes () {
3145         // Is the reset set or old sql_patches?
3146         if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
3147                 // Then abort here
3148                 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
3149         } // END - if
3150
3151         // Get more daily reset scripts
3152         SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
3153
3154         // Update database
3155         if (!defined('DEBUG_RESET')) updateConfiguration('last_update', time());
3156
3157         // Is the config entry set?
3158         if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
3159                 // Create current week mark
3160                 $currWeek = date('W', time());
3161
3162                 // Has it changed?
3163                 if (getConfig('last_week') != $currWeek) {
3164                         // Include weekly reset scripts
3165                         MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
3166
3167                         // Update config
3168                         if (!defined('DEBUG_WEEKLY')) updateConfiguration('last_week', $currWeek);
3169                 } // END - if
3170
3171                 // Create current month mark
3172                 $currMonth = date('m', time());
3173
3174                 // Has it changed?
3175                 if (getConfig('last_month') != $currMonth) {
3176                         // Include monthly reset scripts
3177                         MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
3178
3179                         // Update config
3180                         if (!defined('DEBUG_MONTHLY')) updateConfiguration('last_month', $currMonth);
3181                 } // END - if
3182         } // END - if
3183
3184         // Run the filter
3185         runFilterChain('load_includes');
3186 }
3187
3188 // Handle extra values
3189 function handleExtraValues ($filterFunction, $value, $extraValue) {
3190         // Default is the value itself
3191         $ret = $value;
3192
3193         // Do we have a special filter function?
3194         if (!empty($filterFunction)) {
3195                 // Does the filter function exist?
3196                 if (function_exists($filterFunction)) {
3197                         // Do we have extra parameters here?
3198                         if (!empty($extraValue)) {
3199                                 // Put both parameters in one new array by default
3200                                 $args = array($value, $extraValue);
3201
3202                                 // If we have an array simply use it and pre-extend it with our value
3203                                 if (is_array($extraValue)) {
3204                                         // Make the new args array
3205                                         $args = merge_array(array($value), $extraValue);
3206                                 } // END - if
3207
3208                                 // Call the multi-parameter call-back
3209                                 $ret = call_user_func_array($filterFunction, $args);
3210                         } else {
3211                                 // One parameter call
3212                                 $ret = call_user_func($filterFunction, $value);
3213                         }
3214                 } // END - if
3215         } // END - if
3216
3217         // Return the value
3218         return $ret;
3219 }
3220
3221 // Check if given FQFN is a readable file
3222 function isFileReadable ($FQFN) {
3223         // Check all...
3224         return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
3225 }
3226
3227 // Converts timestamp selections into a timestamp
3228 function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
3229         // Init test variable
3230         $test2 = '';
3231
3232         // Get last three chars
3233         $test = substr($id, -3);
3234
3235         // Improved way of checking! :-)
3236         if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3237                 // Found a multi-selection for timings?
3238                 $test = substr($id, 0, -3);
3239                 if ((isset($POST[$test.'_ye'])) && (isset($POST[$test.'_mo'])) && (isset($POST[$test.'_we'])) && (isset($POST[$test.'_da'])) && (isset($POST[$test.'_ho'])) && (isset($POST[$test.'_mi'])) && (isset($POST[$test.'_se'])) && ($test != $test2)) {
3240                         // Generate timestamp
3241                         $POST[$test] = createTimestampFromSelections($test, $POST);
3242                         $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3243
3244                         // Remove data from array
3245                         foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3246                                 unset($POST[$test.'_'.$rem]);
3247                         } // END - foreach
3248
3249                         // Skip adding
3250                         unset($id); $skip = true; $test2 = $test;
3251                 } // END - if
3252         } else {
3253                 // Process this entry
3254                 $skip = false;
3255                 $test2 = '';
3256         }
3257 }
3258
3259 // Reverts the german decimal comma into Computer decimal dot
3260 function convertCommaToDot ($str) {
3261         // Default float is not a float... ;-)
3262         $float = false;
3263
3264         // Which language is selected?
3265         switch (getLanguage()) {
3266                 case 'de': // German language
3267                         // Remove german thousand dots first
3268                         $str = str_replace('.', '', $str);
3269
3270                         // Replace german commata with decimal dot and cast it
3271                         $float = (float)str_replace(',', '.', $str);
3272                         break;
3273
3274                 default: // US and so on
3275                         // Remove thousand dots first and cast
3276                         $float = (float)str_replace(',', '', $str);
3277                         break;
3278         }
3279
3280         // Return float
3281         return $float;
3282 }
3283
3284 // Handle menu-depending failed logins and return the rendered content
3285 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3286         // Default output is empty ;-)
3287         $OUT = '';
3288
3289         // Is the session data set?
3290         if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3291                 // Ignore zero values
3292                 if (getSession('mxchange_'.$accessLevel.'_failures') > 0) {
3293                         // Non-guest has login failures found, get both data and prepare it for template
3294                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3295                         $content = array(
3296                                 'login_failures' => getSession('mxchange_'.$accessLevel.'_failures'),
3297                                 'last_failure'   => generateDateTime(getSession('mxchange_'.$accessLevel.'_last_fail'), "2")
3298                         );
3299
3300                         // Load template
3301                         $OUT = LOAD_TEMPLATE('login_failures', true, $content);
3302                 } // END - if
3303
3304                 // Reset session data
3305                 setSession('mxchange_'.$accessLevel.'_failures', '');
3306                 setSession('mxchange_'.$accessLevel.'_last_fail', '');
3307         } // END - if
3308
3309         // Return rendered content
3310         return $OUT;
3311 }
3312
3313 // Rebuild cache
3314 function rebuildCacheFiles ($cache, $inc = '') {
3315         // Shall I remove the cache file?
3316         if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
3317                 // Rebuild cache
3318                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3319                         // Destroy it
3320                         $GLOBALS['cache_instance']->destroyCacheFile();
3321                 } // END - if
3322
3323                 // Include file given?
3324                 if (!empty($inc)) {
3325                         // Construct FQFN
3326                         $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3327
3328                         // Is the include there?
3329                         if (isIncludeReadable($INC)) {
3330                                 // And rebuild it from scratch
3331                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3332                                 loadInclude($INC);
3333                         } else {
3334                                 // Include not found!
3335                                 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3336                         }
3337                 } // END - if
3338         } // END - if
3339 }
3340
3341 // Purge admin menu cache
3342 function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
3343         // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3344         if (!EXT_IS_ACTIVE('cache')) {
3345                 // Cache extension not active
3346                 return false;
3347         } elseif (!isCacheInstanceValid()) {
3348                 // No cache instance!
3349                 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3350                 return false;
3351         } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
3352                 // Caching disabled (currently experiemental!)
3353                 return false;
3354         }
3355
3356         // Experiemental feature!
3357         debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3358 }
3359
3360 // Determines the real remote address
3361 function determineRealRemoteAddress () {
3362         // Is a proxy in use?
3363         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
3364                 // Proxy was used
3365                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3366         } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
3367                 // Yet, another proxy
3368                 $address = $_SERVER['HTTP_CLIENT_IP'];
3369         } else {
3370                 // The regular address when no proxy was used
3371                 $address = $_SERVER['REMOTE_ADDR'];
3372         }
3373
3374         // This strips out the real address from proxy output
3375         if (strstr($address, ",")){
3376                 $addressArray = explode(",", $address);
3377                 $address = $addressArray[0];
3378         } // END - if
3379
3380         // Return the result
3381         return $address;
3382 }
3383
3384 // "Getter" for remote IP number
3385 function detectRemoteAddr () {
3386         // Get remote ip from environment
3387         $remoteAddr = determineRealRemoteAddress();
3388
3389         // Is removeip installed?
3390         if (EXT_IS_ACTIVE('removeip')) {
3391                 // Then anonymize it
3392                 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
3393         } // END - if
3394
3395         // Return it
3396         return $remoteAddr;
3397 }
3398
3399 // "Getter" for remote hostname
3400 function detectRemoteHostname () {
3401         // Get remote ip from environment
3402         $remoteHost = getenv('REMOTE_HOST');
3403
3404         // Is removeip installed?
3405         if (EXT_IS_ACTIVE('removeip')) {
3406                 // Then anonymize it
3407                 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
3408         } // END - if
3409
3410         // Return it
3411         return $remoteHost;
3412 }
3413
3414 // "Getter" for user agent
3415 function detectUserAgent () {
3416         // Get remote ip from environment
3417         $userAgent = getenv('HTTP_USER_AGENT');
3418
3419         // Is removeip installed?
3420         if (EXT_IS_ACTIVE('removeip')) {
3421                 // Then anonymize it
3422                 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
3423         } // END - if
3424
3425         // Return it
3426         return $userAgent;
3427 }
3428
3429 // "Getter" for referer
3430 function detectReferer () {
3431         // Get remote ip from environment
3432         $referer = getenv('HTTP_REFERER');
3433
3434         // Is removeip installed?
3435         if (EXT_IS_ACTIVE('removeip')) {
3436                 // Then anonymize it
3437                 $referer = GET_ANONYMOUS_REFERER($referer);
3438         } // END - if
3439
3440         // Return it
3441         return $referer;
3442 }
3443
3444 // Adds a bonus mail to the queue
3445 // This is a high-level function!
3446 function addNewBonusMail ($data, $mode = '', $output=true) {
3447         // Use mode from data if not set and availble ;-)
3448         if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3449
3450         // Generate receiver list
3451         $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3452
3453         // Receivers added?
3454         if (!empty($RECEIVER)) {
3455                 // Add bonus mail to queue
3456                 addBonusMailToQueue(
3457                         $data['subject'],
3458                         $data['text'],
3459                         $RECEIVER,
3460                         $data['points'],
3461                         $data['seconds'],
3462                         $data['url'],
3463                         $data['cat'],
3464                         $mode,
3465                         $data['receiver']
3466                 );
3467
3468                 // Mail inserted into bonus pool
3469                 if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3470         } elseif ($output) {
3471                 // More entered than can be reached!
3472                 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3473         } else {
3474                 // Debug log
3475                 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3476         }
3477 }
3478
3479 // Determines referal id and sets it
3480 function DETERMINE_REFID () {
3481         // Check if refid is set
3482         if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3483                 // The variable user comes from the click-counter script click.php and we only accept this here
3484                 $GLOBALS['refid'] = bigintval($_GET['user']);
3485         } elseif (!empty($_POST['refid'])) {
3486                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3487                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3488         } elseif (!empty($_GET['refid'])) {
3489                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3490                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3491         } elseif (!empty($_GET['ref'])) {
3492                 // Set refid=ref (the referal link uses such variable)
3493                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3494         } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3495                 // Set session refid als global
3496                 $GLOBALS['refid'] = bigintval(getSession('refid'));
3497         } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
3498                 // Set default refid as refid in URL
3499                 $GLOBALS['refid'] = getConfig(('def_refid'));
3500         } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
3501                 // Select a random user which has confirmed enougth mails
3502                 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
3503         } else {
3504                 // No default ID when sql_patches is not installed or none set
3505                 $GLOBALS['refid'] = 0;
3506         }
3507
3508         // Set cookie when default refid > 0
3509         if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3510                 // Set cookie
3511                 setSession('refid', $GLOBALS['refid']);
3512         } // END - if
3513
3514         // Return determined refid
3515         return $GLOBALS['refid'];
3516 }
3517
3518 // Check wether we are installing
3519 function isInstalling () {
3520         $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
3521         //* DEBUG: */ var_dump($installing);
3522         return $installing;
3523 }
3524
3525 // Check wether this script is installed
3526 function isInstalled () {
3527         return isBooleanConstantAndTrue('mxchange_installed');
3528 }
3529
3530 // Check wether an admin is registered
3531 function isAdminRegistered () {
3532         return isBooleanConstantAndTrue('admin_registered');
3533 }
3534
3535 // Enables the reset mode. Only call this function if you really want the
3536 // reset to be run!
3537 function enableResetMode () {
3538         // Enable the reset mode
3539         $GLOBALS['reset_enabled'] = true;
3540
3541         // Run filters
3542         runFilterChain('reset_enabled');
3543 }
3544
3545 // Checks wether the reset mode is active
3546 function isResetModeEnabled () {
3547         // Now simply check it
3548         return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
3549 }
3550
3551 // Checks wether the debug mode is enabled
3552 function isDebugModeEnabled () {
3553         // Simply check it
3554         return isBooleanConstantAndTrue('DEBUG_MODE');
3555 }
3556
3557 // Checks wether the cache instance is valid
3558 function isCacheInstanceValid () {
3559         return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
3560 }
3561
3562 // Our shutdown-function
3563 function shutdown () {
3564         // Call the filter chain 'shutdown'
3565         runFilterChain('shutdown', null, false);
3566
3567         if (SQL_IS_LINK_UP()) {
3568                 // Close link
3569                 SQL_CLOSE(__FILE__, __LINE__);
3570         } elseif ((!isInstalling()) && (isInstalled())) {
3571                 // No database link
3572                 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3573         }
3574
3575         // Stop executing here
3576         exit;
3577 }
3578
3579 // Setter for userid
3580 function setUserId ($userid) {
3581         $GLOBALS['userid'] = bigintval($userid);
3582 }
3583
3584 // Getter for userid or returns zero
3585 function getUserId () {
3586         // Default userid
3587         $userid = 0;
3588
3589         // Is the userid set?
3590         if (isUserIdSet()) {
3591                 // Then use it
3592                 $userid = $GLOBALS['userid'];
3593         } // END - if
3594
3595         // Return it
3596         return $userid;
3597 }
3598
3599 // Checks ether the userid is set
3600 function isUserIdSet () {
3601         return (isset($GLOBALS['userid']));
3602 }
3603
3604 // Checks wether the given FQFN is a directory and not .,.. or .svn
3605 function isDirectory ($FQFN) {
3606         // Generate baseName
3607         $baseName = basename($FQFN);
3608
3609         // Check it
3610         $isDirectory = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != ".svn"));
3611
3612         // Return the result
3613         return $isDirectory;
3614 }
3615
3616 // Handle message codes from URL
3617 function handleCodeMessage () {
3618         if (REQUEST_ISSET_GET(('msg'))) {
3619                 // Default extension is "unknown"
3620                 $ext = "unknown";
3621
3622                 // Is extension given?
3623                 if (REQUEST_ISSET_GET(('ext'))) $ext = REQUEST_GET(('ext'));
3624
3625                 // Convert the 'msg' parameter from URL to a human-readable message
3626                 $msg = convertCodeToMessage(REQUEST_GET('msg'));
3627
3628                 // Load message template
3629                 LOAD_TEMPLATE("message", false, $msg);
3630         } // END - if
3631 }
3632
3633 //////////////////////////////////////////////////
3634 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3635 //////////////////////////////////////////////////
3636 //
3637 if (!function_exists('html_entity_decode')) {
3638         // Taken from documentation on www.php.net
3639         function html_entity_decode ($string) {
3640                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3641                 $trans_tbl = array_flip($trans_tbl);
3642                 return strtr($string, $trans_tbl);
3643         }
3644 } // END - if
3645
3646 // [EOF]
3647 ?>