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