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