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