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