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