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