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