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