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