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