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