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