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