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