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