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