910c71ffa899f2200f77b260f4ae9f5cf6aec39a
[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 generateRandomCodde ($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\r\n";
1757         $request .= "Host: " . $host . "\r\n";
1758         $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1759         if (defined('FULL_VERSION')) {
1760                 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
1761         } else {
1762                 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?\r\n";
1763         }
1764         $request .= "Content-Type: text/plain\r\n";
1765         $request .= "Cache-Control: no-cache\r\n";
1766         $request .= "Connection: Close\r\n\r\n";
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\r\n";
1795         $request .= "Host: " . $host . "\r\n";
1796         $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1797         $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
1798         $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1799         $request .= "Content-length: " . strlen($data) . "\r\n";
1800         $request .= "Cache-Control: no-cache\r\n";
1801         $request .= "Connection: Close\r\n\r\n";
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         // Initialize array
1814         $response = array('', '', '');
1815
1816         // Default is not to use proxy
1817         $useProxy = false;
1818
1819         // Are proxy settins set?
1820         if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
1821                 // Then use it
1822                 $useProxy = true;
1823         } // END - if
1824
1825         // Open connection
1826         //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1827         if ($useProxy) {
1828                 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1829         } else {
1830                 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1831         }
1832
1833         // Is there a link?
1834         if (!is_resource($fp)) {
1835                 // Failed!
1836                 return $response;
1837         } // END - if
1838
1839         // Do we use proxy?
1840         if ($useProxy) {
1841                 // Generate CONNECT request header
1842                 $proxyTunnel  = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1843                 $proxyTunnel .= "Host: ".$host."\r\n";
1844
1845                 // Use login data to proxy? (username at least!)
1846                 if (getConfig('proxy_username') != '') {
1847                         // Add it as well
1848                         $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).getConfig('ENCRYPT_SEPERATOR').COMPILE_CODE(getConfig('proxy_password')));
1849                         $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1850                 } // END - if
1851
1852                 // Add last new-line
1853                 $proxyTunnel .= "\r\n";
1854                 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1855
1856                 // Write request
1857                 fputs($fp, $proxyTunnel);
1858
1859                 // Got response?
1860                 if (feof($fp)) {
1861                         // No response received
1862                         return $response;
1863                 } // END - if
1864
1865                 // Read the first line
1866                 $resp = trim(fgets($fp, 10240));
1867                 $respArray = explode(' ', $resp);
1868                 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1869                         // Invalid response!
1870                         return $response;
1871                 } // END - if
1872         } // END - if
1873
1874         // Write request
1875         fputs($fp, $request);
1876
1877         // Read response
1878         while (!feof($fp)) {
1879                 $response[] = trim(fgets($fp, 1024));
1880         } // END - while
1881
1882         // Close socket
1883         fclose($fp);
1884
1885         // Skip first empty lines
1886         $resp = $response;
1887         foreach ($resp as $idx => $line) {
1888                 // Trim space away
1889                 $line = trim($line);
1890
1891                 // Is this line empty?
1892                 if (empty($line)) {
1893                         // Then remove it
1894                         array_shift($response);
1895                 } else {
1896                         // Abort on first non-empty line
1897                         break;
1898                 }
1899         } // END - foreach
1900
1901         //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1902
1903         // Proxy agent found?
1904         if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy)) {
1905                 // Proxy header detected, so remove two lines
1906                 array_shift($response);
1907                 array_shift($response);
1908         } // END - if
1909
1910         // Was the request successfull?
1911         if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1912                 // Not found / access forbidden
1913                 $response = array('', '', '');
1914         } // END - if
1915
1916         // Return response
1917         return $response;
1918 }
1919
1920 // Taken from www.php.net eregi() user comments
1921 function isEmailValid ($email) {
1922         // Compile email
1923         $email = COMPILE_CODE($email);
1924
1925         // Check first part of email address
1926         $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1927
1928         //  Check domain
1929         $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1930
1931         // Generate pattern
1932         $regex = '@^' . $first . '\@' . $domain . '$@iU';
1933
1934         // Return check result
1935         // @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
1936         return preg_match($regex, $email);
1937 }
1938
1939 // Function taken from user comments on www.php.net / function eregi()
1940 function isUrlValid ($URL, $compile=true) {
1941         // Trim URL a little
1942         $URL = trim(urldecode($URL));
1943         //* DEBUG: */ echo $URL."<br />";
1944
1945         // Compile some chars out...
1946         if ($compile) $URL = compileUriCode($URL, false, false, false);
1947         //* DEBUG: */ echo $URL."<br />";
1948
1949         // Check for the extension filter
1950         if (EXT_IS_ACTIVE('filter')) {
1951                 // Use the extension's filter set
1952                 return FILTER_isUrlValid($URL, false);
1953         } // END - if
1954
1955         // If not installed, perform a simple test. Just make it sure there is always a http:// or
1956         // https:// in front of the URLs
1957         return isUrlValidSimple($URL);
1958 }
1959
1960 // Generate a list of administrative links to a given userid
1961 function generateMemberAdminActionLinks ($uid, $status = '') {
1962         // Define all main targets
1963         $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1964
1965         // Begin of navigation links
1966         $eval = "\$OUT = \"[&nbsp;";
1967
1968         foreach ($TARGETS as $tar) {
1969                 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&amp;what=".$tar."&amp;uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1970                 //* DEBUG: */ echo "*".$tar.'/'.$status."*<br />\n";
1971                 if (($tar == "lock_user") && ($status == 'LOCKED')) {
1972                         // Locked accounts shall be unlocked
1973                         $eval .= "UNLOCK_USER";
1974                 } else {
1975                         // All other status is fine
1976                         $eval .= strtoupper($tar);
1977                 }
1978                 $eval .= "_TITLE--}\\\">{--ADMIN_";
1979                 if (($tar == "lock_user") && ($status == 'LOCKED')) {
1980                         // Locked accounts shall be unlocked
1981                         $eval .= "UNLOCK_USER";
1982                 } else {
1983                         // All other status is fine
1984                         $eval .= strtoupper($tar);
1985                 }
1986                 $eval .= "--}</a></span>&nbsp;|&nbsp;";
1987         }
1988
1989         // Finish navigation link
1990         $eval = substr($eval, 0, -7)."]\";";
1991         eval($eval);
1992
1993         // Return string
1994         return $OUT;
1995 }
1996
1997 // Generate an email link
1998 function generateMemberEmailLink ($email, $table = 'admins') {
1999         // Default email link (INSECURE! Spammer can read this by harvester programs)
2000         $EMAIL = 'mailto:' . $email;
2001
2002         // Check for several extensions
2003         if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
2004                 // Create email link for contacting admin in guest area
2005                 $EMAIL = adminsCreateEmailLink($email);
2006         } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
2007                 // Create email link for contacting a member within admin area (or later in other areas, too?)
2008                 $EMAIL = USER_generateMemberEmailLink($email);
2009         } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
2010                 // Create email link to contact sponsor within admin area (or like the link above?)
2011                 $EMAIL = SPONSOR_generateMemberEmailLink($email);
2012         }
2013
2014         // Shall I close the link when there is no admin?
2015         if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2016
2017         // Return email link
2018         return $EMAIL;
2019 }
2020
2021 // Generate a hash for extra-security for all passwords
2022 function generateHash ($plainText, $salt = '') {
2023         // Is the required extension 'sql_patches' there and a salt is not given?
2024         if (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('sql_patches'))) && (empty($salt))) {
2025                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2026                 return md5($plainText);
2027         } // END - if
2028
2029         // Do we miss an arry element here?
2030         if (!isConfigEntrySet('file_hash')) {
2031                 // Stop here
2032                 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2033         } // END - if
2034
2035         // When the salt is empty build a new one, else use the first x configured characters as the salt
2036         if (empty($salt)) {
2037                 // Build server string (inc/databases.php is no longer updated with every commit)
2038                 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
2039
2040                 // Build key string
2041                 $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');
2042
2043                 // Additional data
2044                 $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
2045
2046                 // Calculate number for generating the code
2047                 $a = time() + getConfig('_ADD') - 1;
2048
2049                 // Generate SHA1 sum from modula of number and the prime number
2050                 $sha1 = sha1(($a % getConfig('_PRIME')).$server.getConfig('ENCRYPT_SEPERATOR').$keys.getConfig('ENCRYPT_SEPERATOR').$data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').$a);
2051                 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2052                 $sha1 = scrambleString($sha1);
2053                 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2054                 //* DEBUG: */ $sha1b = descrambleString($sha1);
2055                 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2056
2057                 // Generate the password salt string
2058                 $salt = substr($sha1, 0, getConfig('salt_length'));
2059                 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2060         } else {
2061                 // Use given salt
2062                 $salt = substr($salt, 0, getConfig('salt_length'));
2063                 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2064         }
2065
2066         // Return hash
2067         return $salt.sha1($salt.$plainText);
2068 }
2069
2070 // Scramble a string
2071 function scrambleString($str) {
2072         // Init
2073         $scrambled = '';
2074
2075         // Final check, in case of failture it will return unscrambled string
2076         if (strlen($str) > 40) {
2077                 // The string is to long
2078                 return $str;
2079         } elseif (strlen($str) == 40) {
2080                 // From database
2081                 $scrambleNums = explode(':', getConfig('pass_scramble'));
2082         } else {
2083                 // Generate new numbers
2084                 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2085         }
2086
2087         // Scramble string here
2088         //* DEBUG: */ echo "***Original=".$str."***<br />";
2089         for ($idx = 0; $idx < strlen($str); $idx++) {
2090                 // Get char on scrambled position
2091                 $char = substr($str, $scrambleNums[$idx], 1);
2092
2093                 // Add it to final output string
2094                 $scrambled .= $char;
2095         } // END - for
2096
2097         // Return scrambled string
2098         //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2099         return $scrambled;
2100 }
2101
2102 // De-scramble a string scrambled by scrambleString()
2103 function descrambleString($str) {
2104         // Scramble only 40 chars long strings
2105         if (strlen($str) != 40) return $str;
2106
2107         // Load numbers from config
2108         $scrambleNums = explode(':', getConfig('pass_scramble'));
2109
2110         // Validate numbers
2111         if (count($scrambleNums) != 40) return $str;
2112
2113         // Begin descrambling
2114         $orig = str_repeat(" ", 40);
2115         //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2116         for ($idx = 0; $idx < 40; $idx++) {
2117                 $char = substr($str, $idx, 1);
2118                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2119         } // END - for
2120
2121         // Return scrambled string
2122         //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2123         return $orig;
2124 }
2125
2126 // Generated a "string" for scrambling
2127 function genScrambleString ($len) {
2128         // Prepare array for the numbers
2129         $scrambleNumbers = array();
2130
2131         // First we need to setup randomized numbers from 0 to 31
2132         for ($idx = 0; $idx < $len; $idx++) {
2133                 // Generate number
2134                 $rand = mt_rand(0, ($len -1));
2135
2136                 // Check for it by creating more numbers
2137                 while (array_key_exists($rand, $scrambleNumbers)) {
2138                         $rand = mt_rand(0, ($len -1));
2139                 } // END - while
2140
2141                 // Add number
2142                 $scrambleNumbers[$rand] = $rand;
2143         } // END - for
2144
2145         // So let's create the string for storing it in database
2146         $scrambleString = implode(':', $scrambleNumbers);
2147         return $scrambleString;
2148 }
2149
2150 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2151 function generatePassString ($passHash) {
2152         // Return vanilla password hash
2153         $ret = $passHash;
2154
2155         // Is a secret key and master salt already initialized?
2156         if ((getConfig('secret_key') != '') && (getConfig('master_salt') != '')) {
2157                 // Only calculate when the secret key is generated
2158                 $newHash = ''; $start = 9;
2159                 for ($idx = 0; $idx < 10; $idx++) {
2160                         $part1 = hexdec(substr($passHash, $start, 4));
2161                         $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2162                         $mod = dechex($idx);
2163                         if ($part1 > $part2) {
2164                                 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2165                         } elseif ($part2 > $part1) {
2166                                 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2167                         }
2168                         $mod = substr(round($mod), 0, 4);
2169                         $mod = str_repeat('0', 4-strlen($mod)).$mod;
2170                         //* DEBUG: */ echo "*".$start.'='.$mod."*<br />";
2171                         $start += 4;
2172                         $newHash .= $mod;
2173                 } // END - for
2174
2175                 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).')');
2176                 $ret = generateHash($newHash, getConfig('master_salt'));
2177                 //* DEBUG: */ print($ret."<br />\n");
2178         } else {
2179                 // Hash it simple
2180                 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2181                 $ret = md5($passHash);
2182                 //* DEBUG: */ echo "++".$ret."++<br />\n";
2183         }
2184
2185         // Return result
2186         return $ret;
2187 }
2188
2189 // Fix "deleted" cookies
2190 function fixDeletedCookies ($cookies) {
2191         // Is this an array with entries?
2192         if ((is_array($cookies)) && (count($cookies) > 0)) {
2193                 // Then check all cookies if they are marked as deleted!
2194                 foreach ($cookies as $cookieName) {
2195                         // Is the cookie set to "deleted"?
2196                         if (getSession($cookieName) == 'deleted') {
2197                                 setSession($cookieName, '');
2198                         } // END - if
2199                 } // END - foreach
2200         } // END - if
2201 }
2202
2203 // Output error messages in a fasioned way and die...
2204 function app_die ($F, $L, $msg) {
2205         // Check if Script is already dieing and not let it kill itself another 1000 times
2206         if (!isset($GLOBALS['app_died'])) {
2207                 // Make sure, that the script realy realy diese here and now
2208                 $GLOBALS['app_died'] = true;
2209
2210                 // Load header
2211                 loadIncludeOnce('inc/header.php');
2212
2213                 // Prepare message for output
2214                 $msg = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $msg);
2215
2216                 // Load the message template
2217                 LOAD_TEMPLATE('admin_settings_saved', false, $msg);
2218
2219                 // Load footer
2220                 loadIncludeOnce('inc/footer.php');
2221         } else {
2222                 // Script tried to kill itself twice
2223                 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $msg . ', file/function=' . $F . ', line=' . $L);
2224         }
2225 }
2226
2227 // Display parsing time and number of SQL queries in footer
2228 function displayParsingTime() {
2229         // Is the timer started?
2230         if (!isset($GLOBALS['startTime'])) {
2231                 // Abort here
2232                 return false;
2233         } // END - if
2234
2235         // Get end time
2236         $endTime = microtime(true);
2237
2238         // "Explode" both times
2239         $start = explode(' ', $GLOBALS['startTime']);
2240         $end = explode(' ', $endTime);
2241         $runTime = $end[0] - $start[0];
2242         if ($runTime < 0) $runTime = 0;
2243         $runTime = translateComma($runTime);
2244
2245         // Prepare output
2246         $content = array(
2247                 'runtime'               => $runTime,
2248                 'numSQLs'               => (getConfig('sql_count') + 1),
2249                 'numTemplates'  => (getConfig('num_templates') + 1)
2250         );
2251
2252         // Load the template
2253         LOAD_TEMPLATE('show_timings', false, $content);
2254 }
2255
2256 // Check wether a boolean constant is set
2257 // Taken from user comments in PHP documentation for function constant()
2258 function isBooleanConstantAndTrue ($constName) { // : Boolean
2259         // Failed by default
2260         $res = false;
2261
2262         // In cache?
2263         if (isset($GLOBALS['cache_array']['const'][$constName])) {
2264                 // Use cache
2265                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2266                 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2267         } else {
2268                 // Check constant
2269                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2270                 if (defined($constName)) {
2271                         // Found!
2272                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2273                         $res = (constant($constName) === true);
2274                 } // END - if
2275
2276                 // Set cache
2277                 $GLOBALS['cache_array']['const'][$constName] = $res;
2278         }
2279         //* DEBUG: */ var_dump($res);
2280
2281         // Return value
2282         return $res;
2283 }
2284
2285 // Checks if a given apache module is loaded
2286 function isApacheModuleLoaded ($apacheModule) {
2287         // Check it and return result
2288         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2289 }
2290
2291 // Get current theme name
2292 function getCurrentTheme() {
2293         // The default theme is 'default'... ;-)
2294         $ret = 'default';
2295
2296         // Load default theme if not empty from configuration
2297         if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2298
2299         if (!isSessionVariableSet('mxchange_theme')) {
2300                 // Set default theme
2301                 setSession('mxchange_theme', $ret);
2302         } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
2303                 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2304                 // Get theme from cookie
2305                 $ret = getSession('mxchange_theme');
2306
2307                 // Is it valid?
2308                 if (getThemeId($ret) == 0) {
2309                         // Fix it to default
2310                         $ret = 'default';
2311                 } // END - if
2312         } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
2313                 // Prepare FQFN for checking
2314                 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
2315
2316                 // Installation mode active
2317                 if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
2318                         // Set cookie from URL data
2319                         setSession('mxchange_theme', REQUEST_GET('theme'));
2320                 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2321                         // Set cookie from posted data
2322                         setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2323                 }
2324
2325                 // Set return value
2326                 $ret = getSession('mxchange_theme');
2327         } else {
2328                 // Invalid design, reset cookie
2329                 setSession('mxchange_theme', $ret);
2330         }
2331
2332         // Add (maybe) found theme.php file to inclusion list
2333         $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2334
2335         // Try to load the requested include file
2336         if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
2337
2338         // Return theme value
2339         return $ret;
2340 }
2341
2342 // Get id from theme
2343 function getThemeId ($name) {
2344         // Is the extension 'theme' installed?
2345         if (!EXT_IS_ACTIVE('theme')) {
2346                 // Then abort here
2347                 return 0;
2348         } // END - if
2349
2350         // Default id
2351         $id = 0;
2352
2353         // Is the cache entry there?
2354         if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2355                 // Get the version from cache
2356                 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2357
2358                 // Count up
2359                 incrementConfigEntry('cache_hits');
2360         } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
2361                 // Check if current theme is already imported or not
2362                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2363                 array($name), __FUNCTION__, __LINE__);
2364
2365                 // Entry found?
2366                 if (SQL_NUMROWS($result) == 1) {
2367                         // Fetch data
2368                         list($id) = SQL_FETCHROW($result);
2369                 } // END - if
2370
2371                 // Free result
2372                 SQL_FREERESULT($result);
2373         }
2374
2375         // Return id
2376         return $id;
2377 }
2378
2379 // Generates an error code from given account status
2380 function generateErrorCodeFromUserStatus ($status) {
2381         // Default error code if unknown account status
2382         $errorCode = getCode('UNKNOWN_STATUS');
2383
2384         // Generate constant name
2385         $constantName = sprintf("ID_%s", $status);
2386
2387         // Is the constant there?
2388         if (isCodeSet($constantName)) {
2389                 // Then get it!
2390                 $errorCode = getCode($constantName);
2391         } else {
2392                 // Unknown status
2393                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2394         }
2395
2396         // Return error code
2397         return $errorCode;
2398 }
2399
2400 // Function to search for the last modifified file
2401 function searchDirsRecursive ($dir, &$last_changed) {
2402         // Get dir as array
2403         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=".$dir."<br />\n";
2404         // Does it match what we are looking for? (We skip a lot files already!)
2405         // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
2406         $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2407         $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
2408         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2409
2410         // Walk through all entries
2411         foreach ($ds as $d) {
2412                 // Generate proper FQFN
2413                 $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
2414
2415                 // Is it a file and readable?
2416                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2417                 if (isDirectory($FQFN)) {
2418                         // $FQFN is a directory so also crawl into this directory
2419                         $newDir = $d;
2420                         if (!empty($dir)) $newDir = $dir . '/'. $d;
2421                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: ".$newDir."<br />\n";
2422                         searchDirsRecursive($newDir, $last_changed);
2423                 } elseif (isFileReadable($FQFN)) {
2424                         // $FQFN is a filename and no directory
2425                         $time = filemtime($FQFN);
2426                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: ".$d." found. (".($last_changed['time'] - $time).")<br />\n";
2427                         if ($last_changed['time'] < $time) {
2428                                 // This file is newer as the file before
2429                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2430                                 $last_changed['path_name'] = $FQFN;
2431                                 $last_changed['time'] = $time;
2432                         } // END - if
2433                 }
2434         } // END - foreach
2435 }
2436
2437 // "Getter" for revision/version data
2438 function getActualVersion ($type = 'Revision') {
2439         // By default nothing is new... ;-)
2440         $new = false;
2441
2442         if (EXT_IS_ACTIVE('cache')) {
2443                 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2444                 if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') $new = true;
2445                 if (!isset($GLOBALS['cache_array']['revision'][$type])
2446                 || count($GLOBALS['cache_array']['revision']) < 3
2447                 || !$GLOBALS['cache_instance']->loadCacheFile('revision')) $new = true;
2448
2449                 // Is the cache file outdated/invalid?
2450                 if ($new === true){
2451                         $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
2452
2453                         // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2454                         unset($GLOBALS['cache_array']['revision']);
2455
2456                         // Reload load_cach-revison.php
2457                         loadInclude('inc/loader/load_cache-revision.php');
2458                 } // END - if
2459
2460                 // Return found value
2461                 return $GLOBALS['cache_array']['revision'][$type][0];
2462
2463         } else {
2464                 // Old Version without ext-cache active (deprecated ?)
2465
2466                 // FQFN of revision file
2467                 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2468
2469                 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2470                 if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
2471                         // Has changed!
2472                         $new = true;
2473                 } else {
2474                         // Check for revision file
2475                         if (!isFileReadable($FQFN)) {
2476                                 // Not found, so we need to create it
2477                                 $new = true;
2478                         } else {
2479                                 // Revision file found
2480                                 $ins_vers = explode("\n", readFromFile($FQFN));
2481
2482                                 // Get array for mapping information
2483                                 $mapper = array_flip(getSearchFor());
2484                                 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2485
2486                                 // Is the content valid?
2487                                 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
2488                                         // File needs update!
2489                                         $new = true;
2490                                 } else {
2491                                         // Return found value
2492                                         return trim($ins_vers[$mapper[$type]]);
2493                                 }
2494                         }
2495                 }
2496
2497                 // Has it been updated?
2498                 if ($new === true)  {
2499                         writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2500                 } // END - if
2501         }
2502 }
2503
2504 // Repares an array we are looking for
2505 // 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
2506 function getSearchFor () {
2507         // Add Revision, Date, Tag and Author
2508         $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2509
2510         // Return the created array
2511         return $searchFor;
2512 }
2513
2514 // @TODO Please describe this function
2515 function getArrayFromActualVersion () {
2516         // Init variables
2517         $next_dir = ''; // Directory to start with search
2518         $last_changed = array(
2519                 'path_name' => '',
2520                 'time'      => 0
2521         );
2522         $akt_vers = array(); // Init return array
2523         $res = 0; // Init value for counting the founded keywords
2524
2525         // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2526         searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2527
2528         // Get file
2529         $last_file = readFromFile($last_changed['path_name']);
2530
2531         // Get all the keywords to search for
2532         $searchFor = getSearchFor();
2533
2534         // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2535         foreach ($searchFor as $search) {
2536                 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2537                 $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
2538                 // This trimms the search-result and puts it in the $akt_vers-return array
2539                 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2540         } // END - foreach
2541
2542         // Save the last-changed filename for debugging
2543         $akt_vers['File'] = $last_changed['path_name'];
2544
2545         // at least 3 keyword-Tags are needed for propper values
2546         if ($res && $res >= 3
2547         && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
2548         && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
2549         && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
2550                 // Prepare content witch need special treadment
2551
2552                 // Prepare timestamp for date
2553                 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2554                 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2555
2556                 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2557                 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2558                         $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2559                 } // END - if
2560
2561         } else {
2562                 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2563                 $version = sendGetRequest('check-updates3.php');
2564
2565                 // Prepare content
2566                 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2567                 if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
2568                 if (!isset($akt_vers['Date'])     || $akt_vers['Date']     == '') $akt_vers['Date']     = trim($version[9]);
2569                 if (!isset($akt_vers['Tag'])      || $akt_vers['Tag']      == '') $akt_vers['Tag']      = trim($version[8]);
2570                 if (!isset($akt_vers['Author'])   || $akt_vers['Author']   == '') $akt_vers['Author']   = "quix0r";
2571         }
2572
2573         // Return prepared array
2574         return $akt_vers;
2575 }
2576
2577 // Back-ported from the new ship-simu engine. :-)
2578 function debug_get_printable_backtrace () {
2579         // Init variable
2580         $backtrace = "<ol>\n";
2581
2582         // Get and prepare backtrace for output
2583         $backtraceArray = debug_backtrace();
2584         foreach ($backtraceArray as $key => $trace) {
2585                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2586                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2587                 if (!isset($trace['args'])) $trace['args'] = array();
2588                 $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";
2589         } // END - foreach
2590
2591         // Close it
2592         $backtrace .= "</ol>\n";
2593
2594         // Return the backtrace
2595         return $backtrace;
2596 }
2597
2598 // Output a debug backtrace to the user
2599 function debug_report_bug ($message = '') {
2600         // Init message
2601         $debug = '';
2602         // Is the optional message set?
2603         if (!empty($message)) {
2604                 // Use and log it
2605                 $debug = sprintf("Note: %s<br />\n",
2606                 $message
2607                 );
2608
2609                 // @TODO Add a little more infos here
2610                 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2611         } // END - if
2612
2613         // Add output
2614         $debug .= "Please report this bug at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>";
2615         $debug .= debug_get_printable_backtrace();
2616         $debug .= "</pre>\nRequest-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
2617         $debug .= "Thank you for finding bugs.";
2618
2619         // And abort here
2620         // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2621         die($debug);
2622 }
2623
2624 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2625 function generateSeed () {
2626         list($usec, $sec) = explode(" ", microtime());
2627         return ((float)$sec + (float)$usec);
2628 }
2629
2630 // Converts a message code to a human-readable message
2631 function convertCodeToMessage ($code) {
2632         $msg = '';
2633         switch ($code) {
2634                 case getCode('LOGOUT_DONE')      : $msg = getMessage('LOGOUT_DONE'); break;
2635                 case getCode('LOGOUT_FAILED')    : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2636                 case getCode('DATA_INVALID')     : $msg = getMessage('MAIL_DATA_INVALID'); break;
2637                 case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2638                 case getCode('ACCOUNT_LOCKED')   : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2639                 case getCode('USER_404')         : $msg = getMessage('USER_NOT_FOUND'); break;
2640                 case getCode('STATS_404')        : $msg = getMessage('MAIL_STATS_404'); break;
2641                 case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2642
2643                 case getCode('ERROR_MAILID'):
2644                         if (EXT_IS_ACTIVE($ext, true)) {
2645                                 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2646                         } else {
2647                                 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2648                         }
2649                         break;
2650
2651                 case getCode('EXTENSION_PROBLEM'):
2652                         if (REQUEST_ISSET_GET('ext')) {
2653                                 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET('ext'));
2654                         } else {
2655                                 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2656                         }
2657                         break;
2658
2659                 case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2660                 case getCode('BEG_SAME_AS_OWN')  : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2661                 case getCode('LOGIN_FAILED')     : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2662                 case getCode('MODULE_MEM_ONLY')  : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2663
2664                 default:
2665                         // Missing/invalid code
2666                         $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2667
2668                         // Log it
2669                         DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
2670                         break;
2671         } // END - switch
2672
2673         // Return the message
2674         return $msg;
2675 }
2676
2677 // Generate a "link" for the given admin id (aid)
2678 function generateAdminLink ($aid) {
2679         // No assigned admin is default
2680         $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2681
2682         // Zero? = Not assigned
2683         if (bigintval($aid) > 0) {
2684                 // Load admin's login
2685                 $login = getAdminLogin($aid);
2686
2687                 // Is the login valid?
2688                 if ($login != '***') {
2689                         // Is the extension there?
2690                         if (EXT_IS_ACTIVE('admins')) {
2691                                 // Admin found
2692                                 $admin = "<a href=\"".adminsCreateEmailLink(getAdminEmail($aid))."\">".$login."</a>";
2693                         } else {
2694                                 // Extension not found
2695                                 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2696                         }
2697                 } else {
2698                         // Maybe deleted?
2699                         $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2700                 }
2701         } // END - if
2702
2703         // Return result
2704         return $admin;
2705 }
2706
2707 // Compile characters which are allowed in URLs
2708 function compileUriCode ($code, $simple=true) {
2709         // Compile constants
2710         if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2711
2712         // Compile QUOT and other non-HTML codes
2713         $code = str_replace('{DOT}', '.',
2714         str_replace('{SLASH}', '/',
2715         str_replace('{QUOT}', "'",
2716         str_replace('{DOLLAR}', '$',
2717         str_replace('{OPEN_ANCHOR}', '(',
2718         str_replace('{CLOSE_ANCHOR}', ')',
2719         str_replace('{OPEN_SQR}', '[',
2720         str_replace('{CLOSE_SQR}', ']',
2721         str_replace('{PER}', '%',
2722         $code
2723         )))))))));
2724
2725         // Return compiled code
2726         return $code;
2727 }
2728
2729 // Function taken from user comments on www.php.net / function eregi()
2730 function isUrlValidSimple ($url) {
2731         // Prepare URL
2732         $url = strip_tags(str_replace("\\", '', compileUriCode(urldecode($url))));
2733
2734         // Allows http and https
2735         $http      = "(http|https)+(:\/\/)";
2736         // Test domain
2737         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2738         // Test double-domains (e.g. .de.vu)
2739         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2740         // Test IP number
2741         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2742         // ... directory
2743         $dir       = "((/)+([-_\.[:alnum:]])+)*";
2744         // ... page
2745         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2746         // ... and the string after and including question character
2747         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2748         // Pattern for URLs like http://url/dir/doc.html?var=value
2749         $pattern['d1dpg1']  = $http.$domain1.$dir.$page.$getstring1;
2750         $pattern['d2dpg1']  = $http.$domain2.$dir.$page.$getstring1;
2751         $pattern['ipdpg1']  = $http.$ip.$dir.$page.$getstring1;
2752         // Pattern for URLs like http://url/dir/?var=value
2753         $pattern['d1dg1']  = $http.$domain1.$dir.'/'.$getstring1;
2754         $pattern['d2dg1']  = $http.$domain2.$dir.'/'.$getstring1;
2755         $pattern['ipdg1']  = $http.$ip.$dir.'/'.$getstring1;
2756         // Pattern for URLs like http://url/dir/page.ext
2757         $pattern['d1dp']  = $http.$domain1.$dir.$page;
2758         $pattern['d1dp']  = $http.$domain2.$dir.$page;
2759         $pattern['ipdp']  = $http.$ip.$dir.$page;
2760         // Pattern for URLs like http://url/dir
2761         $pattern['d1d']  = $http.$domain1.$dir;
2762         $pattern['d2d']  = $http.$domain2.$dir;
2763         $pattern['ipd']  = $http.$ip.$dir;
2764         // Pattern for URLs like http://url/?var=value
2765         $pattern['d1g1']  = $http.$domain1.'/'.$getstring1;
2766         $pattern['d2g1']  = $http.$domain2.'/'.$getstring1;
2767         $pattern['ipg1']  = $http.$ip.'/'.$getstring1;
2768         // Pattern for URLs like http://url?var=value
2769         $pattern['d1g12']  = $http.$domain1.$getstring1;
2770         $pattern['d2g12']  = $http.$domain2.$getstring1;
2771         $pattern['ipg12']  = $http.$ip.$getstring1;
2772         // Test all patterns
2773         $reg = false;
2774         foreach ($pattern as $key=>$pat) {
2775                 // Debug regex?
2776                 if (defined('DEBUG_REGEX')) {
2777                         $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2778                         $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2779                         $pat = str_replace("[:digit:]", "0-9", $pat);
2780                         $pat = str_replace('.', "\.", $pat);
2781                         $pat = str_replace("@", "\@", $pat);
2782                         echo $key."=&nbsp;".$pat."<br />";
2783                 }
2784
2785                 // Check if expression matches
2786                 $reg = ($reg || preg_match(("^".$pat."^"), $url));
2787
2788                 // Does it match?
2789                 if ($reg === true) break;
2790         }
2791
2792         // Return true/false
2793         return $reg;
2794 }
2795
2796 // Wtites data to a config.php-style file
2797 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2798 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2799         // Initialize some variables
2800         $done = false;
2801         $seek++;
2802         $next  = -1;
2803         $found = false;
2804
2805         // Is the file there and read-/write-able?
2806         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2807                 $search = 'CFG: ' . $comment;
2808                 $tmp = $FQFN . '.tmp';
2809
2810                 // Open the source file
2811                 $fp = fopen($FQFN, 'r') or OUTPUT_HTML('<strong>READ:</strong> ' . $FQFN . "<br />\n");
2812
2813                 // Is the resource valid?
2814                 if (is_resource($fp)) {
2815                         // Open temporary file
2816                         $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('<strong>WRITE:</strong> ' . $tmp . "<br />\n");
2817
2818                         // Is the resource again valid?
2819                         if (is_resource($fp_tmp)) {
2820                                 while (!feof($fp)) {
2821                                         // Read from source file
2822                                         $line = fgets ($fp, 1024);
2823
2824                                         if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2825
2826                                         if ($next > -1) {
2827                                                 if ($next === $seek) {
2828                                                         $next = -1;
2829                                                         $line = $prefix . $DATA . $suffix . "\n";
2830                                                 } else {
2831                                                         $next++;
2832                                                 }
2833                                         }
2834
2835                                         // Write to temp file
2836                                         fputs($fp_tmp, $line);
2837                                 } // END - while
2838
2839                                 // Close temp file
2840                                 fclose($fp_tmp);
2841
2842                                 // Finished writing tmp file
2843                                 $done = true;
2844                         } // END - if
2845
2846                         // Close source file
2847                         fclose($fp);
2848
2849                         if (($done === true) && ($found === true)) {
2850                                 // Copy back tmp file and delete tmp :-)
2851                                 copyFileVerified($tmp, $FQFN, 0644);
2852                                 return removeFile($tmp);
2853                         } elseif ($found === false) {
2854                                 OUTPUT_HTML('<strong>CHANGE:</strong> 404!');
2855                         } else {
2856                                 OUTPUT_HTML('<strong>TMP:</strong> UNDONE!');
2857                         }
2858                 }
2859         } else {
2860                 // File not found, not readable or writeable
2861                 OUTPUT_HTML('<strong>404:</strong> ' . $FQFN . '<br />');
2862         }
2863
2864         // An error was detected!
2865         return false;
2866 }
2867 // Send notification to admin
2868 function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
2869         if (GET_EXT_VERSION('admins') >= '0.4.1') {
2870                 // Send new way
2871                 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2872         } else {
2873                 // Send out out-dated way
2874                 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2875                 SEND_ADMIN_EMAILS($subject, $msg);
2876         }
2877 }
2878
2879 // Debug message logger
2880 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
2881         // Is debug mode enabled?
2882         if ((isDebugModeEnabled()) || ($force === true)) {
2883                 // Remove CRLF
2884                 $message = str_replace("\r", '', str_replace("\n", '', $message));
2885
2886                 // Log this message away
2887                 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
2888                 fwrite($fp, date("d.m.Y|H:i:s", time())."|".$GLOBALS['module']."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
2889                 fclose($fp);
2890         } // END - if
2891 }
2892
2893 // Load more reset scripts
2894 function runResetIncludes () {
2895         // Is the reset set or old sql_patches?
2896         if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
2897                 // Then abort here
2898                 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
2899         } // END - if
2900
2901         // Get more daily reset scripts
2902         SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
2903
2904         // Update database
2905         if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
2906
2907         // Is the config entry set?
2908         if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
2909                 // Create current week mark
2910                 $currWeek = date('W', time());
2911
2912                 // Has it changed?
2913                 if (getConfig('last_week') != $currWeek) {
2914                         // Include weekly reset scripts
2915                         MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
2916
2917                         // Update config
2918                         if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
2919                 } // END - if
2920
2921                 // Create current month mark
2922                 $currMonth = date('m', time());
2923
2924                 // Has it changed?
2925                 if (getConfig('last_month') != $currMonth) {
2926                         // Include monthly reset scripts
2927                         MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
2928
2929                         // Update config
2930                         if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
2931                 } // END - if
2932         } // END - if
2933
2934         // Run the filter
2935         runFilterChain('load_includes');
2936 }
2937
2938 // Handle extra values
2939 function handleExtraValues ($filterFunction, $value, $extraValue) {
2940         // Default is the value itself
2941         $ret = $value;
2942
2943         // Do we have a special filter function?
2944         if (!empty($filterFunction)) {
2945                 // Does the filter function exist?
2946                 if (function_exists($filterFunction)) {
2947                         // Do we have extra parameters here?
2948                         if (!empty($extraValue)) {
2949                                 // Put both parameters in one new array by default
2950                                 $args = array($value, $extraValue);
2951
2952                                 // If we have an array simply use it and pre-extend it with our value
2953                                 if (is_array($extraValue)) {
2954                                         // Make the new args array
2955                                         $args = merge_array(array($value), $extraValue);
2956                                 } // END - if
2957
2958                                 // Call the multi-parameter call-back
2959                                 $ret = call_user_func_array($filterFunction, $args);
2960                         } else {
2961                                 // One parameter call
2962                                 $ret = call_user_func($filterFunction, $value);
2963                         }
2964                 } // END - if
2965         } // END - if
2966
2967         // Return the value
2968         return $ret;
2969 }
2970
2971 // Converts timestamp selections into a timestamp
2972 function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
2973         // Init test variable
2974         $test2 = '';
2975
2976         // Get last three chars
2977         $test = substr($id, -3);
2978
2979         // Improved way of checking! :-)
2980         if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2981                 // Found a multi-selection for timings?
2982                 $test = substr($id, 0, -3);
2983                 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)) {
2984                         // Generate timestamp
2985                         $POST[$test] = createTimestampFromSelections($test, $POST);
2986                         $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2987
2988                         // Remove data from array
2989                         foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2990                                 unset($POST[$test.'_'.$rem]);
2991                         } // END - foreach
2992
2993                         // Skip adding
2994                         unset($id); $skip = true; $test2 = $test;
2995                 } // END - if
2996         } else {
2997                 // Process this entry
2998                 $skip = false;
2999                 $test2 = '';
3000         }
3001 }
3002
3003 // Reverts the german decimal comma into Computer decimal dot
3004 function convertCommaToDot ($str) {
3005         // Default float is not a float... ;-)
3006         $float = false;
3007
3008         // Which language is selected?
3009         switch (getLanguage()) {
3010                 case 'de': // German language
3011                         // Remove german thousand dots first
3012                         $str = str_replace('.', '', $str);
3013
3014                         // Replace german commata with decimal dot and cast it
3015                         $float = (float)str_replace(',', '.', $str);
3016                         break;
3017
3018                 default: // US and so on
3019                         // Remove thousand dots first and cast
3020                         $float = (float)str_replace(',', '', $str);
3021                         break;
3022         }
3023
3024         // Return float
3025         return $float;
3026 }
3027
3028 // Handle menu-depending failed logins and return the rendered content
3029 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3030         // Default output is empty ;-)
3031         $OUT = '';
3032
3033         // Is the session data set?
3034         if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3035                 // Ignore zero values
3036                 if (getSession('mxchange_'.$accessLevel.'_failures') > 0) {
3037                         // Non-guest has login failures found, get both data and prepare it for template
3038                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3039                         $content = array(
3040                                 'login_failures' => getSession('mxchange_'.$accessLevel.'_failures'),
3041                                 'last_failure'   => generateDateTime(getSession('mxchange_'.$accessLevel.'_last_fail'), '2')
3042                         );
3043
3044                         // Load template
3045                         $OUT = LOAD_TEMPLATE('login_failures', true, $content);
3046                 } // END - if
3047
3048                 // Reset session data
3049                 setSession('mxchange_'.$accessLevel.'_failures', '');
3050                 setSession('mxchange_'.$accessLevel.'_last_fail', '');
3051         } // END - if
3052
3053         // Return rendered content
3054         return $OUT;
3055 }
3056
3057 // Rebuild cache
3058 function rebuildCacheFiles ($cache, $inc = '') {
3059         // Shall I remove the cache file?
3060         if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
3061                 // Rebuild cache
3062                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3063                         // Destroy it
3064                         $GLOBALS['cache_instance']->destroyCacheFile();
3065                 } // END - if
3066
3067                 // Include file given?
3068                 if (!empty($inc)) {
3069                         // Construct FQFN
3070                         $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3071
3072                         // Is the include there?
3073                         if (isIncludeReadable($INC)) {
3074                                 // And rebuild it from scratch
3075                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3076                                 loadInclude($INC);
3077                         } else {
3078                                 // Include not found!
3079                                 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3080                         }
3081                 } // END - if
3082         } // END - if
3083 }
3084
3085 // Purge admin menu cache
3086 function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
3087         // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3088         if (!EXT_IS_ACTIVE('cache')) {
3089                 // Cache extension not active
3090                 return false;
3091         } elseif (!isCacheInstanceValid()) {
3092                 // No cache instance!
3093                 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3094                 return false;
3095         } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
3096                 // Caching disabled (currently experiemental!)
3097                 return false;
3098         }
3099
3100         // Experiemental feature!
3101         debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3102 }
3103
3104 // Determines the real remote address
3105 function determineRealRemoteAddress () {
3106         // Is a proxy in use?
3107         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
3108                 // Proxy was used
3109                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3110         } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
3111                 // Yet, another proxy
3112                 $address = $_SERVER['HTTP_CLIENT_IP'];
3113         } else {
3114                 // The regular address when no proxy was used
3115                 $address = $_SERVER['REMOTE_ADDR'];
3116         }
3117
3118         // This strips out the real address from proxy output
3119         if (strstr($address, ',')){
3120                 $addressArray = explode(',', $address);
3121                 $address = $addressArray[0];
3122         } // END - if
3123
3124         // Return the result
3125         return $address;
3126 }
3127
3128 // Adds a bonus mail to the queue
3129 // This is a high-level function!
3130 function addNewBonusMail ($data, $mode = '', $output=true) {
3131         // Use mode from data if not set and availble ;-)
3132         if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3133
3134         // Generate receiver list
3135         $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3136
3137         // Receivers added?
3138         if (!empty($RECEIVER)) {
3139                 // Add bonus mail to queue
3140                 addBonusMailToQueue(
3141                 $data['subject'],
3142                 $data['text'],
3143                 $RECEIVER,
3144                 $data['points'],
3145                 $data['seconds'],
3146                 $data['url'],
3147                 $data['cat'],
3148                 $mode,
3149                 $data['receiver']
3150                 );
3151
3152                 // Mail inserted into bonus pool
3153                 if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3154         } elseif ($output) {
3155                 // More entered than can be reached!
3156                 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3157         } else {
3158                 // Debug log
3159                 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3160         }
3161 }
3162
3163 // Determines referal id and sets it
3164 function DETERMINE_REFID () {
3165         // Check if refid is set
3166         if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3167                 // The variable user comes from the click-counter script click.php and we only accept this here
3168                 $GLOBALS['refid'] = bigintval($_GET['user']);
3169         } elseif (!empty($_POST['refid'])) {
3170                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3171                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3172         } elseif (!empty($_GET['refid'])) {
3173                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3174                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3175         } elseif (!empty($_GET['ref'])) {
3176                 // Set refid=ref (the referal link uses such variable)
3177                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3178         } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3179                 // Set session refid als global
3180                 $GLOBALS['refid'] = bigintval(getSession('refid'));
3181         } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
3182                 // Set default refid as refid in URL
3183                 $GLOBALS['refid'] = getConfig(('def_refid'));
3184         } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
3185                 // Select a random user which has confirmed enougth mails
3186                 $GLOBALS['refid'] = determineRandomReferalId();
3187         } else {
3188                 // No default ID when sql_patches is not installed or none set
3189                 $GLOBALS['refid'] = 0;
3190         }
3191
3192         // Set cookie when default refid > 0
3193         if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3194                 // Set cookie
3195                 setSession('refid', $GLOBALS['refid']);
3196         } // END - if
3197
3198         // Return determined refid
3199         return $GLOBALS['refid'];
3200 }
3201
3202 // Enables the reset mode. Only call this function if you really want the
3203 // reset to be run!
3204 function enableResetMode () {
3205         // Enable the reset mode
3206         $GLOBALS['reset_enabled'] = true;
3207
3208         // Run filters
3209         runFilterChain('reset_enabled');
3210 }
3211
3212 // Our shutdown-function
3213 function shutdown () {
3214         // Call the filter chain 'shutdown'
3215         runFilterChain('shutdown', null, false);
3216
3217         if (SQL_IS_LINK_UP()) {
3218                 // Close link
3219                 SQL_CLOSE(__FILE__, __LINE__);
3220         } elseif ((!isInstalling()) && (isInstalled())) {
3221                 // No database link
3222                 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3223         }
3224
3225         // Stop executing here
3226         exit;
3227 }
3228
3229 // Setter for userid
3230 function setUserId ($userid) {
3231         $GLOBALS['userid'] = bigintval($userid);
3232 }
3233
3234 // Getter for userid or returns zero
3235 function getUserId () {
3236         // Default userid
3237         $userid = 0;
3238
3239         // Is the userid set?
3240         if (isUserIdSet()) {
3241                 // Then use it
3242                 $userid = $GLOBALS['userid'];
3243         } // END - if
3244
3245         // Return it
3246         return $userid;
3247 }
3248
3249 // Checks ether the userid is set
3250 function isUserIdSet () {
3251         return (isset($GLOBALS['userid']));
3252 }
3253
3254 // Handle message codes from URL
3255 function handleCodeMessage () {
3256         if (REQUEST_ISSET_GET('msg')) {
3257                 // Default extension is "unknown"
3258                 $ext = 'unknown';
3259
3260                 // Is extension given?
3261                 if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
3262
3263                 // Convert the 'msg' parameter from URL to a human-readable message
3264                 $msg = convertCodeToMessage(REQUEST_GET('msg'));
3265
3266                 // Load message template
3267                 LOAD_TEMPLATE('message', false, $msg);
3268         } // END - if
3269 }
3270
3271 // Setter for extra title
3272 function setExtraTitle ($extraTitle) {
3273         $GLOBALS['extra_title'] = $extraTitle;
3274 }
3275
3276 // Getter for extra title
3277 function getExtraTitle () {
3278         // Is the extra title set?
3279         if (!isExtraTitleSet()) {
3280                 // No, then abort here
3281                 debug_report_bug('extra_title is not set!');
3282         } // END - if
3283
3284         // Return it
3285         return $GLOBALS['extra_title'];
3286 }
3287
3288 // Checks if the extra title is set
3289 function isExtraTitleSet () {
3290         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3291 }
3292
3293 //////////////////////////////////////////////////
3294 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3295 //////////////////////////////////////////////////
3296 //
3297 if (!function_exists('html_entity_decode')) {
3298         // Taken from documentation on www.php.net
3299         function html_entity_decode ($string) {
3300                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3301                 $trans_tbl = array_flip($trans_tbl);
3302                 return strtr($string, $trans_tbl);
3303         }
3304 } // END - if
3305
3306 // [EOF]
3307 ?>