a1d9b344f625bbcb0694f77ce52c51c4464ce4df
[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  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software; you can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License, or    *
21  * (at your option) any later version.                                  *
22  *                                                                      *
23  * This program is distributed in the hope that it will be useful,      *
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
26  * GNU General Public License for more details.                         *
27  *                                                                      *
28  * You should have received a copy of the GNU General Public License    *
29  * along with this program; if not, write to the Free Software          *
30  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
37         require($INC);
38 }
39
40 // Check if our config file is writeable or not
41 function IS_INC_WRITEABLE($inc) {
42         // Generate FQFN
43         $fqfn = sprintf("%sinc/%s.php", PATH, $inc);
44
45         // Abort by simple test
46         if ((FILE_READABLE($fqfn)) && (!is_writeable($fqfn))) {
47                 return false;
48         } // END - if
49
50         // Test if we can append data
51         $fp = @fopen($fqfn, 'a');
52         if ($inc == "dummy") {
53                 // Remove dummy file
54                 @fclose($fp);
55                 return @unlink($fqfn);
56         } else {
57                 // Close all other files
58                 return @fclose($fp);
59         }
60 }
61
62 // Open a table (you may want to add some header stuff here)
63 function OPEN_TABLE($PERCENT = "", $CLASS = "", $ALIGN="left", $VALIGN="", $td_only=false) {
64         global $table_cnt;
65
66         // Count tables so we can generate CSS classes for every table... :-)
67         if (empty($CLASS)) {
68                 // Class is empty so count one up and create a class
69                 $table_cnt++; $CLASS = "class".$table_cnt;
70         }
71         $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
72
73         // Shall I add the classes to TABLE and TD or only to TD?
74         if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
75
76         // Width is given
77         if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
78
79         // Horizonal align
80         if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
81
82         // Vertical align is given
83         if (!empty($VALIGN))  $OUT .= " valign=\"".$VALIGN."\"";
84         $OUT .= ">\n<TR>\n<TD";
85         if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
86         $OUT .= " class=\"".$CLASS."\">";
87         OUTPUT_HTML($OUT);
88 }
89
90 // Close a table (you may want to add some footer stuff here)
91 function CLOSE_TABLE($ADD="") {
92         OUTPUT_HTML("  </TD>\n</TR>");
93         if (!empty($ADD)) OUTPUT_HTML($ADD);
94         OUTPUT_HTML("</TABLE>");
95 }
96
97 // Output HTML code directly or "render" it. You addionally switch the new-line character off
98 function OUTPUT_HTML($HTML, $NEW_LINE = true) {
99         // Some global variables
100         global $OUTPUT, $footer, $CSS;
101
102         // Do we have HTML-Code here?
103         if (!empty($HTML)) {
104                 // Yes, so we handle it as you have configured
105                 switch (OUTPUT_MODE)
106                 {
107                 case "render":
108                         // That's why you don't need any \n at the end of your HTML code... :-)
109                         if (_OB_CACHING == "on") {
110                                 // Output into PHP's internal buffer
111                                 OUTPUT_RAW($HTML);
112
113                                 // That's why you don't need any \n at the end of your HTML code... :-)
114                                 if ($NEW_LINE) echo "\n";
115                         } else {
116                                 // Render mode for old or lame servers...
117                                 $OUTPUT .= $HTML;
118
119                                 // That's why you don't need any \n at the end of your HTML code... :-)
120                                 if ($NEW_LINE) $OUTPUT .= "\n";
121                         }
122                         break;
123
124                 case "direct":
125                         // If we are switching from render to direct output rendered code
126                         if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
127
128                         // The same as above... ^
129                         OUTPUT_RAW($HTML);
130                         if ($NEW_LINE) echo "\n";
131                         break;
132
133                 default:
134                         // Huh, something goes wrong or maybe you have edited config.php ???
135                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", OUTPUT_MODE));
136                         MXCHANGE_DIE("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
137                         break;
138                 }
139         } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
140                 // Output cached HTML code
141                 $OUTPUT = ob_get_contents();
142
143                 // Clear output buffer for later output
144                 ob_end_clean();
145
146                 // Send HTTP header
147                 header("HTTP/1.1 200");
148
149                 // Used later
150                 $now = gmdate('D, d M Y H:i:s') . ' GMT';
151
152                 // General headers for no caching
153                 header("Expired: " . $now); // RFC2616 - Section 14.21
154                 header("Last-Modified: " . $now);
155                 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
156                 header("Pragma: no-cache"); // HTTP/1.0
157                 header("Connection: Close");
158
159                 // Extension "rewrite" installed?
160                 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
161                         $OUTPUT = REWRITE_LINKS($OUTPUT);
162                 } // END - if
163
164                 // Compile and run finished rendered HTML code
165                 while (strpos($OUTPUT, '{!') > 0) {
166                         // Prepare the content and eval() it...
167                         $newContent = "";
168                         $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
169                         @eval($eval);
170
171                         // Was that eval okay?
172                         if (empty($newContent)) {
173                                 // Something went wrong!
174                                 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
175                         } // END - if
176                         $OUTPUT = $newContent;
177                 } // END - while
178
179                 // Output code here, DO NOT REMOVE! ;-)
180                 OUTPUT_RAW($OUTPUT);
181         } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
182                 // Rewrite links when rewrite extension is active
183                 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
184                         $OUTPUT = REWRITE_LINKS($OUTPUT);
185                 } // END - if
186
187                 // Compile and run finished rendered HTML code
188                 while (strpos($OUTPUT, '{!') > 0) {
189                         $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
190                         eval($eval);
191                 } // END - while
192
193                 // Output code here, DO NOT REMOVE! ;-)
194                 OUTPUT_RAW($OUTPUT);
195         }
196 }
197
198 // Output the raw HTML code
199 function OUTPUT_RAW ($HTML) {
200         // Output stripped HTML code to avoid broken JavaScript code, etc.
201         echo stripslashes(stripslashes($HTML));
202
203         // Flush the output if only _OB_CACHING is not "on"
204         if (_OB_CACHING != "on") {
205                 // Flush it
206                 flush();
207         } // END - if
208 }
209
210 // Add a fatal error message to the queue array
211 function ADD_FATAL ($message, $extra="") {
212         global $FATAL;
213
214         if (empty($extra)) {
215                 // Regular text message to add to $FATAL
216                 $FATAL[] = $message;
217         } else {
218                 // $message is text with a mask plus extras to insert into the text
219                 $message = sprintf($message, $extra);
220                 $FATAL[] = $message;
221         }
222
223         // Log fatal messages away
224         DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
225 }
226
227 // Load a template file and return it's content (only it's name; do not use ' or ")
228 function LOAD_TEMPLATE($template, $return=false, $content=array()) {
229         // Add more variables which you want to use in your template files
230         global $DATA, $_CONFIG, $username;
231
232         // Make all template names lowercase
233         $template = strtolower($template);
234
235         // Count the template load
236         if (getConfig('num_templates') == null) {
237                 $_CONFIG['num_templates'] = 1;
238         } else {
239                 $_CONFIG['num_templates']++;
240         }
241
242         // Prepare IP number and User Agent
243         $REMOTE_ADDR     = GET_REMOTE_ADDR();
244         if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
245         $HTTP_USER_AGENT = GET_USER_AGENT();
246
247         // Init some data
248         $ret = "";
249         if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
250
251         // @DEPRECATED Try to rewrite the if() condition
252         if ($template == "member_support_form") {
253                 // Support request of a member
254                 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
255                         array($GLOBALS['userid']), __FILE__, __LINE__);
256
257                 // Is content an array?
258                 if (is_array($content)) {
259                         // Merge data
260                         $content = merge_array($content, SQL_FETCHARRAY($result));
261
262                         // Translate gender
263                         $content['gender'] = TRANSLATE_GENDER($content['gender']);
264                 } else {
265                         // DEPRECATED: Load data in direct variables
266                         list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
267
268                         // Translate gender
269                         $gender = TRANSLATE_GENDER($gender);
270                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
271                 }
272
273                 // Free result
274                 SQL_FREERESULT($result);
275         } // END - if
276
277         // Generate date/time string
278         $date_time = MAKE_DATETIME(time(), "1");
279
280         // Base directory
281         $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
282         $MODE = "";
283
284         // Check for admin/guest/member templates
285         if (strpos($template, "admin_") > -1) {
286                 // Admin template found
287                 $MODE = "admin/";
288         } elseif (strpos($template, "guest_") > -1) {
289                 // Guest template found
290                 $MODE = "guest/";
291         } elseif (strpos($template, "member_") > -1) {
292                 // Member template found
293                 $MODE = "member/";
294         } elseif (strpos($template, "install_") > -1) {
295                 // Installation template found
296                 $MODE = "install/";
297         } elseif (strpos($template, "ext_") > -1) {
298                 // Extension template found
299                 $MODE = "ext/";
300         } elseif (strpos($template, "la_") > -1) {
301                 // "Logical-area" template found
302                 $MODE = "la/";
303         } else {
304                 // Test for extension
305                 $test = substr($template, 0, strpos($template, "_"));
306                 if (EXT_IS_ACTIVE($test)) {
307                         // Set extra path to extension's name
308                         $MODE = $test."/";
309                 }
310         }
311
312         ////////////////////////
313         // Generate file name //
314         ////////////////////////
315         $file = $BASE.$MODE.$template.".tpl";
316
317         if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
318                 // Select what depended header/footer template file for admin/guest/member area
319                 $file2 = sprintf("%s%s%s_%s.tpl",
320                         $BASE,
321                         $MODE,
322                         $template,
323                         SQL_ESCAPE($GLOBALS['what'])
324                 );
325
326                 // Probe for it...
327                 if (FILE_READABLE($file2)) $file = $file2;
328
329                 // Remove variable from memory
330                 unset($file2);
331         }
332
333         // Does the special template exists?
334         if (!FILE_READABLE($file)) {
335                 // Reset to default template
336                 $file = $BASE.$template.".tpl";
337         } // END - if
338
339         // Now does the final template exists?
340         if (FILE_READABLE($file)) {
341                 // The local file does exists so we load it. :)
342                 $tmpl_file = implode("", file($file));
343
344                 // Replace ' to our own chars to preventing them being quoted
345                 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
346
347                 // Do we have to compile the code?
348                 $ret = "";
349                 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
350                         // Okay, compile it!
351                         $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
352                         eval($tmpl_file);
353                 } else {
354                         // Simply return loaded code
355                         $ret = $tmpl_file;
356                 }
357
358                 // Add surrounding HTML comments to help finding bugs faster
359                 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
360         } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
361                 // Only admins shall see this warning or when installation mode is active
362                 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
363 (".basename($file).")<br />
364 <br />
365 ".TEMPLATE_CONTENT."
366 <pre>".print_r($content, true)."</pre>
367 ".TEMPLATE_DATA."
368 <pre>".print_r($DATA, true)."</pre>
369 <br /><br />";
370         }
371
372         // Remove content and data
373         unset($content);
374         unset($DATA);
375
376         // Do we have some content to output or return?
377         if (!empty($ret)) {
378                 // Not empty so let's put it out! ;)
379                 if ($return) {
380                         // Return the HTML code
381                         return $ret;
382                 } else {
383                         // Output direct
384                         OUTPUT_HTML($ret);
385                 }
386         } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
387                 // Warning, empty output!
388                 return "E:".$template."<br />\n";
389         }
390 }
391
392 // Send mail out to an email address
393 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
394         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
395
396         // Compile subject line (for POINTS constant etc.)
397         $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
398         eval($eval);
399
400         // Set from header
401         if ((!eregi("@", $TO)) && ($TO > 0)) {
402                 // Value detected, is the message extension installed?
403                 if (EXT_IS_ACTIVE("msg")) {
404                         ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
405                         return;
406                 } else {
407                         // Load email address
408                         $result_email = SQL_QUERY_ESC("SELECT email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
409                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
410
411                         // Does the user exist?
412                         if (SQL_NUMROWS($result_email)) {
413                                 // Load email address
414                                 list($TO) = SQL_FETCHROW($result_email);
415                         } else {
416                                 // Set webmaster
417                                 $TO = WEBMASTER;
418                         }
419
420                         // Free result
421                         SQL_FREERESULT($result_email);
422                 }
423         } elseif ("$TO" == "0") {
424                 // Is the webmaster!
425                 $TO = WEBMASTER;
426         }
427         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
428
429         // Check for PHPMailer or debug-mode
430         if (!CHECK_PHPMAILER_USAGE()) {
431                 // Not in PHPMailer-Mode
432                 if (empty($FROM)) {
433                         // Load email header template
434                         $FROM = LOAD_EMAIL_TEMPLATE("header");
435                 } else {
436                         // Append header
437                         $FROM .= LOAD_EMAIL_TEMPLATE("header");
438                 }
439         } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
440                 if (empty($FROM)) {
441                         // Load email header template
442                         $FROM = LOAD_EMAIL_TEMPLATE("header");
443                 } else {
444                         // Append header
445                         $FROM .= LOAD_EMAIL_TEMPLATE("header");
446                 }
447         }
448
449         // Compile "TO"
450         $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
451         eval($eval);
452
453         // Compile "MSG"
454         $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
455         eval($eval);
456
457         // Fix HTML parameter (default is no!)
458         if (empty($HTML)) $HTML = "N";
459         if (isBooleanConstantAndTrue('DEBUG_MODE')) {
460                 // In debug mode we want to display the mail instead of sending it away so we can debug this part
461                 echo "<pre>
462 ".htmlentities(trim($FROM))."
463 To      : ".$TO."
464 Subject : ".$SUBJECT."
465 Message : ".$MSG."
466 </pre>\n";
467
468                 // Log the mail away
469                 if (defined('DEBUG_MAIL')) DEBUG_LOG(__FUNCTION__, __LINE__, "to={$TO},subject={$SUBJECT},msg={$MSG}");
470         } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
471                 // Send mail as HTML away
472                 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
473         } elseif (!empty($TO)) {
474                 // Send Mail away
475                 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
476         } elseif ($HTML == "N") {
477                 // Problem found!
478                 SEND_RAW_EMAIL(WEBMASTER, "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
479         }
480 }
481
482 // Check if legacy or PHPMailer command
483 // @private
484 function CHECK_PHPMAILER_USAGE() {
485         return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
486 }
487
488 /*
489  * Send out a raw email with PHPMailer class or legacy mail() command
490  */
491 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
492         // Shall we use PHPMailer class or legacy mode?
493         if (CHECK_PHPMAILER_USAGE()) {
494                 // Use PHPMailer class with SMTP enabled
495                 require_once(PATH."inc/phpmailer/class.phpmailer.php");
496                 require_once(PATH."inc/phpmailer/class.smtp.php");
497
498                 // get new instance
499                 $mail = new PHPMailer();
500                 $mail->PluginDir  = sprintf("%sinc/phpmailer/", PATH);
501
502                 $mail->IsSMTP();
503                 $mail->SMTPAuth   = true;
504                 $mail->Host       = SMTP_HOSTNAME;
505                 $mail->Port       = 25;
506                 $mail->Username   = SMTP_USER;
507                 $mail->Password   = SMTP_PASSWORD;
508                 if (empty($from)) {
509                         $mail->From = WEBMASTER;
510                 } else {
511                         $mail->From = $from;
512                 }
513                 $mail->FromName   = MAIN_TITLE;
514                 $mail->Subject    = $subject;
515                 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
516                         $mail->Body       = $msg;
517                         $mail->AltBody    = "Your mail program required HTML support to read this mail!";
518                         $mail->WordWrap   = 70;
519                         $mail->IsHTML(true);
520                 } else {
521                         $mail->Body       = html_entity_decode($msg);
522                 }
523                 $mail->AddAddress($to, "");
524                 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
525                 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
526                 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
527                 $mail->Send();
528         } else {
529                 // Use legacy mail() command
530                 @mail($to, $subject, html_entity_decode($msg), $from);
531         }
532 }
533 //
534
535 // Generate a password in a specified length or use default password length
536 function GEN_PASS($LEN = 0) {
537         global $_CONFIG;
538         if ($LEN == 0) $LEN = getConfig('pass_len');
539
540         // Initialize array with all allowed chars
541         $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,-,+,_,/");
542
543         // Initialize randomizer
544         mt_srand((double) microtime() * 1000000);
545
546         // Start creating password
547         $PASS = "";
548         for ($i = 0; $i < $LEN; $i++) {
549                 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
550         } // END - for
551
552         // When the size is below 40 we can also add additional security by scrambling it
553         if (strlen($PASS) <= 40) {
554                 // Also scramble the password
555                 $PASS = scrambleString($PASS);
556         } // END - if
557
558         // Return the password
559         return $PASS;
560 }
561 //
562 function MAKE_DATETIME ($time, $mode="0")
563 {
564         if ($time == 0) {
565                 // Never happend
566                 return NEVER_HAPPENED;
567         } else {
568                 // Filter out numbers
569                 $time = bigintval($time);
570         }
571
572         switch (GET_LANGUAGE())
573         {
574         case "de": // German date / time format
575                 switch ($mode) {
576                         case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
577                         case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
578                         case "2": $ret = date("d.m.Y|H:i", $time); break;
579                         case "3": $ret = date("d.m.Y", $time); break;
580                         default:
581                                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
582                                 break;
583                 }
584                 break;
585
586         default:        // Default is the US date / time format!
587                 switch ($mode) {
588                         case "0": $ret = date("r", $time); break;
589                         case "1": $ret = date("Y-m-d - g:i A", $time); break;
590                         case "2": $ret = date("y-m-d|H:i", $time); break;
591                         case "3": $ret = date("y-m-d", $time); break;
592                         default:
593                                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
594                                 break;
595                 }
596         }
597         return $ret;
598 }
599
600 // Translates the american decimal dot into a german comma
601 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
602         global $_CONFIG;
603
604         // Default is 3 you can change this in admin area "Misc -> Misc Options"
605         if (getConfig('max_comma') == null) $_CONFIG['max_comma'] = "3";
606
607         // Use from config is default
608         $maxComma = getConfig('max_comma');
609
610         // Use from parameter?
611         if ($max > 0) $maxComma = $max;
612
613         // Cut zeros off?
614         if (($cut) && ($max == 0)) {
615                 // Test for commata if in cut-mode
616                 $com = explode(".", $dotted);
617                 if (count($com) < 2) {
618                         // Don't display commatas even if there are none... ;-)
619                         $maxComma = 0;
620                 }
621         } // END - if
622
623         // Debug log
624         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
625
626         // Translate it now
627         switch (GET_LANGUAGE()) {
628         case "de":
629                 $dotted = number_format($dotted, $maxComma, ",", ".");
630                 break;
631
632         default:
633                 $dotted = number_format($dotted, $maxComma, ".", ",");
634                 break;
635         }
636
637         // Return translated value
638         return $dotted;
639 }
640
641 //
642 function DEREFERER ($URL) {
643         // Don't de-refer our own links!
644         if (substr($URL, 0, strlen(URL)) != URL) {
645                 // De-refer this link
646                 $URL = URL."/modules.php?module=loader&amp;url=".urlencode(base64_encode(gzcompress($URL)));
647         } // END - if
648
649         // Return link
650         return $URL;
651 }
652
653 //
654 function TRANSLATE_GENDER ($gender) {
655         switch ($gender)
656         {
657                 case "M": $ret = GENDER_M; break;
658                 case "F": $ret = GENDER_F; break;
659                 case "C": $ret = GENDER_C; break;
660                 default : $ret = $gender; break;
661         }
662         return $ret;
663 }
664 //
665 function FRAMETESTER($URL) {
666         // Prepare frametester URL
667         $frametesterUrl = sprintf("%s/modules.php?module=frametester&amp;url=%s",
668                 URL,
669                 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
670         );
671         return $frametesterUrl;
672 }
673 //
674 function SELECTION_COUNT($array) {
675         $ret = 0;
676         if (is_array($array)) {
677                 foreach ($array as $key => $sel) {
678                         if (!empty($sel)) $ret++;
679                 }
680         }
681         return $ret;
682 }
683 //
684 function IMG_CODE ($code, $type, $DATA, $uid) {
685         return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&amp;".$type."=".$DATA."&amp;mode=img&amp;code=".$code."\">";
686 }
687 //
688 function TRANSLATE_STATUS($status) {
689         switch ($status)
690         {
691         case "UNCONFIRMED":
692                 $ret = ACCOUNT_UNCONFIRMED;
693                 break;
694
695         case "CONFIRMED":
696                 $ret = ACCOUNT_CONFIRMED;
697                 break;
698
699         case "LOCKED":
700                 $ret = ACCOUNT_LOCKED;
701                 break;
702
703         case "":
704         case null:
705                 $ret = ACCOUNT_DELETED;
706                 break;
707
708         default:
709                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
710                 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
711                 break;
712         }
713         return $ret;
714 }
715 //
716 function GET_LANGUAGE() {
717         global $cacheArray;
718
719         // Set default return value to default language from config
720         $ret = DEFAULT_LANG;
721
722         // Init variable
723         $lang = "";
724
725         // Is the variable set
726         if (!empty($_GET['mx_lang'])) {
727                 // Accept only first 2 chars
728                 $lang = substr($_GET['mx_lang'], 0, 2);
729         } elseif (isset($cacheArray['language'])) {
730                 // Use cached
731                 $ret = $cacheArray['language'];
732         } elseif (!empty($lang)) {
733                 // Check if main language file does exist
734                 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
735                         // Okay found, so let's update cookies
736                         SET_LANGUAGE($lang);
737                 }
738         } elseif (!isSessionVariableSet('mx_lang')) {
739                 // Return stored value from cookie
740                 $ret = get_session('mx_lang');
741
742                 // Fixes a warning before the session has the mx_lang constant
743                 if (empty($ret)) $ret = DEFAULT_LANG;
744         }
745
746         // Cache entry
747         $cacheArray['language'] = $ret;
748
749         // Return value
750         return $ret;
751 }
752 //
753 function SET_LANGUAGE($lang) {
754         global $_CONFIG;
755
756         // Accept only first 2 chars!
757         $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
758
759         // Set cookie
760         set_session("mx_lang", $lang);
761 }
762 //
763 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
764         global $DATA, $_CONFIG, $REPLACER;
765
766         // Make sure all template names are lowercase!
767         $template = strtolower($template);
768
769         // Default "nickname" if extension is not installed
770         $nick = "---";
771
772         // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
773         // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
774
775         // Prepare IP number and User Agent
776         $REMOTE_ADDR     = GET_REMOTE_ADDR();
777         $HTTP_USER_AGENT = GET_USER_AGENT();
778
779         // Default admin
780         $ADMIN = MAIN_TITLE;
781
782         // Is the admin logged in?
783         if (IS_ADMIN()) {
784                 // Get admin id
785                 $aid = GET_CURRENT_ADMIN_ID();
786
787                 // Load Admin data
788                 $ADMIN = GET_ADMIN_EMAIL($aid);
789         } // END - if
790
791         // Neutral email address is default
792         $email = WEBMASTER;
793
794         // Expiration in a nice output format
795         if (getConfig('auto_purge') == 0) {
796                 // Will never expire!
797                 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
798         } elseif (function_exists('CREATE_FANCY_TIME')) {
799                 // Create nice date string
800                 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
801         } else {
802                 // Display days only
803                 $EXPIRATION = round(getConfig('auto_purge')/60/60/24)." "._DAYS;
804         }
805
806         // Is content an array?
807         if (is_array($content)) {
808                 // Add expiration to array, $EXPIRATION is now deprecated!
809                 $content['expiration'] = $EXPIRATION;
810         } // END - if
811
812         // Load user's data
813         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
814         if (($UID > 0) && (is_array($content))) {
815                 // If nickname extension is installed, fetch nickname as well
816                 if (EXT_IS_ACTIVE("nickname")) {
817                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
818                         // Load nickname
819                         $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
820                                 array(bigintval($UID)), __FILE__, __LINE__);
821                 } else {
822                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
823                         /// Load normal data
824                         $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
825                                 array(bigintval($UID)), __FILE__, __LINE__);
826                 }
827
828                 // Fetch and merge data
829                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
830                 $content = merge_array($content, SQL_FETCHARRAY($result));
831                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
832
833                 // Free result
834                 SQL_FREERESULT($result);
835         } // END - if
836
837         // Translate M to male or F to female if present
838         if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
839
840         // Overwrite email from data if present
841         if (isset($content['email'])) $email = $content['email'];
842
843         // Store email for some functions in global data array
844         $DATA['email'] = $email;
845
846         // Base directory
847         $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
848
849         // Check for admin/guest/member templates
850         if (strpos($template, "admin_") > -1) {
851                 // Admin template found
852                 $file = $BASE."admin/".$template.".tpl";
853         } elseif (strpos($template, "guest_") > -1) {
854                 // Guest template found
855                 $file = $BASE."guest/".$template.".tpl";
856         } elseif (strpos($template, "member_") > -1) {
857                 // Member template found
858                 $file = $BASE."member/".$template.".tpl";
859         } else {
860                 // Test for extension
861                 $test = substr($template, 0, strpos($template, "_"));
862                 if (EXT_IS_ACTIVE($test)) {
863                         // Set extra path to extension's name
864                         $file = $BASE.$test."/".$template.".tpl";
865                 } else {
866                         // No special filename
867                         $file = $BASE.$template.".tpl";
868                 }
869         }
870
871         // Does the special template exists?
872         if (!FILE_READABLE($file)) {
873                 // Reset to default template
874                 $file = $BASE.$template.".tpl";
875         } // END - if
876
877         // Now does the final template exists?
878         $newContent = "";
879         if (FILE_READABLE($file)) {
880                 // The local file does exists so we load it. :)
881                 $tmpl_file = implode("", file($file));
882                 $tmpl_file = addslashes($tmpl_file);
883
884                 // Run code
885                 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
886                 @eval($tmpl_file);
887         } elseif (!empty($template)) {
888                 // Template file not found!
889                 $newContent = TEMPLATE_404.": ".$template."<br />
890 ".TEMPLATE_CONTENT."
891 <pre>".print_r($content, true)."</pre>
892 ".TEMPLATE_DATA."
893 <pre>".print_r($DATA, true)."</pre>
894 <br /><br />";
895
896                 // Debug mode not active? Then remove the HTML tags
897                 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
898         } else {
899                 // No template name supplied!
900                 $newContent = NO_TEMPLATE_SUPPLIED;
901         }
902
903         // Is there some content?
904         if (empty($newContent)) {
905                 // Compiling failed
906                 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
907                 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
908         } // END - if
909
910         // Remove content and data
911         unset($content);
912         unset($DATA);
913
914         // Return compiled content
915         return COMPILE_CODE($newContent);
916 }
917 //
918 function MAKE_TIME($H, $M, $S, $stamp) {
919         // Extract day, month and year from given timestamp
920         $DAY   = date("d", $stamp);
921         $MONTH = date("m", $stamp);
922         $YEAR  = date('Y', $stamp);
923
924         // Create timestamp for wished time which depends on extracted date
925         return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
926 }
927 //
928 function LOAD_URL($URL, $addUrlData=true) {
929         global $CSS, $_CONFIG, $footer;
930
931         // Compile out URI codes
932         $URL = COMPILE_CODE($URL);
933
934         // Check if http(s):// is there
935         if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
936                 // Make all URLs full-qualified
937                 $URL = URL."/".$URL;
938         }
939
940         // Get output buffer
941         $OUTPUT = ob_get_contents();
942
943         // Clear it only if there is content
944         if (!empty($OUTPUT)) {
945                 ob_end_clean();
946         } // END - if
947
948         // Add some data to URL if cookies are not accepted
949         if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
950
951         // Probe for bot from search engine
952         if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT())) || (eregi("spider", GET_USER_AGENT()))) {
953                 // Search engine bot detected so let's rewrite many chars for the link
954                 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
955
956                 // Output new location link as anchor
957                 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
958         } elseif (!headers_sent()) {
959                 // Load URL when headers are not sent
960                 /*
961                 print("<pre>");
962                 debug_print_backtrace();
963                 die("</pre>URL={$URL}");
964                 */
965                 @header ("Location: ".str_replace("&amp;", "&", $URL));
966         } else {
967                 // Output error message
968                 include(PATH."inc/header.php");
969                 LOAD_TEMPLATE("redirect_url", false, str_replace("&amp;", "&", $URL));
970                 include(PATH."inc/footer.php");
971         }
972         exit();
973 }
974 //
975 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
976         global $SEC_CHARS, $URL_CHARS;
977         // Is the code a string?
978         if (!is_string($code)) {
979                 // Silently return it
980                 return $code;
981         } // END - if
982
983         $ARRAY = $SEC_CHARS;
984
985         // Select smaller set of chars to replace when we e.g. want to compile URLs
986         if (!$full) $ARRAY = $URL_CHARS;
987
988         // Compile constants
989         if ($constants) {
990                 // BEFORE 0.2.1 : Language and data constants
991                 // WITH 0.2.1+  : Only language constants
992                 $code = str_replace('{--','".', str_replace('--}','."', $code));
993
994                 // BEFORE 0.2.1 : Not used
995                 // WITH 0.2.1+  : Data constants
996                 $code = str_replace('{!','".', str_replace("!}", '."', $code));
997         } // END - if
998
999         // Compile QUOT and other non-HTML codes
1000         foreach ($ARRAY['to'] as $k => $to) {
1001                 // Do the reversed thing as in inc/libs/security_functions.php
1002                 $code = str_replace($to, $ARRAY['from'][$k], $code);
1003         } // END - foreach
1004
1005         // But shall I keep simple quotes for later use?
1006         if ($simple) $code = str_replace("\'", '{QUOT}', $code);
1007
1008         // Find $content[bla][blub] entries
1009         @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1010
1011         // Are some matches found?
1012         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1013                 // Replace all matches
1014                 $matchesFound = array();
1015                 foreach ($matches[0] as $key => $match) {
1016                         // Fuzzy look has failed by default
1017                         $fuzzyFound = false;
1018
1019                         // Fuzzy look on match if already found
1020                         foreach ($matchesFound as $found => $set) {
1021                                 // Get test part
1022                                 $test = substr($found, 0, strlen($match));
1023
1024                                 // Does this entry exist?
1025                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1026                                 if ($test == $match) {
1027                                         // Match found!
1028                                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1029                                         $fuzzyFound = true;
1030                                         break;
1031                                 } // END - if
1032                         } // END - foreach
1033
1034                         // Skip this entry?
1035                         if ($fuzzyFound) continue;
1036
1037                         // Take all string elements
1038                         if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1039                                 // Replace it in the code
1040                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1041                                 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1042                                 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1043                                 $matchesFound[$key."_".$matches[4][$key]] = 1;
1044                                 $matchesFound[$match] = 1;
1045                         } elseif (!isset($matchesFound[$match])) {
1046                                 // Not yet replaced!
1047                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1048                                 $code = str_replace($match, "\".".$match.".\"", $code);
1049                                 $matchesFound[$match] = 1;
1050                         }
1051                 } // END - foreach
1052         } // END - if
1053
1054         // Return compiled code
1055         return $code;
1056 }
1057 //
1058 /************************************************************************
1059  *                                                                      *
1060  * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!)       *
1061  * $a_sort sortiert:                                                    *
1062  *                                                                      *
1063  * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1064  * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben    *
1065  * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird   *
1066  * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A             *
1067  * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren   *
1068  *                                                                      *
1069  * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array    *
1070  * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1071  * Sie, dass es doch nicht so schwer ist! :-)                           *
1072  *                                                                      *
1073  ************************************************************************/
1074 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1075 {
1076         $dummy = $array;
1077         while ($primary_key < count($a_sort)) {
1078                 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1079                         foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1080                                 $match = false;
1081                                 if (!$nums) {
1082                                         // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1083                                         if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1084                                 } elseif ($key != $key2) {
1085                                         // Sort numbers (E.g.: 9 < 10)
1086                                         if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1087                                         if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1))  $match = true;
1088                                 }
1089
1090                                 if ($match) {
1091                                         // We have found two different values, so let's sort whole array
1092                                         foreach ($dummy as $sort_key => $sort_val) {
1093                                                 $t                       = $dummy[$sort_key][$key];
1094                                                 $dummy[$sort_key][$key]  = $dummy[$sort_key][$key2];
1095                                                 $dummy[$sort_key][$key2] = $t;
1096                                                 unset($t);
1097                                         } // END - foreach
1098                                 } // END - if
1099                         } // END - foreach
1100                 } // END - foreach
1101
1102                 // Count one up
1103                 $primary_key++;
1104         } // END - while
1105
1106         // Write back sorted array
1107         $array = $dummy;
1108 }
1109 //
1110 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1111         global $MONTH_DESCR, $_CONFIG;
1112         $OUT = "";
1113
1114         if ($type == "yn") {
1115                 // This is a yes/no selection only!
1116                 if ($id > 0) $prefix .= "[".$id."]";
1117                 $OUT .= "    <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1118         } else {
1119                 // Begin with regular selection box here
1120                 if (!empty($prefix)) $prefix .= "_";
1121                 $type2 = $type;
1122                 if ($id > 0) $type2 .= "[".$id."]";
1123                 $OUT .= "    <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1124         }
1125
1126         switch ($type) {
1127         case "day": // Day
1128                 for ($idx = 1; $idx < 32; $idx++) {
1129                         $OUT .= "<OPTION value=\"".$idx."\"";
1130                         if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1131                         $OUT .= ">".$idx."</OPTION>\n";
1132                 } // END - for
1133                 break;
1134
1135         case "month": // Month
1136                 foreach ($MONTH_DESCR as $month => $descr) {
1137                         $OUT .= "<OPTION value=\"".$month."\"";
1138                         if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1139                         $OUT .= ">".$descr."</OPTION>\n";
1140                 } // END - for
1141                 break;
1142
1143         case "year": // Year
1144                 // Get current year
1145                 $YEAR = date('Y', time());
1146
1147                 // Use configured min age or fixed?
1148                 if (GET_EXT_VERSION("other") >= "0.2.1") {
1149                         // Configured
1150                         $startYear = $YEAR - getConfig('min_age');
1151                 } else {
1152                         // Fixed 16 years
1153                         $startYear = $YEAR - 16;
1154                 }
1155
1156                 // Calculate earliest year (100 years old people can still enter Internet???)
1157                 $minYear = $YEAR - 100;
1158
1159                 // Check if the default value is larger than minimum and bigger than actual year
1160                 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1161                         for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1162                                 $OUT .= "<OPTION value=\"".$idx."\"";
1163                                 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1164                                 $OUT .= ">".$idx."</OPTION>\n";
1165                         } // END - for
1166                 } elseif ($DEFAULT == -1) {
1167                         // Current year minus 1
1168                         for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1169                         {
1170                                 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1171                         }
1172                 } else {
1173                         // Get current year and subtract the configured minimum age
1174                         $OUT .= "<OPTION value=\"".($minYear - 1)."\">&lt;".$minYear."</OPTION>\n";
1175                         // Calculate earliest year depending on extension version
1176                         if (GET_EXT_VERSION("other") >= "0.2.1") {
1177                                 // Use configured minimum age
1178                                 $YEAR = date('Y', time()) - getConfig('min_age');
1179                         } else {
1180                                 // Use fixed 16 years age
1181                                 $YEAR = date('Y', time()) - 16;
1182                         }
1183
1184                         // Construct year selection list
1185                         for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1186                                 $OUT .= "<OPTION value=\"".$idx."\"";
1187                                 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1188                                 $OUT .= ">".$idx."</OPTION>\n";
1189                         } // END - for
1190                 }
1191                 break;
1192
1193         case "sec":
1194         case "min":
1195                 for ($idx = 0; $idx < 60; $idx+=5) {
1196                         if (strlen($idx) == 1) $idx = "0".$idx;
1197                         $OUT .= "<OPTION value=\"".$idx."\"";
1198                         if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1199                         $OUT .= ">".$idx."</OPTION>\n";
1200                 } // END - for
1201                 break;
1202
1203         case "hour":
1204                 for ($idx = 0; $idx < 24; $idx++) {
1205                         if (strlen($idx) == 1) $idx = "0".$idx;
1206                         $OUT .= "<OPTION value=\"".$idx."\"";
1207                         if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1208                         $OUT .= ">".$idx."</OPTION>\n";
1209                 } // END - for
1210                 break;
1211
1212         case "yn":
1213                 $OUT .= "<OPTION value=\"Y\"";
1214                 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1215                 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1216                 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1217                 $OUT .= ">".NO."</OPTION>\n";
1218                 break;
1219         }
1220         $OUT .= "    </SELECT>\n";
1221         return $OUT;
1222 }
1223 //
1224 function TRANSLATE_YESNO($yn)
1225 {
1226         switch ($yn)
1227         {
1228                 case "Y": $yn = YES; break;
1229                 case "N": $yn = NO; break;
1230                 default : $yn = "??? (".$yn.")"; break;
1231         }
1232         return $yn;
1233 }
1234 //
1235 // Deprecated : $length
1236 // Optional   : $DATA
1237 //
1238 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1239         global $_CONFIG;
1240
1241         // Fix missing _MAX constant
1242         if (!defined('_MAX')) define('_MAX', 15235);
1243
1244         // Build server string
1245         $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1246
1247         // Build key string
1248         $keys   = SITE_KEY.":".DATE_KEY;
1249         if (getConfig('secret_key') != null)  $keys .= ":".getConfig('secret_key');
1250         if (getConfig('file_hash') != null)   $keys .= ":".getConfig('file_hash');
1251         $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1252         if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1253
1254         // Build string from misc data
1255         $data   = $code.":".$uid.":".$DATA;
1256
1257         // Add more additional data
1258         if (isSessionVariableSet('u_hash'))                     $data .= ":".get_session('u_hash');
1259         if (isset($GLOBALS['userid']))                          $data .= ":".$GLOBALS['userid'];
1260         if (isSessionVariableSet('lifetime'))           $data .= ":".get_session('lifetime');
1261         if (isSessionVariableSet('mxchange_theme'))     $data .= ":".get_session('mxchange_theme');
1262         if (isSessionVariableSet('mx_lang'))            $data .= ":".GET_LANGUAGE();
1263         if (isset($GLOBALS['refid']))                           $data .= ":".$GLOBALS['refid'];
1264
1265         // Calculate number for generating the code
1266         $a = $code + _ADD - 1;
1267
1268         if (getConfig('master_hash') != null) {
1269                 // Generate hash with master salt from modula of number with the prime number and other data
1270                 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1271
1272                 // Create number from hash
1273                 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1274         } else {
1275                 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1276                 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1277
1278                 // Create number from hash
1279                 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1280         }
1281
1282         // At least 10 numbers shall be secure enought!
1283         $len = getConfig('code_length');
1284         if ($len == 0) $len = $length;
1285         if ($len == 0) $len = 10;
1286
1287         // Cut off requested counts of number
1288         $return = substr(str_replace('.', "", $rcode), 0, $len);
1289
1290         // Done building code
1291         return $return;
1292 }
1293 // Does only allow numbers
1294 function bigintval($num, $castValue = true) {
1295         // Filter all numbers out
1296         $ret = preg_replace("/[^0123456789]/", "", $num);
1297
1298         // Shall we cast?
1299         if ($castValue) $ret = (double)$ret;
1300
1301         // Has the whole value changed?
1302         if ("".$ret."" != "".$num."") {
1303                 // Log the values
1304                 print("<pre>");
1305                 debug_print_backtrace();
1306                 die("</pre>");
1307                 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1308         } // END - if
1309
1310         // Return result
1311         return $ret;
1312 }
1313 // Insert the code in $img_code into jpeg or PNG image
1314 function GENERATE_IMAGE($img_code, $header=true) {
1315         global $_CONFIG;
1316
1317         if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1318                 // Stop execution of function here because of over-sized code length
1319                 return;
1320         } elseif (!$header) {
1321                 // Return in an HTML code code
1322                 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1323         }
1324
1325         // Load image
1326         $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), getConfig('img_type'));
1327         if (FILE_READABLE($img)) {
1328                 // Switch image type
1329                 switch (getConfig('img_type'))
1330                 {
1331                 case "jpg":
1332                         // Okay, load image and hide all errors
1333                         $image = @imagecreatefromjpeg($img);
1334                         break;
1335
1336                 case "png":
1337                         // Okay, load image and hide all errors
1338                         $image = @imagecreatefrompng($img);
1339                         break;
1340                 }
1341         } else {
1342                 // Exit function here
1343                 return;
1344         }
1345
1346         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1347         $text_color = imagecolorallocate($image, 0, 0, 0);
1348
1349         // Insert code into image
1350         imagestring($image, 5, 14, 2, $img_code, $text_color);
1351
1352         // Return to browser
1353         header ("Content-Type: image/".getConfig('img_type'));
1354
1355         // Output image with matching image factory
1356         switch (getConfig('img_type')) {
1357                 case "jpg": imagejpeg($image); break;
1358                 case "png": imagepng($image);  break;
1359         }
1360
1361         // Remove image from memory
1362         imagedestroy($image);
1363 }
1364 // Create selection box or array of splitted timestamp
1365 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1366         global $_CONFIG;
1367
1368         // Calculate 2-seconds timestamp
1369         $stamp = round($timestamp);
1370         //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1371
1372         // Do we have a leap year?
1373         $SWITCH = 0;
1374         $TEST = date('Y', time()) / 4;
1375         $M1 = date("m", time());
1376         $M2 = date("m", (time() + $timestamp));
1377
1378         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1379         if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02"))  $SWITCH = getConfig('one_day');
1380
1381         // First of all years...
1382         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1383         //* DEBUG: */ print("Y={$Y}<br />\n");
1384         // Next months...
1385         $M = abs(floor($timestamp / 2628000 - $Y * 12));
1386         //* DEBUG: */ print("M={$M}<br />\n");
1387         // Next weeks
1388         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1389         //* DEBUG: */ print("W={$W}<br />\n");
1390         // Next days...
1391         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1392         //* DEBUG: */ print("D={$D}<br />\n");
1393         // Next hours...
1394         $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));
1395         //* DEBUG: */ print("h={$h}<br />\n");
1396         // Next minutes..
1397         $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));
1398         //* DEBUG: */ print("m={$m}<br />\n");
1399         // And at last seconds...
1400         $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));
1401         //* DEBUG: */ print("s={$s}<br />\n");
1402
1403         // Is seconds zero and time is < 60 seconds?
1404         if (($s == 0) && ($timestamp < 60)) {
1405                 // Fix seconds
1406                 $s = round($timestamp);
1407         } // END - if
1408
1409         //
1410         // Now we convert them in seconds...
1411         //
1412         if ($return_array) {
1413                 // Just put all data in an array for later use
1414                 $OUT = array(
1415                         'YEARS'   => $Y,
1416                         'MONTHS'  => $M,
1417                         'WEEKS'   => $W,
1418                         'DAYS'    => $D,
1419                         'HOURS'   => $h,
1420                         'MINUTES' => $m,
1421                         'SECONDS' => $s
1422                 );
1423         } else {
1424                 // Generate table
1425                 $OUT  = "<DIV align=\"".$align."\">\n";
1426                 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1427                 $OUT .= "<TR>\n";
1428
1429                 if (ereg('Y', $display) || (empty($display))) {
1430                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1431                 }
1432
1433                 if (ereg("M", $display) || (empty($display))) {
1434                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1435                 }
1436
1437                 if (ereg("W", $display) || (empty($display))) {
1438                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1439                 }
1440
1441                 if (ereg("D", $display) || (empty($display))) {
1442                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1443                 }
1444
1445                 if (ereg("h", $display) || (empty($display))) {
1446                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1447                 }
1448
1449                 if (ereg("m", $display) || (empty($display))) {
1450                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1451                 }
1452
1453                 if (ereg("s", $display) || (empty($display))) {
1454                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1455                 }
1456
1457                 $OUT .= "</TR>\n";
1458                 $OUT .= "<TR>\n";
1459
1460                 if (ereg('Y', $display) || (empty($display))) {
1461                         // Generate year selection
1462                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1463                         for ($idx = 0; $idx <= 10; $idx++) {
1464                                 $OUT .= "    <OPTION class=\"mini_select\" value=\"".$idx."\"";
1465                                 if ($idx == $Y) $OUT .= " selected default";
1466                                 $OUT .= ">".$idx."</OPTION>\n";
1467                         }
1468                         $OUT .= "  </SELECT></TD>\n";
1469                 } else {
1470                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1471                 }
1472
1473                 if (ereg("M", $display) || (empty($display))) {
1474                         // Generate month selection
1475                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1476                         for ($idx = 0; $idx <= 11; $idx++)
1477                         {
1478                                         $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1479                                 if ($idx == $M) $OUT .= " selected default";
1480                                 $OUT .= ">".$idx."</OPTION>\n";
1481                         }
1482                         $OUT .= "  </SELECT></TD>\n";
1483                 } else {
1484                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1485                 }
1486
1487                 if (ereg("W", $display) || (empty($display))) {
1488                         // Generate week selection
1489                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1490                         for ($idx = 0; $idx <= 4; $idx++) {
1491                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1492                                 if ($idx == $W) $OUT .= " selected default";
1493                                 $OUT .= ">".$idx."</OPTION>\n";
1494                         }
1495                         $OUT .= "  </SELECT></TD>\n";
1496                 } else {
1497                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1498                 }
1499
1500                 if (ereg("D", $display) || (empty($display))) {
1501                         // Generate day selection
1502                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1503                         for ($idx = 0; $idx <= 31; $idx++) {
1504                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1505                                 if ($idx == $D) $OUT .= " selected default";
1506                                 $OUT .= ">".$idx."</OPTION>\n";
1507                         }
1508                         $OUT .= "  </SELECT></TD>\n";
1509                 } else {
1510                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1511                 }
1512
1513                 if (ereg("h", $display) || (empty($display))) {
1514                         // Generate hour selection
1515                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1516                         for ($idx = 0; $idx <= 23; $idx++)      {
1517                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1518                                 if ($idx == $h) $OUT .= " selected default";
1519                                 $OUT .= ">".$idx."</OPTION>\n";
1520                         }
1521                         $OUT .= "  </SELECT></TD>\n";
1522                 } else {
1523                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1524                 }
1525
1526                 if (ereg("m", $display) || (empty($display))) {
1527                         // Generate minute selection
1528                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1529                         for ($idx = 0; $idx <= 59; $idx++) {
1530                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1531                                 if ($idx == $m) $OUT .= " selected default";
1532                                 $OUT .= ">".$idx."</OPTION>\n";
1533                         }
1534                         $OUT .= "  </SELECT></TD>\n";
1535                 } else {
1536                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1537                 }
1538
1539                 if (ereg("s", $display) || (empty($display))) {
1540                         // Generate second selection
1541                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1542                         for ($idx = 0; $idx <= 59; $idx++) {
1543                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1544                                 if ($idx == $s) $OUT .= " selected default";
1545                                 $OUT .= ">".$idx."</OPTION>\n";
1546                         }
1547                         $OUT .= "  </SELECT></TD>\n";
1548                 } else {
1549                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1550                 }
1551                 $OUT .= "</TR>\n";
1552                 $OUT .= "</TABLE>\n";
1553                 $OUT .= "</DIV>\n";
1554                 // Return generated HTML code
1555         }
1556         return $OUT;
1557 }
1558 //
1559 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1560         global $_CONFIG;
1561         $ret = 0;
1562
1563         // Do we have a leap year?
1564         $SWITCH = 0;
1565         $TEST = date('Y', time()) / 4;
1566         $M1   = date("m", time());
1567         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1568         if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02"))  $SWITCH = getConfig('one_day');
1569         // First add years...
1570         $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1571         // Next months...
1572         $ret += $POST[$prefix."_mo"] * 2628000;
1573         // Next weeks
1574         $ret += $POST[$prefix."_we"] * 604800;
1575         // Next days...
1576         $ret += $POST[$prefix."_da"] * 86400;
1577         // Next hours...
1578         $ret += $POST[$prefix."_ho"] * 3600;
1579         // Next minutes..
1580         $ret += $POST[$prefix."_mi"] * 60;
1581         // And at last seconds...
1582         $ret += $POST[$prefix."_se"];
1583         // Return calculated value
1584         return $ret;
1585 }
1586 // Sends out mail to all administrators
1587 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1588 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1589         // Trim template name
1590         $template = trim($template);
1591
1592         // Load email template
1593         $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1594
1595         if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1596                 // Older version detected!
1597                 return SEND_ADMIN_EMAILS($subj, $msg);
1598         } // END - if
1599
1600         // Check which admin shall receive this mail
1601         $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1602          array($template), __FILE__, __LINE__);
1603         if (SQL_NUMROWS($result) == 0) {
1604                 // Create new entry (to all admins)
1605                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1606                  array($template), __FILE__, __LINE__);
1607         } else {
1608                 // Load admin IDs...
1609                 $aids = array();
1610                 while(list($aid) = SQL_FETCHROW($result)) {
1611                         $aids[] = $aid;
1612                 }
1613
1614                 // Free memory
1615                 SQL_FREERESULT($result);
1616
1617                 // "implode" IDs and query string
1618                 $aid = implode(",", $aids);
1619                 if ($aid == "-1") {
1620                         // Add line to userlog
1621                         USERLOG_ADD_LINE($subj, $msg, $UID);
1622                         return;
1623                 } elseif ($aid == "0") {
1624                         // Select all email adresses
1625                         $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1626                 } else {
1627                         // If Admin-ID is not "to-all" select
1628                         $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1629                 }
1630         }
1631
1632         // Load email addresses and send away
1633         while (list($email) = SQL_FETCHROW($result)) {
1634                 SEND_EMAIL($email, $subj, $msg);
1635         }
1636
1637         // Free memory
1638         SQL_FREERESULT($result);
1639 }
1640 //
1641 function CREATE_FANCY_TIME ($stamp) {
1642         // Get data array with years/months/weeks/days/...
1643         $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1644         $ret = "";
1645         foreach($data as $k => $v) {
1646                 if ($v > 0) {
1647                         // Value is greater than 0 "eval" data to return string
1648                         $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1649                         eval($eval);
1650                         break;
1651                 } // END - if
1652         } // END - foreach
1653
1654         // Do we have something there?
1655         if (strlen($ret) > 0) {
1656                 // Remove leading commata and space
1657                 $ret = substr($ret, 2);
1658         } else {
1659                 // Zero seconds
1660                 $ret = "0 "._SECONDS;
1661         }
1662
1663         // Return fancy time string
1664         return $ret;
1665 }
1666 //
1667 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1668         $SEP = ""; $TOP = "";
1669         if (!$show_form) {
1670                 $TOP = " top2";
1671                 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\">&nbsp;</TD></TR>";
1672         }
1673
1674         $NAV = "";
1675         for ($page = 1; $page <= $PAGES; $page++) {
1676                 // Is the page currently selected or shall we generate a link to it?
1677                 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1678                         // Is currently selected, so only highlight it
1679                         $NAV .= "<STRONG>-";
1680                 } else {
1681                         // Open anchor tag and add base URL
1682                         $NAV .= "<A href=\"".URL."/modules.php?module=admin&amp;what=".$GLOBALS['what']."&amp;page=".$page."&amp;offset=".$offset;
1683
1684                         // Add userid when we shall show all mails from a single member
1685                         if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&amp;u_id=".bigintval($_GET['u_id']);
1686
1687                         // Close open anchor tag
1688                         $NAV .= "\">";
1689                 }
1690                 $NAV .= $page;
1691                 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1692                         // Is currently selected, so only highlight it
1693                         $NAV .= "-</STRONG>";
1694                 } else {
1695                         // Close anchor tag
1696                         $NAV .= "</A>";
1697                 }
1698
1699                 // Add seperator if we have not yet reached total pages
1700                 if ($page < $PAGES) $NAV .= "&nbsp;|&nbsp;";
1701         }
1702
1703         // Define constants only once
1704         if (!defined('__NAV_OUTPUT')) {
1705                 define('__NAV_OUTPUT' , $NAV);
1706                 define('__NAV_COLSPAN', $colspan);
1707                 define('__NAV_TOP'    , $TOP);
1708                 define('__NAV_SEP'    , $SEP);
1709         }
1710
1711         // Load navigation template
1712         $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1713
1714         if ($return) {
1715                 // Return generated HTML-Code
1716                 return $OUT;
1717         } else {
1718                 // Output HTML-Code
1719                 OUTPUT_HTML($OUT);
1720         }
1721 }
1722
1723 // Extract host from script name
1724 function EXTRACT_HOST (&$script) {
1725         // Use default SERVER_URL by default... ;) So?
1726         $url = SERVER_URL;
1727
1728         // Is this URL valid?
1729         if (substr($script, 0, 7) == "http://") {
1730                 // Use the hostname from script URL as new hostname
1731                 $url = substr($script, 7);
1732                 $extract = explode("/", $url);
1733                 $url = $extract[0];
1734                 // Done extracting the URL :)
1735         } // END - if
1736
1737         // Extract host name
1738         $host = str_replace("http://", "", $url);
1739         if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1740
1741         // Generate relative URL
1742         //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1743         if (substr(strtolower($script), 0, 7) == "http://") {
1744                 // But only if http:// is in front!
1745                 $script = substr($script, (strlen($url) + 7));
1746         } elseif (substr(strtolower($script), 0, 8) == "https://") {
1747                 // Does this work?!
1748                 $script = substr($script, (strlen($url) + 8));
1749         }
1750
1751         //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1752         if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1753
1754         // Return host name
1755         return $host;
1756 }
1757
1758 // Send a GET request
1759 function GET_URL ($script) {
1760         // Compile the script name
1761         $script = COMPILE_CODE($script);
1762
1763         // Extract host name from script
1764         $host = EXTRACT_HOST($script);
1765
1766         // Generate GET request header
1767         $request  = "GET /" . trim($script) . " HTTP/1.1\r\n";
1768         $request .= "Host: " . $host . "\r\n";
1769         $request .= "Referer: " . URL . "/admin.php\r\n";
1770         $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1771         $request .= "Content-Type: text/plain\r\n";
1772         $request .= "Cache-Control: no-cache\r\n";
1773         $request .= "Connection: Close\r\n\r\n";
1774
1775         // Send the raw request
1776         $response = SEND_RAW_REQUEST($host, $request);
1777
1778         // Return the result to the caller function
1779         return $response;
1780 }
1781
1782 // Send a POST request
1783 function POST_URL ($script, $postData) {
1784         // Is postData an array?
1785         if (!is_array($postData)) {
1786                 // Abort here
1787                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1788                 return array("", "", "");
1789         } // END - if
1790
1791         // Compile the script name
1792         $script = COMPILE_CODE($script);
1793
1794         // Extract host name from script
1795         $host = EXTRACT_HOST($script);
1796
1797         // Construct request
1798         $data = http_build_query($postData, '','&');
1799
1800         // Generate POST request header
1801         $request  = "POST /" . trim($script) . " HTTP/1.1\r\n";
1802         $request .= "Host: " . $host . "\r\n";
1803         $request .= "Referer: " . URL . "/admin.php\r\n";
1804         $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1805         $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1806         $request .= "Content-length: " . strlen($data) . "\r\n";
1807         $request .= "Cache-Control: no-cache\r\n";
1808         $request .= "Connection: Close\r\n\r\n";
1809         $request .= $data;
1810
1811         // Send the raw request
1812         $response = SEND_RAW_REQUEST($host, $request);
1813
1814         // Return the result to the caller function
1815         return $response;
1816 }
1817
1818 // Sends a raw request to another host
1819 function SEND_RAW_REQUEST ($host, $request) {
1820         global $_CONFIG;
1821
1822         // Initialize array
1823         $response = array("", "", "");
1824
1825         // Default is not to use proxy
1826         $useProxy = false;
1827
1828         // Are proxy settins set?
1829         if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1830                 // Then use it
1831                 $useProxy = true;
1832         } // END - if
1833
1834         // Open connection
1835         //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1836         if ($useProxy) {
1837                 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1838         } else {
1839                 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1840         }
1841
1842         // Is there a link?
1843         if (!is_resource($fp)) {
1844                 // Failed!
1845                 return $response;
1846         } // END - if
1847
1848         // Do we use proxy?
1849         if ($useProxy) {
1850                 // Generate CONNECT request header
1851                 $proxyTunnel  = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1852                 $proxyTunnel .= "Host: ".$host."\r\n";
1853
1854                 // Use login data to proxy? (username at least!)
1855                 if (getConfig('proxy_username') != "") {
1856                         // Add it as well
1857                         $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1858                         $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1859                 } // END - if
1860
1861                 // Add last new-line
1862                 $proxyTunnel .= "\r\n";
1863                 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1864
1865                 // Write request
1866                 fputs($fp, $proxyTunnel);
1867
1868                 // Got response?
1869                 if (feof($fp)) {
1870                         // No response received
1871                         return $response;
1872                 } // END - if
1873
1874                 // Read the first line
1875                 $resp = trim(fgets($fp, 10240));
1876                 $respArray = explode(" ", $resp);
1877                 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1878                         // Invalid response!
1879                         return $response;
1880                 } // END - if
1881         } // END - if
1882
1883         // Write request
1884         fputs($fp, $request);
1885
1886         // Read response
1887         while(!feof($fp)) {
1888                 $response[] = trim(fgets($fp, 1024));
1889         } // END - while
1890
1891         // Close socket
1892         fclose($fp);
1893
1894         // Skip first empty lines
1895         $resp = $response;
1896         foreach ($resp as $idx => $line) {
1897                 // Trim space away
1898                 $line = trim($line);
1899
1900                 // Is this line empty?
1901                 if (empty($line)) {
1902                         // Then remove it
1903                         array_shift($response);
1904                 } else {
1905                         // Abort on first non-empty line
1906                         break;
1907                 }
1908         } // END - foreach
1909
1910         //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1911
1912         // Proxy agent found?
1913         if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1914                 // Proxy header detected, so remove two lines
1915                 array_shift($response);
1916                 array_shift($response);
1917         } // END - if
1918
1919         // Was the request successfull?
1920         if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1921                 // Not found / access forbidden
1922                 $response = array("", "", "");
1923         } // END - if
1924
1925         // Return response
1926         return $response;
1927 }
1928 // Taken from www.php.net eregi() user comments
1929 function VALIDATE_EMAIL($email) {
1930         // Compile email
1931         $email = COMPILE_CODE($email);
1932
1933         // Check first part of email address
1934         $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1935
1936         //  Check domain
1937         $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1938
1939         // Generate pattern
1940         $regex = "^".$first."@".$domain."$";
1941
1942         // Return check result
1943         return eregi($regex, $email);
1944 }
1945 // Function taken from user comments on www.php.net / function eregi()
1946 function VALIDATE_URL ($URL, $compile=true) {
1947         // Trim URL a little
1948         $URL = trim(urldecode($URL));
1949         //* DEBUG: */ echo $URL."<br />";
1950
1951         // Compile some chars out...
1952         if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1953         //* DEBUG: */ echo $URL."<br />";
1954
1955         // Check for the extension filter
1956         if (EXT_IS_ACTIVE("filter")) {
1957                 // Use the extension's filter set
1958                 return FILTER_VALIDATE_URL($URL, false);
1959         }
1960
1961         // If not installed, perform a simple test. Just make it sure there is always a http:// or
1962         // https:// in front of the URLs
1963         return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1964 }
1965 //
1966 function MEMBER_ACTION_LINKS($uid, $status="") {
1967         // Define all main targets
1968         $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1969
1970         // Begin of navigation links
1971         $eval = "\$OUT = \"[&nbsp;";
1972
1973         foreach ($TARGETS as $tar) {
1974                 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&amp;what=".$tar."&amp;u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1975                 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1976                 if (($tar == "lock_user") && ($status == "LOCKED")) {
1977                         // Locked accounts shall be unlocked
1978                         $eval .= "UNLOCK_USER";
1979                 } else {
1980                         // All other status is fine
1981                         $eval .= strtoupper($tar);
1982                 }
1983                 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1984                 if (($tar == "lock_user") && ($status == "LOCKED")) {
1985                         // Locked accounts shall be unlocked
1986                         $eval .= "UNLOCK_USER";
1987                 } else {
1988                         // All other status is fine
1989                         $eval .= strtoupper($tar);
1990                 }
1991                 $eval .= ".\"</A></SPAN>&nbsp;|&nbsp;";
1992         }
1993
1994         // Finish navigation link
1995         $eval = substr($eval, 0, -7)."]\";";
1996         eval($eval);
1997
1998         // Return string
1999         return $OUT;
2000 }
2001 // Function for backward-compatiblity
2002 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
2003         // Load it from the register extension
2004         return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
2005 }
2006 // Generate an email link
2007 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2008         // Default email link (INSECURE! Spammer can read this by harvester programs)
2009         $EMAIL = "mailto:".$email;
2010
2011         // Check for several extensions
2012         if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2013                 // Create email link for contacting admin in guest area
2014                 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2015         } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2016                 // Create email link for contacting a member within admin area (or later in other areas, too?)
2017                 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2018         } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2019                 // Create email link to contact sponsor within admin area (or like the link above?)
2020                 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2021         }
2022
2023         // Shall I close the link when there is no admin?
2024         if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2025
2026         // Return email link
2027         return $EMAIL;
2028 }
2029 // Generate a hash for extra-security for all passwords
2030 function generateHash ($plainText, $salt = "") {
2031         global $_CONFIG, $_SERVER;
2032
2033         // Is the required extension "sql_patches" there and a salt is not given?
2034         if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2035                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2036                 return md5($plainText);
2037         } // END - if
2038
2039         // Do we miss an arry element here?
2040         if (getConfig('file_hash') == null) {
2041                 // Stop here
2042                 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2043                 debug_print_backtrace();
2044                 die("</pre>");
2045         } // END - if
2046
2047         // When the salt is empty build a new one, else use the first x configured characters as the salt
2048         if (empty($salt)) {
2049                 // Build server string
2050                 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2051
2052                 // Build key string
2053                 $keys   = SITE_KEY.":".DATE_KEY.":".getConfig('secret_key').":".getConfig('file_hash').":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime'))).":".getConfig('master_salt');
2054
2055                 // Additional data
2056                 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2057
2058                 // Calculate number for generating the code
2059                 $a = time() + _ADD - 1;
2060
2061                 // Generate SHA1 sum from modula of number and the prime number
2062                 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2063                 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2064                 $sha1 = scrambleString($sha1);
2065                 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2066                 //* DEBUG: */ $sha1b = descrambleString($sha1);
2067                 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2068
2069                 // Generate the password salt string
2070                 $salt = substr($sha1, 0, getConfig('salt_length'));
2071                 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2072         } else {
2073                 // Use given salt
2074                 $salt = substr($salt, 0, getConfig('salt_length'));
2075                 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2076         }
2077
2078         // Return hash
2079         return $salt.sha1($salt.$plainText);
2080 }
2081 //
2082 function scrambleString($str) {
2083         global $_CONFIG;
2084
2085         // Init
2086         $scrambled = "";
2087
2088         // Final check, in case of failture it will return unscrambled string
2089         if (strlen($str) > 40) {
2090                 // The string is to long
2091                 return $str;
2092         } elseif (strlen($str) == 40) {
2093                 // From database
2094                 $scrambleNums = explode(":", getConfig('pass_scramble'));
2095         } else {
2096                 // Generate new numbers
2097                 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2098         }
2099
2100         // Scramble string here
2101         //* DEBUG: */ echo "***Original=".$str."***<br />";
2102         for ($idx = 0; $idx < strlen($str); $idx++) {
2103                 // Get char on scrambled position
2104                 $char = substr($str, $scrambleNums[$idx], 1);
2105
2106                 // Add it to final output string
2107                 $scrambled .= $char;
2108         } // END - for
2109
2110         // Return scrambled string
2111         //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2112         return $scrambled;
2113 }
2114 //
2115 function descrambleString($str) {
2116         global $_CONFIG;
2117         // Scramble only 40 chars long strings
2118         if (strlen($str) != 40) return $str;
2119
2120         // Load numbers from config
2121         $scrambleNums = explode(":", getConfig('pass_scramble'));
2122
2123         // Validate numbers
2124         if (count($scrambleNums) != 40) return $str;
2125
2126         // Begin descrambling
2127         $orig = str_repeat(" ", 40);
2128         //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2129         for ($idx = 0; $idx < 40; $idx++) {
2130                 $char = substr($str, $idx, 1);
2131                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2132         } // END - for
2133
2134         // Return scrambled string
2135         //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2136         return $orig;
2137 }
2138 //
2139 function genScrambleString($len) {
2140         // Prepare randomizer and array for the numbers
2141         mt_srand((double) microtime() * 1000000);
2142         $scrambleNumbers = array();
2143
2144         // First we need to setup randomized numbers from 0 to 31
2145         for ($idx = 0; $idx < $len; $idx++) {
2146                 // Generate number
2147                 $rand = mt_rand(0, ($len -1));
2148
2149                 // Check for it by creating more numbers
2150                 while (array_key_exists($rand, $scrambleNumbers)) {
2151                         $rand = mt_rand(0, ($len -1));
2152                 } // END - while
2153
2154                 // Add number
2155                 $scrambleNumbers[$rand] = $rand;
2156         } // END - for
2157
2158         // So let's create the string for storing it in database
2159         $scrambleString = implode(":", $scrambleNumbers);
2160         return $scrambleString;
2161 }
2162 // Append data like session ID or referal ID to the given URL which would
2163 // normally be stored in cookies
2164 function ADD_URL_DATA($URL) {
2165         global $_CONFIG;
2166         $ADD = "";
2167
2168         // Determine URL binder
2169         $BIND = "?";
2170         if (strpos($URL, "?") !== false) $BIND = "&";
2171
2172         if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2173                 // Cookies are not accepted
2174                 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2175                         // Cookie found in URL
2176                         $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2177                 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2178                         // Not found! So let's set default here
2179                         $ADD .= $BIND."refid=".getConfig('def_refid');
2180                 }
2181
2182                 // Is there already added data? Then change the binder
2183                 if (!empty($ADD)) $BIND = "&";
2184
2185                 // Add session ID
2186                 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2187                         // Add session from URL
2188                         $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2189                 } else {
2190                         // Add current session
2191                         $ADD .= $BIND."PHPSESSID=".session_id();
2192                 }
2193         } // END - if
2194
2195         // Add all together and return it
2196         return $URL.$ADD;
2197 }
2198 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2199 function generatePassString($passHash) {
2200         global $_CONFIG;
2201
2202         // Return vanilla password hash
2203         $ret = $passHash;
2204
2205         // Is a secret key and master salt already initialized?
2206         if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2207                 // Only calculate when the secret key is generated
2208                 $newHash = ""; $start = 9;
2209                 for ($idx = 0; $idx < 10; $idx++) {
2210                         $part1 = hexdec(substr($passHash, $start, 4));
2211                         $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2212                         $mod = dechex($idx);
2213                         if ($part1 > $part2) {
2214                                 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2215                         } elseif ($part2 > $part1) {
2216                                 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2217                         }
2218                         $mod = substr(round($mod), 0, 4);
2219                         $mod = str_repeat('0', 4-strlen($mod)).$mod;
2220                         //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2221                         $start += 4;
2222                         $newHash .= $mod;
2223                 } // END - for
2224
2225                 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2226                 $ret = generateHash($newHash, getConfig('master_salt'));
2227                 //* DEBUG: */ print($ret."<br />\n");
2228         } else {
2229                 // Hash it simple
2230                 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2231                 $ret = md5($passHash);
2232                 //* DEBUG: */ echo "++".$ret."++<br />\n";
2233         }
2234
2235         // Return result
2236         return $ret;
2237 }
2238
2239 // Fix "deleted" cookies
2240 function FIX_DELETED_COOKIES ($cookies) {
2241         // Is this an array with entries?
2242         if ((is_array($cookies)) && (count($cookies) > 0)) {
2243                 // Then check all cookies if they are marked as deleted!
2244                 foreach ($cookies as $cookieName) {
2245                         // Is the cookie set to "deleted"?
2246                         if (get_session($cookieName) == "deleted") {
2247                                 set_session($cookieName, "");
2248                         }
2249                 } // END - foreach
2250         } // END - if
2251 }
2252
2253 // Output error messages in a fasioned way and die...
2254 function mxchange_die ($msg) {
2255         global $footer;
2256
2257         // Load the message template
2258         LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2259
2260         // Load footer
2261         include(PATH."inc/footer.php");
2262
2263         // Exit explicitly
2264         exit;
2265 }
2266
2267 // Display parsing time and number of SQL queries in footer
2268 function DISPLAY_PARSING_TIME_FOOTER() {
2269         global $_CONFIG;
2270
2271         // Is the timer started?
2272         if (!isset($GLOBALS['startTime'])) {
2273                 // Abort here
2274                 return false;
2275         } // END - if
2276
2277         // Get end time
2278         $endTime = microtime(true);
2279
2280         // "Explode" both times
2281         $start = explode(" ", $GLOBALS['startTime']);
2282         $end = explode(" ", $endTime);
2283         $runTime = $end[0] - $start[0];
2284         if ($runTime < 0) $runTime = 0;
2285         $runTime = TRANSLATE_COMMA($runTime);
2286
2287         // Prepare output
2288         $content = array(
2289                 'runtime'               => $runTime,
2290                 'numSQLs'               => (getConfig('sql_count') + 1),
2291                 'numTemplates'  => (getConfig('num_templates') + 1)
2292         );
2293
2294         // Load the template
2295         LOAD_TEMPLATE("show_timings", false, $content);
2296 }
2297
2298 // Unset/set session variables
2299 function set_session ($var, $value) {
2300         global $CSS;
2301
2302         // Abort in CSS mode here
2303         if ($CSS == 1) return true;
2304
2305         // Trim value and session variable
2306         $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2307
2308         // Is the session variable set?
2309         if (("".$value."" == "") && (isSessionVariableSet($var))) {
2310                 // Remove the session
2311                 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2312                 unset($_SESSION[$var]);
2313                 return session_unregister($var);
2314         } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2315                 // Set session
2316                 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2317                 $_SESSION[$var] =  $value;
2318                 return session_register($var);
2319         } elseif (!empty($value)) {
2320                 // Update session
2321                 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2322                 $_SESSION[$var] = $value;
2323                 return true;
2324         }
2325
2326         // Ignored (but valid)
2327         //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2328         return true;
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         global $cacheArray;
2335
2336         // Failed by default
2337         $res = false;
2338
2339         // In cache?
2340         if (isset($cacheArray['const'][$constName])) {
2341                 // Use cache
2342                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2343                 $res = $cacheArray['const'][$constName];
2344         } else {
2345                 // Check constant
2346                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2347                 if (defined($constName)) $res = (constant($constName) === true);
2348
2349                 // Set cache
2350                 $cacheArray['const'][$constName] = $res;
2351         }
2352         //* DEBUG: */ var_dump($res);
2353
2354         // Return value
2355         return $res;
2356 }
2357
2358 // Check wether a session variable is set
2359 function isSessionVariableSet ($var) {
2360         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2361         return (isset($_SESSION[$var]));
2362 }
2363 // Returns wether the value of the session variable or NULL if not set
2364 function get_session ($var) {
2365         global $cacheArray;
2366
2367         // Default is not found! ;-)
2368         $value = null;
2369
2370         // Is the variable there or cached values?
2371         if (isset($cacheArray['session'][$var])) {
2372                 // Get cached value (skips a lot SQL_ESCAPE() calles!
2373                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2374                 $value = $cacheArray['session'][$var];
2375         } elseif (isSessionVariableSet($var)) {
2376                 // Then  get it secured!
2377                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2378                 $value = SQL_ESCAPE($_SESSION[$var]);
2379
2380                 // Cache the value
2381                 $cacheArray['session'][$var] = $value;
2382         } // END - if
2383
2384         // Return the value
2385         return $value;
2386 }
2387 // Send notification to admin
2388 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2389         if (GET_EXT_VERSION("admins") >= "0.4.1") {
2390                 // Send new way
2391                 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2392         } else {
2393                 // Send outdated way
2394                 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2395                 SEND_ADMIN_EMAILS($subject, $msg);
2396         }
2397 }
2398 // Destroy user session
2399 function destroy_user_session () {
2400         // Remove all user data from session
2401         return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2402 }
2403 // Merges an array together but only if both are arrays
2404 function merge_array ($array1, $array2) {
2405         // Are both an array?
2406         if ((is_array($array1)) && (is_array($array2))) {
2407                 // Merge all together
2408                 return array_merge($array1, $array2);
2409         } elseif (is_array($array1)) {
2410                 // Return left array
2411                 return $array1;
2412         }
2413
2414         // Something wired happened here...
2415         print(__FUNCTION__.":<pre>");
2416         debug_print_backtrace();
2417         die("</pre>");
2418 }
2419 // Debug message logger
2420 function DEBUG_LOG ($file, $line, $message, $force=true) {
2421         // Is debug mode enabled?
2422         if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2423                 // Log this message away
2424                 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2425                 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2426                 fclose($fp);
2427         } // END - if
2428 }
2429 // Reads a directory with PHP files in and gets only files back
2430 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2431         $INCs = array();
2432
2433         // Open directory
2434         $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2435
2436         // Read all entries
2437         while ($baseFile = readdir($dirPointer)) {
2438                 // Load file only if extension is active
2439                 // Make full path
2440                 $file = $baseDir.$baseFile;
2441
2442                 // Is this a valid reset file?
2443                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2444                 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2445                         // Remove both for extension name
2446                         $extName = substr($baseFile, strlen($prefix), -4);
2447
2448                         // Try to find it
2449                         $extId = GET_EXT_ID($extName);
2450
2451                         // Is the extension valid and active?
2452                         if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2453                                 // Then add this file
2454                                 $INCs[] = $file;
2455                         } elseif ($extId == 0) {
2456                                 // Add non-extension files as well
2457                                 $INCs[] = $file;
2458                         }
2459                 } // END - if
2460         } // END - while
2461
2462         // Close directory
2463         closedir($dirPointer);
2464
2465         // Sort array
2466         asort($INCs);
2467
2468         // Return array with include files
2469         return $INCs;
2470 }
2471 // Load more reset scripts
2472 function RESET_ADD_INCLUDES () {
2473         global $_CONFIG;
2474
2475         // Is the reset set or old sql_patches?
2476         if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2477                 // Then abort here
2478                 return array();
2479         } // END - if
2480
2481         // Get more daily reset scripts
2482         $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2483
2484         // Update database
2485         if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2486
2487         // Create current week mark
2488         $currWeek = date("W", time());
2489
2490         // Has it changed?
2491         if (getConfig('last_week') != $currWeek) {
2492                 // Include weekly reset scripts
2493                 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2494
2495                 // Update config
2496                 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2497         } // END - if
2498
2499         // Create current month mark
2500         $currMonth = date("m", time());
2501
2502         // Has it changed?
2503         if (getConfig('last_month') != $currMonth) {
2504                 // Include monthly reset scripts
2505                 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2506
2507                 // Update config
2508                 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2509         } // END - if
2510
2511         // Return array
2512         return $INC_POOL;
2513 }
2514 // Handle extra values
2515 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2516         // Default is the value itself
2517         $ret = $value;
2518
2519         // Do we have a special filter function?
2520         if (!empty($filterFunction)) {
2521                 // Does the filter function exist?
2522                 if (function_exists($filterFunction)) {
2523                         // Do we have extra parameters here?
2524                         if (!empty($extraValue)) {
2525                                 // Put both parameters in one new array by default
2526                                 $args = array($value, $extraValue);
2527
2528                                 // If we have an array simply use it and pre-extend it with our value
2529                                 if (is_array($extraValue)) {
2530                                         // Make the new args array
2531                                         $args = merge_array(array($value), $extraValue);
2532                                 } // END - if
2533
2534                                 // Call the multi-parameter call-back
2535                                 $ret = call_user_func_array($filterFunction, $args);
2536                         } else {
2537                                 // One parameter call
2538                                 $ret = call_user_func($filterFunction, $value);
2539                         }
2540                 } // END - if
2541         } // END - if
2542
2543         // Return the value
2544         return $ret;
2545 }
2546 // Check if given FQFN is a readable file
2547 function FILE_READABLE($fqfn) {
2548         // Check all...
2549         return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2550 }
2551 // Converts timestamp selections into a timestamp
2552 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2553         // Init test variable
2554         $test2 = "";
2555
2556         // Get last three chars
2557         $test = substr($id, -3);
2558
2559         // Improved way of checking! :-)
2560         if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2561                 // Found a multi-selection for timings?
2562                 $test = substr($id, 0, -3);
2563                 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)) {
2564                         // Generate timestamp
2565                         $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2566                         $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2567
2568                         // Remove data from array
2569                         foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2570                                 unset($POST[$test."_".$rem]);
2571                         } // END - foreach
2572
2573                         // Skip adding
2574                         unset($id); $skip = true; $test2 = $test;
2575                 } // END - if
2576         } else {
2577                 // Process this entry
2578                 $skip = false; $test2 = "";
2579         }
2580 }
2581 // Reverts the german decimal comma into Computer decimal dot
2582 function REVERT_COMMA ($str) {
2583         // Default float is not a float... ;-)
2584         $float = false;
2585
2586         // Which language is selected?
2587         switch (GET_LANGUAGE()) {
2588                 case "de": // German language
2589                         // Remove german thousand dots first
2590                         $str = str_replace(".", "", $str);
2591
2592                         // Replace german commata with decimal dot and cast it
2593                         $float = (float)str_replace(",", ".", $str);
2594                         break;
2595
2596                 default: // US and so on
2597                         // Remove thousand dots first and cast
2598                         $float = (float)str_replace(",", "", $str);
2599                         break;
2600         }
2601
2602         // Return float
2603         return $float;
2604 }
2605 // Handle menu-depending failed logins and return the rendered content
2606 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2607         // Default output is empty ;-)
2608         $OUT = "";
2609
2610         // Is the session data set?
2611         if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2612                 // Ignore zero values
2613                 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2614                         // Non-guest has login failtures found, get both data and prepare it for template
2615                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2616                         $content = array(
2617                                 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2618                                 'last_failture'   => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2619                         );
2620
2621                         // Load template
2622                         $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2623                 } // END - if
2624
2625                 // Reset session data
2626                 set_session('mxchange_'.$accessLevel.'_failtures', "");
2627                 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2628         } // END - if
2629
2630         // Return rendered content
2631         return $OUT;
2632 }
2633 // Rebuild cache
2634 function REBUILD_CACHE ($cache, $inc="") {
2635         global $cacheInstance, $_CONFIG, $CSS;
2636
2637         // Shall I remove the cache file?
2638         if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2639                 // Rebuild cache
2640                 if ($cacheInstance->loadCacheFile($cache)) {
2641                         // Destroy it
2642                         $cacheInstance->destroyCacheFile();
2643                 } // END - if
2644
2645                 // Include file given?
2646                 if (!empty($inc)) {
2647                         // Construct FQFN
2648                         $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2649
2650                         // Is the include there?
2651                         if (FILE_READABLE($fqfn)) {
2652                                 // And rebuild it from scratch
2653                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2654                                 require($fqfn);
2655                         } else {
2656                                 // Include not found!
2657                                 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2658                         }
2659                 } // END - if
2660         } // END - if
2661 }
2662 // Purge admin menu cache
2663 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2664         global $cacheInstance;
2665
2666         // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2667         if (!EXT_IS_ACTIVE("cache")) {
2668                 // Cache extension not active
2669                 return false;
2670         } elseif (!is_object($cacheInstance)) {
2671                 // No cache instance!
2672                 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2673                 return false;
2674         } elseif ((getConfig('cache_admin_menu') == null) || (getConfig('cache_admin_menu') == "N")) {
2675                 // Caching disabled (currently experiemental!)
2676                 return false;
2677         }
2678
2679         // Experiemental feature!
2680         trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2681 }
2682 // Translates the "pool type" into human-readable
2683 function TRANSLATE_POOL_TYPE ($type) {
2684         // Default type is unknown
2685         $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2686
2687         // Generate constant
2688         $constName = sprintf("POOL_TYPE_%s", $type);
2689
2690         // Does it exist?
2691         if (defined($constName)) {
2692                 // Then use it
2693                 $translated = constant($constName);
2694         } // END - if
2695
2696         // Return "translation"
2697         return $translated;
2698 }
2699 // "Getter" for remote IP number
2700 function GET_REMOTE_ADDR () {
2701         // Get remote ip from environment
2702         $remoteAddr = getenv('REMOTE_ADDR');
2703
2704         // Is removeip installed?
2705         if (EXT_IS_ACTIVE("removeip")) {
2706                 // Then anonymize it
2707                 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2708         } // END - if
2709
2710         // Return it
2711         return $remoteAddr;
2712 }
2713 // "Getter" for remote hostname
2714 function GET_REMOTE_HOST () {
2715         // Get remote ip from environment
2716         $remoteHost = getenv('REMOTE_HOST');
2717
2718         // Is removeip installed?
2719         if (EXT_IS_ACTIVE("removeip")) {
2720                 // Then anonymize it
2721                 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2722         } // END - if
2723
2724         // Return it
2725         return $remoteHost;
2726 }
2727 // "Getter" for user agent
2728 function GET_USER_AGENT () {
2729         // Get remote ip from environment
2730         $userAgent = getenv('HTTP_USER_AGENT');
2731
2732         // Is removeip installed?
2733         if (EXT_IS_ACTIVE("removeip")) {
2734                 // Then anonymize it
2735                 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2736         } // END - if
2737
2738         // Return it
2739         return $userAgent;
2740 }
2741 // "Getter" for referer
2742 function GET_REFERER () {
2743         // Get remote ip from environment
2744         $referer = getenv('HTTP_REFERER');
2745
2746         // Is removeip installed?
2747         if (EXT_IS_ACTIVE("removeip")) {
2748                 // Then anonymize it
2749                 $referer = GET_ANONYMOUS_REFERER($referer);
2750         } // END - if
2751
2752         // Return it
2753         return $referer;
2754 }
2755
2756 // Adds a bonus mail to the queue
2757 // This is a high-level function!
2758 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2759         // Use mode from data if not set and availble ;-)
2760         if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2761
2762         // Generate receiver list
2763         $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2764
2765         // Receivers added?
2766         if (!empty($RECEIVER)) {
2767                 // Add bonus mail to queue
2768                 ADD_BONUS_MAIL_TO_QUEUE(
2769                         $data['subject'],
2770                         $data['text'],
2771                         $RECEIVER,
2772                         $data['points'],
2773                         $data['seconds'],
2774                         $data['url'],
2775                         $data['cat'],
2776                         $mode,
2777                         $data['receiver']
2778                 );
2779
2780                 // Mail inserted into bonus pool
2781                 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_BONUS_SEND);
2782         } elseif ($output) {
2783                 // More entered than can be reached!
2784                 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_MORE_SELECTED);
2785         } else {
2786                 // Debug log
2787                 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2788         }
2789 }
2790 // Determines referal id and sets it
2791 function DETERMINE_REFID () {
2792         global $_CONFIG, $CLICK, $_SERVER;
2793
2794         // Check if refid is set
2795         if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2796                 // The variable user comes from the click-counter script click.php and we only accept this here
2797                 $GLOBALS['refid'] = bigintval($_GET['user']);
2798         } elseif (!empty($_POST['refid'])) {
2799                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2800                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2801         } elseif (!empty($_GET['refid'])) {
2802                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2803                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2804         } elseif (!empty($_GET['ref'])) {
2805                 // Set refid=ref (the referal link uses such variable)
2806                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2807         } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2808                 // Set session refid als global
2809                 $GLOBALS['refid'] = bigintval(get_session('refid'));
2810         } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2811                 // Set default refid as refid in URL
2812                 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2813         } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2814                 // Select a random user which has confirmed enougth mails
2815                 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2816         } else {
2817                 // No default ID when sql_patches is not installed or none set
2818                 $GLOBALS['refid'] = 0;
2819         }
2820
2821         // Set cookie when default refid > 0
2822         if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2823                 // Set cookie
2824                 set_session('refid', $GLOBALS['refid']);
2825         } // END - if
2826
2827         // Return determined refid
2828         return $GLOBALS['refid'];
2829 }
2830
2831 // Destroys the admin session
2832 function DESTROY_ADMIN_SESSION ($destroy = true) {
2833         // Kill maybe existing session variables including array elements
2834         set_session('admin_login', "");
2835         set_session('admin_md5'  , "");
2836         set_session('admin_last' , "");
2837         set_session('admin_to'   , "");
2838
2839         // Destroy session and return status
2840         if ($destroy) {
2841                 return @session_destroy();
2842         } // END - if
2843
2844         // All fine if we shall not really destroy the session
2845         return true;
2846 }
2847
2848 // Checks if a given apache module is loaded
2849 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2850         // Check it and return result
2851         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2852 }
2853
2854 // Getter for $_CONFIG entries
2855 function getConfig ($entry) {
2856         global $_CONFIG;
2857
2858         // Default value
2859         $value = null;
2860
2861         // Is the entry there?
2862         if (isset($_CONFIG[$entry])) {
2863                 // Then use it
2864                 $value = $_CONFIG[$entry];
2865         } // END - if
2866
2867         // Return it
2868         return $value;
2869 }
2870
2871 //////////////////////////////////////////////////
2872 //                                              //
2873 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2874 //                                              //
2875 //////////////////////////////////////////////////
2876 //
2877 if (!function_exists('html_entity_decode')) {
2878         // Taken from documentation on www.php.net
2879         function html_entity_decode ($string) {
2880                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2881                 $trans_tbl = array_flip($trans_tbl);
2882                 return strtr($string, $trans_tbl);
2883         }
2884 } // END - if
2885
2886 //
2887 ?>