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