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