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