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