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