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