aeb0ac419f36d907c3eeaeaf1fb390ea38faa3b8
[mailer.git] / inc / functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/25/2003 *
4  * ===================                          Last change: 11/29/2005 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : functions.php                                    *
8  * -------------------------------------------------------------------- *
9  * Short description : Many non-database functions (also file access)   *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Viele Nicht-Datenbank-Funktionen                 *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://www.mxchange.org                  *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Sends out all headers required for HTTP/1.1 reply
44 function sendHttpHeaders () {
45         // Used later
46         $now = gmdate('D, d M Y H:i:s') . ' GMT';
47
48         // Send HTTP header
49         sendHeader('HTTP/1.1 ' . getHttpStatus());
50
51         // General headers for no caching
52         sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
53         sendHeader('Last-Modified: ' . $now);
54         sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
55         sendHeader('Pragma: no-cache'); // HTTP/1.0
56         sendHeader('Connection: Close');
57         sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
58         sendHeader('Content-Language: ' . getLanguage());
59 }
60
61 // Init fatal message array
62 function initFatalMessages () {
63         $GLOBALS['fatal_messages'] = array();
64 }
65
66 // Getter for whole fatal error messages
67 function getFatalArray () {
68         return $GLOBALS['fatal_messages'];
69 }
70
71 // Add a fatal error message to the queue array
72 function addFatalMessage ($F, $L, $message, $extra = '') {
73         if (is_array($extra)) {
74                 // Multiple extras for a message with masks
75                 $message = call_user_func_array('sprintf', $extra);
76         } elseif (!empty($extra)) {
77                 // $message is text with a mask plus extras to insert into the text
78                 $message = sprintf($message, $extra);
79         }
80
81         // Add message to $GLOBALS['fatal_messages']
82         $GLOBALS['fatal_messages'][] = $message;
83
84         // Log fatal messages away
85         logDebugMessage($F, $L, 'Fatal error message: ' . $message);
86 }
87
88 // Getter for total fatal message count
89 function getTotalFatalErrors () {
90         // Init count
91         $count = '0';
92
93         // Do we have at least the first entry?
94         if (!empty($GLOBALS['fatal_messages'][0])) {
95                 // Get total count
96                 $count = count($GLOBALS['fatal_messages']);
97         } // END - if
98
99         // Return value
100         return $count;
101 }
102
103 // Send mail out to an email address
104 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
105         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'toEmail=' . $toEmail . ',subject=' . $subject . ',isHtml=' . $isHtml);
106
107         // Set from header
108         if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
109                 // Value detected, is the message extension installed?
110                 // @TODO Extension 'msg' does not exist
111                 if (isExtensionActive('msg')) {
112                         ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
113                         return;
114                 } else {
115                         // Does the user exist?
116                         if (fetchUserData($toEmail)) {
117                                 // Get the email
118                                 $toEmail = getUserData('email');
119                         } else {
120                                 // Set webmaster
121                                 $toEmail = getWebmaster();
122                         }
123                 }
124         } elseif ($toEmail == '0') {
125                 // Is the webmaster!
126                 $toEmail = getWebmaster();
127         }
128         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
129
130         // Check for PHPMailer or debug-mode
131         if ((!checkPhpMailerUsage()) || (isDebugModeEnabled())) {
132                 // Prefix is '' for text mails
133                 $prefix = '';
134
135                 // Is HTML?
136                 if ($isHtml == 'Y') {
137                         // Set prefix
138                         $prefix = 'html_';
139                 } // END - if
140
141                 // Not in PHPMailer-Mode
142                 if (empty($mailHeader)) {
143                         // Load email header template
144                         $mailHeader = loadEmailTemplate($prefix . 'header');
145                 } else {
146                         // Append header
147                         $mailHeader .= loadEmailTemplate($prefix . 'header');
148                 }
149         } // END - if
150
151         // Fix HTML parameter (default is no!)
152         if (empty($isHtml)) {
153                 $isHtml = 'N';
154         } // END - if
155
156         // Debug mode enabled?
157         if (isDebugModeEnabled()) {
158                 // In debug mode we want to display the mail instead of sending it away so we can debug this part
159                 outputHtml('<pre>
160 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
161 To      : ' . htmlentities(utf8_decode($toEmail)) . '
162 Subject : ' . htmlentities(utf8_decode($subject)) . '
163 Message : ' . htmlentities(utf8_decode($message)) . '
164 </pre>');
165
166                 // This is always fine
167                 return true;
168         } elseif (!empty($toEmail)) {
169                 // Send Mail away
170                 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
171         } elseif ($isHtml != 'Y') {
172                 // Problem detected while sending a mail, forward it to admin
173                 return sendRawEmail(getWebmaster(), '[PROBLEM:]' . $subject, $message, $mailHeader);
174         }
175
176         // Why did we end up here? This should not happen
177         debug_report_bug(__FUNCTION__, __LINE__, 'Ending up: template=' . $template);
178 }
179
180 // Check to use wether legacy mail() command or PHPMailer class
181 // @TODO Rewrite this to an extension 'smtp'
182 // @private
183 function checkPhpMailerUsage() {
184         return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
185 }
186
187 // Send out a raw email with PHPMailer class or legacy mail() command
188 function sendRawEmail ($toEmail, $subject, $message, $headers) {
189         // Just compile all to put out all configs, etc.
190         $eval  = '$toEmail = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($toEmail), false)) . '"); ';
191         $eval .= '$subject = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($subject), false)) . '"); ';
192         $eval .= '$headers = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($headers), false)) . '"); ';
193
194         // Do not decode entities in the message because we also send HTML mails through this function
195         $eval .= '$message = "' . escapeQuotes(doFinalCompilation(compileRawCode($message), false)) . '";';
196
197         // Run the final eval() command
198         eval($eval);
199
200         // Shall we use PHPMailer class or legacy mode?
201         if (checkPhpMailerUsage()) {
202                 // Use PHPMailer class with SMTP enabled
203                 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
204                 loadIncludeOnce('inc/phpmailer/class.smtp.php');
205
206                 // get new instance
207                 $mail = new PHPMailer();
208
209                 // Set charset to UTF-8
210                 $mail->CharSet = 'UTF-8';
211
212                 // Path for PHPMailer
213                 $mail->PluginDir  = sprintf("%sinc/phpmailer/", getPath());
214
215                 $mail->IsSMTP();
216                 $mail->SMTPAuth   = true;
217                 $mail->Host       = getConfig('SMTP_HOSTNAME');
218                 $mail->Port       = 25;
219                 $mail->Username   = getConfig('SMTP_USER');
220                 $mail->Password   = getConfig('SMTP_PASSWORD');
221                 if (empty($headers)) {
222                         $mail->From = getWebmaster();
223                 } else {
224                         $mail->From = $headers;
225                 }
226                 $mail->FromName   = getMainTitle();
227                 $mail->Subject    = $subject;
228                 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
229                         $mail->Body       = $message;
230                         $mail->AltBody    = 'Your mail program required HTML support to read this mail!';
231                         $mail->WordWrap   = 70;
232                         $mail->IsHTML(true);
233                 } else {
234                         $mail->Body       = decodeEntities($message);
235                 }
236
237                 $mail->AddAddress($toEmail, '');
238                 $mail->AddReplyTo(getWebmaster(), getMainTitle());
239                 $mail->AddCustomHeader('Errors-To:' . getWebmaster());
240                 $mail->AddCustomHeader('X-Loop:' . getWebmaster());
241                 $mail->AddCustomHeader('Bounces-To:' . getWebmaster());
242                 $mail->Send();
243
244                 // Has an error occured?
245                 if (!empty($mail->ErrorInfo)) {
246                         // Log message
247                         logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
248
249                         // Raise an error
250                         return false;
251                 } else {
252                         // All fine!
253                         return true;
254                 }
255         } else {
256                 // Use legacy mail() command
257                 return mail($toEmail, $subject, decodeEntities($message), $headers);
258         }
259 }
260
261 // Generate a password in a specified length or use default password length
262 function generatePassword ($length = '0') {
263         // Auto-fix invalid length of zero
264         if ($length == '0') $length = getPassLen();
265
266         // Initialize array with all allowed chars
267         $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,-,+,_,/,.');
268
269         // Start creating password
270         $PASS = '';
271         for ($i = '0'; $i < $length; $i++) {
272                 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
273         } // END - for
274
275         // When the size is below 40 we can also add additional security by scrambling
276         // it. Otherwise we may corrupt hashes
277         if (strlen($PASS) <= 40) {
278                 // Also scramble the password
279                 $PASS = scrambleString($PASS);
280         } // END - if
281
282         // Return the password
283         return $PASS;
284 }
285
286 // Generates a human-readable timestamp from the Uni* stamp
287 function generateDateTime ($time, $mode = '0') {
288         // If the stamp is zero it mostly didn't "happen"
289         if ($time == '0') {
290                 // Never happend
291                 return '{--NEVER_HAPPENED--}';
292         } // END - if
293
294         // Filter out numbers
295         $time = bigintval($time);
296
297         // Is it cached?
298         if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
299                 // Then use it
300                 return $GLOBALS[__FUNCTION__][$time][$mode];
301         } // END - if
302
303         // Detect language
304         switch (getLanguage()) {
305                 case 'de': // German date / time format
306                         switch ($mode) {
307                                 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
308                                 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
309                                 case '2': $ret = date('d.m.Y|H:i', $time); break;
310                                 case '3': $ret = date('d.m.Y', $time); break;
311                                 case '4': $ret = date('d.m.Y|H:i:s', $time); break;
312                                 case '5': $ret = date('d-m-Y (l-F-T)', $time); break;
313                                 case '6': $ret = date('Ymd', $time); break;
314                                 default:
315                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
316                                         break;
317                         }
318                         break;
319
320                 default: // Default is the US date / time format!
321                         switch ($mode) {
322                                 case '0': $ret = date('r', $time); break;
323                                 case '1': $ret = strtolower(date('Y-m-d - g:i A', $time)); break;
324                                 case '2': $ret = date('y-m-d|H:i', $time); break;
325                                 case '3': $ret = date('y-m-d', $time); break;
326                                 case '4': $ret = date('d.m.Y|H:i:s', $time); break;
327                                 case '5': $ret = date('d-m-Y (l-F-T)', $time); break;
328                                 case '6': $ret = date('Ymd', $time); break;
329                                 default:
330                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
331                                         break;
332                         } // END - switch
333         } // END - switch
334
335         // Store it in cache
336         $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
337
338         // Return result
339         return $ret;
340 }
341
342 // Translates Y/N to yes/no
343 function translateYesNo ($yn) {
344         // Is it cached?
345         if (!isset($GLOBALS[__FUNCTION__][$yn])) {
346                 // Default
347                 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
348                 switch ($yn) {
349                         case 'Y': $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; break;
350                         case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break;
351                         default:
352                                 // Log unknown value
353                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
354                                 break;
355                 } // END - switch
356         } // END - if
357
358         // Return it
359         return $GLOBALS[__FUNCTION__][$yn];
360 }
361
362 // Translates the american decimal dot into a german comma
363 function translateComma ($dotted, $cut = true, $max = '0') {
364         // First, cast all to double, due to PHP changes
365         $dotted = (double) $dotted;
366
367         // Default is 3 you can change this in admin area "Misc -> Misc Options"
368         if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
369
370         // Use from config is default
371         $maxComma = getConfig('max_comma');
372
373         // Use from parameter?
374         if ($max > 0) $maxComma = $max;
375
376         // Cut zeros off?
377         if (($cut === true) && ($max == '0')) {
378                 // Test for commata if in cut-mode
379                 $com = explode('.', $dotted);
380                 if (count($com) < 2) {
381                         // Don't display commatas even if there are none... ;-)
382                         $maxComma = '0';
383                 } // END - if
384         } // END - if
385
386         // Debug log
387
388         // Translate it now
389         $translated = $dotted;
390         switch (getLanguage()) {
391                 case 'de': // German language
392                         $translated = number_format($dotted, $maxComma, ',', '.');
393                         break;
394
395                 default: // All others
396                         $translated = number_format($dotted, $maxComma, '.', ',');
397                         break;
398         } // END - switch
399
400         // Return translated value
401         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
402         return $translated;
403 }
404
405 // Translate Uni*-like gender to human-readable
406 function translateGender ($gender) {
407         // Default
408         $ret = '!' . $gender . '!';
409
410         // Male/female or company?
411         switch ($gender) {
412                 case 'M': // Male
413                 case 'F': // Female
414                 case 'C': // Company
415                         $ret = sprintf("{--GENDER_%s--}", $gender);
416                         break;
417
418                 default:
419                         // Please report bugs on unknown genders
420                         debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
421                         break;
422         } // END - switch
423
424         // Return translated gender
425         return $ret;
426 }
427
428 // "Translates" the user status
429 function translateUserStatus ($status) {
430         // Default status is unknown if something goes through
431         $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
432
433         // Generate message depending on status
434         switch ($status) {
435                 case 'UNCONFIRMED':
436                 case 'CONFIRMED':
437                 case 'LOCKED':
438                         $ret = sprintf("{--ACCOUNT_STATUS_%s--}", $status);
439                         break;
440
441                 case '':
442                 case null:
443                         $ret = '{--ACCOUNT_STATUS_DELETED--}';
444                         break;
445
446                 default:
447                         // Please report all unknown status
448                         debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
449                         break;
450         } // END - switch
451
452         // Return it
453         return $ret;
454 }
455
456 // "Translates" 'visible' and 'locked' to a CSS class
457 function translateMenuVisibleLocked ($content, $prefix = '') {
458         // Default is 'menu_unknown'
459         $content['visible_css'] = $prefix . 'menu_unknown';
460
461         // Translate 'visible' and keep an eye on the prefix
462         switch ($content['visible']) {
463                 // Should be visible
464                 case 'Y': $content['visible_css'] = $prefix . 'menu_visible'  ; break;
465                 case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break;
466                 default:
467                         // Please report this
468                         debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, true) . '</pre>');
469                         break;
470         } // END - switch
471
472         // Translate 'locked' and keep an eye on the prefix
473         switch ($content['locked']) {
474                 // Should be locked
475                 case 'Y': $content['locked_css'] = $prefix . 'menu_locked'  ; break;
476                 case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break;
477                 default:
478                         // Please report this
479                         debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, true) . '</pre>');
480                         break;
481         } // END - switch
482
483         // Return the resulting array
484         return $content;
485 }
486
487 // Generates an URL for the dereferer
488 function generateDerefererUrl ($URL) {
489         // Don't de-refer our own links!
490         if (substr($URL, 0, strlen(getUrl())) != getUrl()) {
491                 // De-refer this link
492                 $URL = '{%url=modules.php?module=loader&amp;url=' . encodeString(compileUriCode($URL)) . '%}';
493         } // END - if
494
495         // Return link
496         return $URL;
497 }
498
499 // Generates an URL for the frametester
500 function generateFrametesterUrl ($URL) {
501         // Prepare frametester URL
502         $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&amp;url=%s%%}",
503                 encodeString(compileUriCode($URL))
504         );
505
506         // Return the new URL
507         return $frametesterUrl;
508 }
509
510 // Count entries from e.g. a selection box
511 function countSelection ($array) {
512         // Integrity check
513         if (!is_array($array)) {
514                 // Not an array!
515                 debug_report_bug(__FUNCTION__, __LINE__, 'No array provided.');
516         } // END - if
517
518         // Init count
519         $ret = '0';
520
521         // Count all entries
522         foreach ($array as $key => $selected) {
523                 // Is it checked?
524                 if (!empty($selected)) $ret++;
525         } // END - foreach
526
527         // Return counted selections
528         return $ret;
529 }
530
531 // Generates a timestamp (some wrapper for mktime())
532 function makeTime ($hours, $minutes, $seconds, $stamp) {
533         // Extract day, month and year from given timestamp
534         $days   = getDay($stamp);
535         $months = getMonth($stamp);
536         $years  = getYear($stamp);
537
538         // Create timestamp for wished time which depends on extracted date
539         return mktime(
540                 $hours,
541                 $minutes,
542                 $seconds,
543                 $months,
544                 $days,
545                 $years
546         );
547 }
548
549 // Redirects to an URL and if neccessarry extends it with own base URL
550 function redirectToUrl ($URL, $allowSpider = true) {
551         // Remove {%url=
552         if (substr($URL, 0, 6) == '{%url=') $URL = substr($URL, 6, -2);
553
554         // Compile out codes
555         eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
556
557         // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
558         $rel = ' rel="external"';
559
560         // Do we have internal or external URL?
561         if (substr($URL, 0, strlen(getUrl())) == getUrl()) {
562                 // Own (=internal) URL
563                 $rel = '';
564         } // END - if
565
566         // Three different ways to debug...
567         //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'URL=' . $URL);
568         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
569         //* DEBUG: */ die($URL);
570
571         // Simple probe for bots/spiders from search engines
572         if ((isSpider()) && ($allowSpider === true)) {
573                 // Set HTTP-Status
574                 setHttpStatus('200 OK');
575
576                 // Set content-type here to fix a missing array element
577                 setContentType('text/html');
578
579                 // Output new location link as anchor
580                 outputHtml('<a href="' . $URL . '"' . $rel . '>' . secureString($URL) . '</a>');
581         } elseif (!headers_sent()) {
582                 // Clear output buffer
583                 clearOutputBuffer();
584
585                 // Clear own output buffer
586                 $GLOBALS['output'] = '';
587
588                 // Load URL when headers are not sent
589                 sendRawRedirect(doFinalCompilation(str_replace('&amp;', '&', $URL), false));
590         } else {
591                 // Output error message
592                 loadInclude('inc/header.php');
593                 loadTemplate('redirect_url', false, str_replace('&amp;', '&', $URL));
594                 loadInclude('inc/footer.php');
595         }
596
597         // Shut the mailer down here
598         shutdown();
599 }
600
601 /************************************************************************
602  *                                                                      *
603  * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!)       *
604  * $a_sort sortiert:                                                    *
605  *                                                                      *
606  * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
607  * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben    *
608  * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird   *
609  * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a             *
610  * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren   *
611  *                                                                      *
612  * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array    *
613  * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
614  * Sie, dass es doch nicht so schwer ist! :-)                           *
615  *                                                                      *
616  ************************************************************************/
617 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
618         $dummy = $array;
619         while ($primary_key < count($a_sort)) {
620                 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
621                         foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
622                                 $match = false;
623                                 if ($nums === false) {
624                                         // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
625                                         if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
626                                 } elseif ($key != $key2) {
627                                         // Sort numbers (E.g.: 9 < 10)
628                                         if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
629                                         if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1))  $match = true;
630                                 }
631
632                                 if ($match) {
633                                         // We have found two different values, so let's sort whole array
634                                         foreach ($dummy as $sort_key => $sort_val) {
635                                                 $t                       = $dummy[$sort_key][$key];
636                                                 $dummy[$sort_key][$key]  = $dummy[$sort_key][$key2];
637                                                 $dummy[$sort_key][$key2] = $t;
638                                                 unset($t);
639                                         } // END - foreach
640                                 } // END - if
641                         } // END - foreach
642                 } // END - foreach
643
644                 // Count one up
645                 $primary_key++;
646         } // END - while
647
648         // Write back sorted array
649         $array = $dummy;
650 }
651
652
653 //
654 // Deprecated : $length (still has one reference in this function)
655 // Optional   : $DATA
656 //
657 function generateRandomCode ($length, $code, $userid, $DATA = '') {
658         // Build server string
659         $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
660
661         // Build key string
662         $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY');
663         if (isConfigEntrySet('secret_key')) {
664                 $keys .= getEncryptSeperator().getSecretKey();
665         } // END - if
666         if (isConfigEntrySet('file_hash')) {
667                 $keys .= getEncryptSeperator().getFileHash();
668         } // END - if
669         $keys .= getEncryptSeperator() . getDateFromPatchTime();
670         if (isConfigEntrySet('master_salt')) {
671                 $keys .= getEncryptSeperator().getMasterSalt();
672         } // END - if
673
674         // Build string from misc data
675         $data   = $code . getEncryptSeperator() . $userid . getEncryptSeperator() . $DATA;
676
677         // Add more additional data
678         if (isSessionVariableSet('u_hash')) {
679                 $data .= getEncryptSeperator() . getSession('u_hash');
680         } // END - if
681
682         // Add referal id, language, theme and userid
683         $data .= getEncryptSeperator() . determineReferalId();
684         $data .= getEncryptSeperator() . getLanguage();
685         $data .= getEncryptSeperator() . getCurrentTheme();
686         $data .= getEncryptSeperator() . getMemberId();
687
688         // Calculate number for generating the code
689         $a = $code + getConfig('_ADD') - 1;
690
691         if (isConfigEntrySet('master_salt')) {
692                 // Generate hash with master salt from modula of number with the prime number and other data
693                 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, getMasterSalt());
694
695                 // Create number from hash
696                 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
697         } else {
698                 // Generate hash with "hash of site key" from modula of number with the prime number and other data
699                 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, substr(sha1(getConfig('SITE_KEY')), 0, getSaltLength()));
700
701                 // Create number from hash
702                 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
703         }
704
705         // At least 10 numbers shall be secure enought!
706         $len = getCodeLength();
707         if ($len == '0') $len = $length;
708         if ($len == '0') $len = 10;
709
710         // Cut off requested counts of number
711         $return = substr(str_replace('.', '', $rcode), 0, $len);
712
713         // Done building code
714         return $return;
715 }
716
717 // Does only allow numbers
718 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
719         // Filter all numbers out
720         $ret = preg_replace('/[^0123456789]/', '', $num);
721
722         // Shall we cast?
723         if ($castValue === true) {
724                 // Cast to biggest numeric type
725                 $ret = (double) $ret;
726         } // END - if
727
728         // Has the whole value changed?
729         if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true) && (!is_null($num))) {
730                 // Log the values
731                 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
732         } // END - if
733
734         // Return result
735         return $ret;
736 }
737
738 // Creates a Uni* timestamp from given selection data and prefix
739 function createTimestampFromSelections ($prefix, $postData) {
740         // Initial return value
741         $ret = '0';
742
743         // Do we have a leap year?
744         $SWITCH = '0';
745         $TEST = getYear() / 4;
746         $M1   = getMonth();
747
748         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
749         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02'))  $SWITCH = getOneDay();
750
751         // First add years...
752         $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
753
754         // Next months...
755         $ret += $postData[$prefix . '_mo'] * 2628000;
756
757         // Next weeks
758         $ret += $postData[$prefix . '_we'] * 604800;
759
760         // Next days...
761         $ret += $postData[$prefix . '_da'] * 86400;
762
763         // Next hours...
764         $ret += $postData[$prefix . '_ho'] * 3600;
765
766         // Next minutes..
767         $ret += $postData[$prefix . '_mi'] * 60;
768
769         // And at last seconds...
770         $ret += $postData[$prefix . '_se'];
771
772         // Return calculated value
773         return $ret;
774 }
775
776 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
777 function createFancyTime ($stamp) {
778         // Get data array with years/months/weeks/days/...
779         $data = createTimeSelections($stamp, '', '', '', true);
780         $ret = '';
781         foreach ($data as $k => $v) {
782                 if ($v > 0) {
783                         // Value is greater than 0 "eval" data to return string
784                         $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
785                         break;
786                 } // END - if
787         } // END - foreach
788
789         // Do we have something there?
790         if (strlen($ret) > 0) {
791                 // Remove leading commata and space
792                 $ret = substr($ret, 2);
793         } else {
794                 // Zero seconds
795                 $ret = '0 {--_SECONDS--}';
796         }
797
798         // Return fancy time string
799         return $ret;
800 }
801
802 // Extract host from script name
803 function extractHostnameFromUrl (&$script) {
804         // Use default SERVER_URL by default... ;) So?
805         $url = getServerUrl();
806
807         // Is this URL valid?
808         if (substr($script, 0, 7) == 'http://') {
809                 // Use the hostname from script URL as new hostname
810                 $url = substr($script, 7);
811                 $extract = explode('/', $url);
812                 $url = $extract[0];
813                 // Done extracting the URL :)
814         } // END - if
815
816         // Extract host name
817         $host = str_replace('http://', '', $url);
818         if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
819
820         // Generate relative URL
821         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
822         if (substr(strtolower($script), 0, 7) == 'http://') {
823                 // But only if http:// is in front!
824                 $script = substr($script, (strlen($url) + 7));
825         } elseif (substr(strtolower($script), 0, 8) == 'https://') {
826                 // Does this work?!
827                 $script = substr($script, (strlen($url) + 8));
828         }
829
830         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
831         if (substr($script, 0, 1) == '/') $script = substr($script, 1);
832
833         // Return host name
834         return $host;
835 }
836
837 // Send a GET request
838 function sendGetRequest ($script, $data = array()) {
839         // Extract host name from script
840         $host = extractHostnameFromUrl($script);
841
842         // Add data
843         $body = http_build_query($data, '', '&');
844
845         // There should be data, else we don't need to extend $script with $body
846         if (empty($body)) {
847                 // Do we have a question-mark in the script?
848                 if (strpos($script, '?') === false) {
849                         // No, so first char must be question mark
850                         $body = '?' . $body;
851                 } else {
852                         // Ok, add &
853                         $body = '&' . $body;
854                 }
855
856                 // Add script data
857                 $script .= $body;
858
859                 // Remove trailed & to make it more conform
860                 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
861         } // END - if
862
863         // Generate GET request header
864         $request  = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
865         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
866         $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
867         if (isConfigEntrySet('FULL_VERSION')) {
868                 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
869         } else {
870                 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
871         }
872         $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
873         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
874         $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
875         $request .= 'Connection: close' . getConfig('HTTP_EOL');
876         $request .= getConfig('HTTP_EOL');
877
878         // Send the raw request
879         $response = sendRawRequest($host, $request);
880
881         // Return the result to the caller function
882         return $response;
883 }
884
885 // Send a POST request
886 function sendPostRequest ($script, $postData) {
887         // Is postData an array?
888         if (!is_array($postData)) {
889                 // Abort here
890                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
891                 return array('', '', '');
892         } // END - if
893
894         // Extract host name from script
895         $host = extractHostnameFromUrl($script);
896
897         // Construct request body
898         $body = http_build_query($postData, '', '&');
899
900         // Generate POST request header
901         $request  = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
902         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
903         $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
904         $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
905         $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
906         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
907         $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
908         $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
909         $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
910         $request .= 'Connection: close' . getConfig('HTTP_EOL');
911         $request .= getConfig('HTTP_EOL');
912
913         // Add body
914         $request .= $body;
915
916         // Send the raw request
917         $response = sendRawRequest($host, $request);
918
919         // Return the result to the caller function
920         return $response;
921 }
922
923 // Sends a raw request to another host
924 function sendRawRequest ($host, $request) {
925         // Init errno and errdesc with 'all fine' values
926         $errno = '0'; $errdesc = '';
927
928         // Initialize array
929         $response = array('', '', '');
930
931         // Default is not to use proxy
932         $useProxy = false;
933
934         // Are proxy settins set?
935         if (isProxyUsed()) {
936                 // Then use it
937                 $useProxy = true;
938         } // END - if
939
940         // Load include
941         loadIncludeOnce('inc/classes/resolver.class.php');
942
943         // Get resolver instance
944         $resolver = new HostnameResolver();
945
946         // Open connection
947         //* DEBUG: */ die('SCRIPT=' . $script);
948         if ($useProxy === true) {
949                 // Resolve hostname into IP address
950                 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
951
952                 // Connect to host through proxy connection
953                 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
954         } else {
955                 // Resolve hostname into IP address
956                 $ip = $resolver->resolveHostname($host);
957
958                 // Connect to host directly
959                 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
960         }
961
962         // Is there a link?
963         if (!is_resource($fp)) {
964                 // Failed!
965                 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
966                 return $response;
967         } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
968                 // Cannot set non-blocking mode or timeout
969                 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
970                 return $response;
971         }
972
973         // Do we use proxy?
974         if ($useProxy === true) {
975                 // Setup proxy tunnel
976                 $response = setupProxyTunnel($host, $fp);
977
978                 // If the response is invalid, abort
979                 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
980                         // Invalid response!
981                         logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
982                         return $response;
983                 } // END - if
984         } // END - if
985
986         // Write request
987         fwrite($fp, $request);
988
989         // Start counting
990         $start = microtime(true);
991
992         // Read response
993         while (!feof($fp)) {
994                 // Get info from stream
995                 $info = stream_get_meta_data($fp);
996
997                 // Is it timed out? 15 seconds is a really patient...
998                 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
999                         // Timeout
1000                         logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1001
1002                         // Abort here
1003                         break;
1004                 } // END - if
1005
1006                 // Get line from stream
1007                 $line = fgets($fp, 128);
1008
1009                 // Ignore empty lines because of non-blocking mode
1010                 if (empty($line)) {
1011                         // uslepp a little to avoid 100% CPU load
1012                         usleep(10);
1013
1014                         // Skip this
1015                         continue;
1016                 } // END - if
1017
1018                 // Add it to response
1019                 $response[] = trim($line);
1020         } // END - while
1021
1022         // Close socket
1023         fclose($fp);
1024
1025         // Time request if debug-mode is enabled
1026         if (isDebugModeEnabled()) {
1027                 // Add debug message...
1028                 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1029         } // END - if
1030
1031         // Skip first empty lines
1032         $resp = $response;
1033         foreach ($resp as $idx => $line) {
1034                 // Trim space away
1035                 $line = trim($line);
1036
1037                 // Is this line empty?
1038                 if (empty($line)) {
1039                         // Then remove it
1040                         array_shift($response);
1041                 } else {
1042                         // Abort on first non-empty line
1043                         break;
1044                 }
1045         } // END - foreach
1046
1047         //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1048         //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1049
1050         // Proxy agent found or something went wrong?
1051         if (!isset($response[0])) {
1052                 // No response, maybe timeout
1053                 $response = array('', '', '');
1054                 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1055         } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1056                 // Proxy header detected, so remove two lines
1057                 array_shift($response);
1058                 array_shift($response);
1059         } // END - if
1060
1061         // Was the request successfull?
1062         if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1063                 // Not found / access forbidden
1064                 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1065                 $response = array('', '', '');
1066         } // END - if
1067
1068         // Return response
1069         return $response;
1070 }
1071
1072 // Sets up a proxy tunnel for given hostname and through resource
1073 function setupProxyTunnel ($host, $resource) {
1074         // Initialize array
1075         $response = array('', '', '');
1076
1077         // Generate CONNECT request header
1078         $proxyTunnel  = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1079         $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1080
1081         // Use login data to proxy? (username at least!)
1082         if (getConfig('proxy_username') != '') {
1083                 // Add it as well
1084                 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1085                 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1086         } // END - if
1087
1088         // Add last new-line
1089         $proxyTunnel .= getConfig('HTTP_EOL');
1090         //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1091
1092         // Write request
1093         fwrite($fp, $proxyTunnel);
1094
1095         // Got response?
1096         if (feof($fp)) {
1097                 // No response received
1098                 return $response;
1099         } // END - if
1100
1101         // Read the first line
1102         $resp = trim(fgets($fp, 10240));
1103         $respArray = explode(' ', $resp);
1104         if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1105                 // Invalid response!
1106                 return $response;
1107         } // END - if
1108
1109         // All fine!
1110         return $respArray;
1111 }
1112
1113 // Taken from www.php.net isInStringIgnoreCase() user comments
1114 function isEmailValid ($email) {
1115         // Check first part of email address
1116         $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1117
1118         //  Check domain
1119         $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1120
1121         // Generate pattern
1122         $regex = '@^' . $first . '\@' . $domain . '$@iU';
1123
1124         // Return check result
1125         return preg_match($regex, $email);
1126 }
1127
1128 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1129 function isUrlValid ($URL, $compile=true) {
1130         // Trim URL a little
1131         $URL = trim(urldecode($URL));
1132         //* DEBUG: */ debugOutput($URL);
1133
1134         // Compile some chars out...
1135         if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1136         //* DEBUG: */ debugOutput($URL);
1137
1138         // Check for the extension filter
1139         if (isExtensionActive('filter')) {
1140                 // Use the extension's filter set
1141                 return FILTER_VALIDATE_URL($URL, false);
1142         } // END - if
1143
1144         // If not installed, perform a simple test. Just make it sure there is always a http:// or
1145         // https:// in front of the URLs
1146         return isUrlValidSimple($URL);
1147 }
1148
1149 // Generate a hash for extra-security for all passwords
1150 function generateHash ($plainText, $salt = '', $hash = true) {
1151         // Debug output
1152         //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
1153
1154         // Is the required extension 'sql_patches' there and a salt is not given?
1155         // 123                            4                      43    3     4     432    2                  3             32    2                             3                32    2      3     3      21
1156         if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
1157                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1158                 if ($hash === true) {
1159                         // Is plain password
1160                         return md5($plainText);
1161                 } else {
1162                         // Is already a hash
1163                         return $plainText;
1164                 }
1165         } // END - if
1166
1167         // Do we miss an arry element here?
1168         if (!isConfigEntrySet('file_hash')) {
1169                 // Stop here
1170                 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
1171         } // END - if
1172
1173         // When the salt is empty build a new one, else use the first x configured characters as the salt
1174         if (empty($salt)) {
1175                 // Build server string for more entropy
1176                 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
1177
1178                 // Build key string
1179                 $keys   = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
1180
1181                 // Additional data
1182                 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
1183
1184                 // Calculate number for generating the code
1185                 $a = time() + getConfig('_ADD') - 1;
1186
1187                 // Generate SHA1 sum from modula of number and the prime number
1188                 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a);
1189                 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
1190                 $sha1 = scrambleString($sha1);
1191                 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
1192                 //* DEBUG: */ $sha1b = descrambleString($sha1);
1193                 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
1194
1195                 // Generate the password salt string
1196                 $salt = substr($sha1, 0, getSaltLength());
1197                 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
1198         } else {
1199                 // Use given salt
1200                 //* DEBUG: */ debugOutput('salt=' . $salt);
1201                 $salt = substr($salt, 0, getSaltLength());
1202                 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
1203
1204                 // Sanity check on salt
1205                 if (strlen($salt) != getSaltLength()) {
1206                         // Not the same!
1207                         debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
1208                 } // END - if
1209         }
1210
1211         // Generate final hash (for debug output)
1212         $finalHash = $salt . sha1($salt . $plainText);
1213
1214         // Debug output
1215         //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
1216
1217         // Return hash
1218         return $finalHash;
1219 }
1220
1221 // Scramble a string
1222 function scrambleString ($str) {
1223         // Init
1224         $scrambled = '';
1225
1226         // Final check, in case of failture it will return unscrambled string
1227         if (strlen($str) > 40) {
1228                 // The string is to long
1229                 return $str;
1230         } elseif (strlen($str) == 40) {
1231                 // From database
1232                 $scrambleNums = explode(':', getPassScramble());
1233         } else {
1234                 // Generate new numbers
1235                 $scrambleNums = explode(':', genScrambleString(strlen($str)));
1236         }
1237
1238         // Compare both lengths and abort if different
1239         if (strlen($str) != count($scrambleNums)) return $str;
1240
1241         // Scramble string here
1242         //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
1243         for ($idx = 0; $idx < strlen($str); $idx++) {
1244                 // Get char on scrambled position
1245                 $char = substr($str, $scrambleNums[$idx], 1);
1246
1247                 // Add it to final output string
1248                 $scrambled .= $char;
1249         } // END - for
1250
1251         // Return scrambled string
1252         //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
1253         return $scrambled;
1254 }
1255
1256 // De-scramble a string scrambled by scrambleString()
1257 function descrambleString ($str) {
1258         // Scramble only 40 chars long strings
1259         if (strlen($str) != 40) return $str;
1260
1261         // Load numbers from config
1262         $scrambleNums = explode(':', getPassScramble());
1263
1264         // Validate numbers
1265         if (count($scrambleNums) != 40) return $str;
1266
1267         // Begin descrambling
1268         $orig = str_repeat(' ', 40);
1269         //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
1270         for ($idx = 0; $idx < 40; $idx++) {
1271                 $char = substr($str, $idx, 1);
1272                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1273         } // END - for
1274
1275         // Return scrambled string
1276         //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1277         return $orig;
1278 }
1279
1280 // Generated a "string" for scrambling
1281 function genScrambleString ($len) {
1282         // Prepare array for the numbers
1283         $scrambleNumbers = array();
1284
1285         // First we need to setup randomized numbers from 0 to 31
1286         for ($idx = 0; $idx < $len; $idx++) {
1287                 // Generate number
1288                 $rand = mt_rand(0, ($len - 1));
1289
1290                 // Check for it by creating more numbers
1291                 while (array_key_exists($rand, $scrambleNumbers)) {
1292                         $rand = mt_rand(0, ($len - 1));
1293                 } // END - while
1294
1295                 // Add number
1296                 $scrambleNumbers[$rand] = $rand;
1297         } // END - for
1298
1299         // So let's create the string for storing it in database
1300         $scrambleString = implode(':', $scrambleNumbers);
1301         return $scrambleString;
1302 }
1303
1304 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1305 function encodeHashForCookie ($passHash) {
1306         // Return vanilla password hash
1307         $ret = $passHash;
1308
1309         // Is a secret key and master salt already initialized?
1310         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1311         if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1312                 // Only calculate when the secret key is generated
1313                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1314                 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1315                         // Both keys must have same length so return unencrypted
1316                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1317                         return $ret;
1318                 } // END - if
1319
1320                 $newHash = ''; $start = 9;
1321                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1322                 for ($idx = 0; $idx < 20; $idx++) {
1323                         $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1324                         $part2 = hexdec(substr(getSecretKey(), $start, 2));
1325                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1326                         $mod = dechex($idx);
1327                         if ($part1 > $part2) {
1328                                 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1329                         } elseif ($part2 > $part1) {
1330                                 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1331                         }
1332                         $mod = substr($mod, 0, 2);
1333                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1334                         $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1335                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1336                         $start += 2;
1337                         $newHash .= $mod;
1338                 } // END - for
1339
1340                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1341                 $ret = generateHash($newHash, getMasterSalt());
1342         } // END - if
1343
1344         // Return result
1345         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1346         return $ret;
1347 }
1348
1349 // Fix "deleted" cookies
1350 function fixDeletedCookies ($cookies) {
1351         // Is this an array with entries?
1352         if ((is_array($cookies)) && (count($cookies) > 0)) {
1353                 // Then check all cookies if they are marked as deleted!
1354                 foreach ($cookies as $cookieName) {
1355                         // Is the cookie set to "deleted"?
1356                         if (getSession($cookieName) == 'deleted') {
1357                                 setSession($cookieName, '');
1358                         } // END - if
1359                 } // END - foreach
1360         } // END - if
1361 }
1362
1363 // Checks if a given apache module is loaded
1364 function isApacheModuleLoaded ($apacheModule) {
1365         // Check it and return result
1366         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1367 }
1368
1369 // Get current theme name
1370 function getCurrentTheme () {
1371         // The default theme is 'default'... ;-)
1372         $ret = 'default';
1373
1374         // Do we have ext-theme installed and active?
1375         if (isExtensionActive('theme')) {
1376                 // Call inner method
1377                 $ret = getActualTheme();
1378         } // END - if
1379
1380         // Return theme value
1381         return $ret;
1382 }
1383
1384 // Generates an error code from given account status
1385 function generateErrorCodeFromUserStatus ($status = '') {
1386         // If no status is provided, use the default, cached
1387         if ((empty($status)) && (isMember())) {
1388                 // Get user status
1389                 $status = getUserData('status');
1390         } // END - if
1391
1392         // Default error code if unknown account status
1393         $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1394
1395         // Generate constant name
1396         $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1397
1398         // Is the constant there?
1399         if (isCodeSet($codeName)) {
1400                 // Then get it!
1401                 $errorCode = getCode($codeName);
1402         } else {
1403                 // Unknown status
1404                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1405         }
1406
1407         // Return error code
1408         return $errorCode;
1409 }
1410
1411 // Back-ported from the new ship-simu engine. :-)
1412 function debug_get_printable_backtrace () {
1413         // Init variable
1414         $backtrace = '<ol>';
1415
1416         // Get and prepare backtrace for output
1417         $backtraceArray = debug_backtrace();
1418         foreach ($backtraceArray as $key => $trace) {
1419                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1420                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1421                 if (!isset($trace['args'])) $trace['args'] = array();
1422                 $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>';
1423         } // END - foreach
1424
1425         // Close it
1426         $backtrace .= '</ol>';
1427
1428         // Return the backtrace
1429         return $backtrace;
1430 }
1431
1432 // A mail-able backtrace
1433 function debug_get_mailable_backtrace () {
1434         // Init variable
1435         $backtrace = '';
1436
1437         // Get and prepare backtrace for output
1438         $backtraceArray = debug_backtrace();
1439         foreach ($backtraceArray as $key => $trace) {
1440                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1441                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1442                 if (!isset($trace['args'])) $trace['args'] = array();
1443                 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1444         } // END - foreach
1445
1446         // Return the backtrace
1447         return $backtrace;
1448 }
1449
1450 // Generates a ***weak*** seed
1451 function generateSeed () {
1452         return microtime(true) * 100000;
1453 }
1454
1455 // Converts a message code to a human-readable message
1456 function getMessageFromErrorCode ($code) {
1457         $message = '';
1458         switch ($code) {
1459                 case '': break;
1460                 case getCode('LOGOUT_DONE')        : $message = '{--LOGOUT_DONE--}'; break;
1461                 case getCode('LOGOUT_FAILED')      : $message = '<span class="notice">{--LOGOUT_FAILED--}</span>'; break;
1462                 case getCode('DATA_INVALID')       : $message = '{--MAIL_DATA_INVALID--}'; break;
1463                 case getCode('POSSIBLE_INVALID')   : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1464                 case getCode('USER_404')           : $message = '{--USER_404--}'; break;
1465                 case getCode('STATS_404')          : $message = '{--MAIL_STATS_404--}'; break;
1466                 case getCode('ALREADY_CONFIRMED')  : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1467                 case getCode('WRONG_PASS')         : $message = '{--LOGIN_WRONG_PASS--}'; break;
1468                 case getCode('WRONG_ID')           : $message = '{--LOGIN_WRONG_ID--}'; break;
1469                 case getCode('ACCOUNT_LOCKED')     : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1470                 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1471                 case getCode('COOKIES_DISABLED')   : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1472                 case getCode('BEG_SAME_AS_OWN')    : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1473                 case getCode('LOGIN_FAILED')       : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1474                 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1475                 case getCode('OVERLENGTH')         : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1476                 case getCode('URL_FOUND')          : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1477                 case getCode('SUBJECT_URL')        : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1478                 case getCode('BLIST_URL')          : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1479                 case getCode('NO_RECS_LEFT')       : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1480                 case getCode('INVALID_TAGS')       : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1481                 case getCode('MORE_POINTS')        : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1482                 case getCode('MORE_RECEIVERS1')    : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1483                 case getCode('MORE_RECEIVERS2')    : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1484                 case getCode('MORE_RECEIVERS3')    : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1485                 case getCode('INVALID_URL')        : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1486                 case getCode('NO_MAIL_TYPE')       : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1487                 case getCode('UNKNOWN_ERROR')      : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1488                 case getCode('UNKNOWN_STATUS')     : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1489                 case getCode('PROFILE_UPDATED')    : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1490
1491                 case getCode('ERROR_MAILID'):
1492                         if (isExtensionActive('mailid', true)) {
1493                                 $message = '{--ERROR_CONFIRMING_MAIL--}';
1494                         } else {
1495                                 $message = generateExtensionInactiveNotInstalledMessage('mailid');
1496                         }
1497                         break;
1498
1499                 case getCode('EXTENSION_PROBLEM'):
1500                         if (isGetRequestParameterSet('ext')) {
1501                                 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1502                         } else {
1503                                 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1504                         }
1505                         break;
1506
1507                 case getCode('URL_TIME_LOCK'):
1508                         // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1509                         $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1510                                 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1511
1512                         // Load timestamp from last order
1513                         $content = SQL_FETCHARRAY($result);
1514
1515                         // Free memory
1516                         SQL_FREERESULT($result);
1517
1518                         // Translate it for templates
1519                         $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1520
1521                         // Calculate hours...
1522                         $content['hours'] = round(getConfig('url_tlock') / 60 / 60);
1523
1524                         // Minutes...
1525                         $content['minutes'] = round((getConfig('url_tlock') - $content['hours'] * 60 * 60) / 60);
1526
1527                         // And seconds
1528                         $content['seconds'] = round(getConfig('url_tlock') - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1529
1530                         // Finally contruct the message
1531                         $message = loadTemplate('tlock_message', true, $content);
1532                         break;
1533
1534                 default:
1535                         // Missing/invalid code
1536                         $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1537
1538                         // Log it
1539                         logDebugMessage(__FUNCTION__, __LINE__, $message);
1540                         break;
1541         } // END - switch
1542
1543         // Return the message
1544         return $message;
1545 }
1546
1547 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1548 function isUrlValidSimple ($url) {
1549         // Prepare URL
1550         $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1551
1552         // Allows http and https
1553         $http      = "(http|https)+(:\/\/)";
1554         // Test domain
1555         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1556         // Test double-domains (e.g. .de.vu)
1557         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1558         // Test IP number
1559         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1560         // ... directory
1561         $dir       = "((/)+([-_\.[:alnum:]])+)*";
1562         // ... page
1563         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1564         // ... and the string after and including question character
1565         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1566         // Pattern for URLs like http://url/dir/doc.html?var=value
1567         $pattern['d1dpg1']  = $http . $domain1 . $dir . $page . $getstring1;
1568         $pattern['d2dpg1']  = $http . $domain2 . $dir . $page . $getstring1;
1569         $pattern['ipdpg1']  = $http . $ip . $dir . $page . $getstring1;
1570         // Pattern for URLs like http://url/dir/?var=value
1571         $pattern['d1dg1']  = $http . $domain1 . $dir.'/' . $getstring1;
1572         $pattern['d2dg1']  = $http . $domain2 . $dir.'/' . $getstring1;
1573         $pattern['ipdg1']  = $http . $ip . $dir.'/' . $getstring1;
1574         // Pattern for URLs like http://url/dir/page.ext
1575         $pattern['d1dp']  = $http . $domain1 . $dir . $page;
1576         $pattern['d1dp']  = $http . $domain2 . $dir . $page;
1577         $pattern['ipdp']  = $http . $ip . $dir . $page;
1578         // Pattern for URLs like http://url/dir
1579         $pattern['d1d']  = $http . $domain1 . $dir;
1580         $pattern['d2d']  = $http . $domain2 . $dir;
1581         $pattern['ipd']  = $http . $ip . $dir;
1582         // Pattern for URLs like http://url/?var=value
1583         $pattern['d1g1']  = $http . $domain1 . '/' . $getstring1;
1584         $pattern['d2g1']  = $http . $domain2 . '/' . $getstring1;
1585         $pattern['ipg1']  = $http . $ip . '/' . $getstring1;
1586         // Pattern for URLs like http://url?var=value
1587         $pattern['d1g12']  = $http . $domain1 . $getstring1;
1588         $pattern['d2g12']  = $http . $domain2 . $getstring1;
1589         $pattern['ipg12']  = $http . $ip . $getstring1;
1590
1591         // Test all patterns
1592         $reg = false;
1593         foreach ($pattern as $key => $pat) {
1594                 // Debug regex?
1595                 if (isDebugRegularExpressionEnabled()) {
1596                         // @TODO Are these convertions still required?
1597                         $pat = str_replace('.', '&#92;&#46;', $pat);
1598                         $pat = str_replace('@', '&#92;&#64;', $pat);
1599                         //* DEBUG: */ debugOutput($key . '=&nbsp;' . $pat);
1600                 } // END - if
1601
1602                 // Check if expression matches
1603                 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1604
1605                 // Does it match?
1606                 if ($reg === true) break;
1607         }
1608
1609         // Return true/false
1610         return $reg;
1611 }
1612
1613 // Wtites data to a config.php-style file
1614 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1615 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1616         // Initialize some variables
1617         $done = false;
1618         $seek++;
1619         $next  = -1;
1620         $found = false;
1621
1622         // Is the file there and read-/write-able?
1623         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1624                 $search = 'CFG: ' . $comment;
1625                 $tmp = $FQFN . '.tmp';
1626
1627                 // Open the source file
1628                 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1629
1630                 // Is the resource valid?
1631                 if (is_resource($fp)) {
1632                         // Open temporary file
1633                         $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1634
1635                         // Is the resource again valid?
1636                         if (is_resource($fp_tmp)) {
1637                                 // Mark temporary file as readable
1638                                 $GLOBALS['file_readable'][$tmp] = true;
1639
1640                                 // Start reading
1641                                 while (!feof($fp)) {
1642                                         // Read from source file
1643                                         $line = fgets ($fp, 1024);
1644
1645                                         if (strpos($line, $search) > -1) { 
1646                                                 $next = '0';
1647                                                 $found = true;
1648                                         } // END - if
1649
1650                                         if ($next > -1) {
1651                                                 if ($next === $seek) {
1652                                                         $next = -1;
1653                                                         $line = $prefix . $DATA . $suffix . "\n";
1654                                                 } else {
1655                                                         $next++;
1656                                                 }
1657                                         } // END - if
1658
1659                                         // Write to temp file
1660                                         fwrite($fp_tmp, $line);
1661                                 } // END - while
1662
1663                                 // Close temp file
1664                                 fclose($fp_tmp);
1665
1666                                 // Finished writing tmp file
1667                                 $done = true;
1668                         } // END - if
1669
1670                         // Close source file
1671                         fclose($fp);
1672
1673                         if (($done === true) && ($found === true)) {
1674                                 // Copy back tmp file and delete tmp :-)
1675                                 copyFileVerified($tmp, $FQFN, 0644);
1676                                 return removeFile($tmp);
1677                         } elseif ($found === false) {
1678                                 outputHtml('<strong>CHANGE:</strong> 404!');
1679                         } else {
1680                                 outputHtml('<strong>TMP:</strong> UNDONE!');
1681                         }
1682                 }
1683         } else {
1684                 // File not found, not readable or writeable
1685                 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1686         }
1687
1688         // An error was detected!
1689         return false;
1690 }
1691
1692 // Send notification to admin
1693 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = '0') {
1694         if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1695                 // Send new way
1696                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName);
1697                 sendAdminsEmails($subject, $templateName, $content, $userid);
1698         } else {
1699                 // Send out-dated way
1700                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName);
1701                 $message = loadEmailTemplate($templateName, $content, $userid);
1702                 sendAdminEmails($subject, $message);
1703         }
1704 }
1705
1706 // Debug message logger
1707 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1708         // Is debug mode enabled?
1709         if ((isDebugModeEnabled()) || ($force === true)) {
1710                 // Remove CRLF
1711                 $message = str_replace("\r", '', str_replace("\n", '', $message));
1712
1713                 // Log this message away
1714                 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1715         } // END - if
1716 }
1717
1718 // Handle extra values
1719 function handleExtraValues ($filterFunction, $value, $extraValue) {
1720         // Default is the value itself
1721         $ret = $value;
1722
1723         // Do we have a special filter function?
1724         if (!empty($filterFunction)) {
1725                 // Does the filter function exist?
1726                 if (function_exists($filterFunction)) {
1727                         // Do we have extra parameters here?
1728                         if (!empty($extraValue)) {
1729                                 // Put both parameters in one new array by default
1730                                 $args = array($value, $extraValue);
1731
1732                                 // If we have an array simply use it and pre-extend it with our value
1733                                 if (is_array($extraValue)) {
1734                                         // Make the new args array
1735                                         $args = merge_array(array($value), $extraValue);
1736                                 } // END - if
1737
1738                                 // Call the multi-parameter call-back
1739                                 $ret = call_user_func_array($filterFunction, $args);
1740                         } else {
1741                                 // One parameter call
1742                                 $ret = call_user_func($filterFunction, $value);
1743                         }
1744                 } // END - if
1745         } // END - if
1746
1747         // Return the value
1748         return $ret;
1749 }
1750
1751 // Converts timestamp selections into a timestamp
1752 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1753         // Init test variable
1754         $skip  = false;
1755         $test2 = '';
1756
1757         // Get last three chars
1758         $test = substr($id, -3);
1759
1760         // Improved way of checking! :-)
1761         if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1762                 // Found a multi-selection for timings?
1763                 $test = substr($id, 0, -3);
1764                 if ((isset($postData[$test.'_ye'])) && (isset($postData[$test.'_mo'])) && (isset($postData[$test.'_we'])) && (isset($postData[$test.'_da'])) && (isset($postData[$test.'_ho'])) && (isset($postData[$test.'_mi'])) && (isset($postData[$test.'_se'])) && ($test != $test2)) {
1765                         // Generate timestamp
1766                         $postData[$test] = createTimestampFromSelections($test, $postData);
1767                         $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1768                         $GLOBALS['skip_config'][$test] = true;
1769
1770                         // Remove data from array
1771                         foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1772                                 unset($postData[$test . '_' . $rem]);
1773                         } // END - foreach
1774
1775                         // Skip adding
1776                         unset($id);
1777                         $skip = true;
1778                         $test2 = $test;
1779                 } // END - if
1780         } // END - if
1781 }
1782
1783 // Reverts the german decimal comma into Computer decimal dot
1784 function convertCommaToDot ($str) {
1785         // Default float is not a float... ;-)
1786         $float = false;
1787
1788         // Which language is selected?
1789         switch (getLanguage()) {
1790                 case 'de': // German language
1791                         // Remove german thousand dots first
1792                         $str = str_replace('.', '', $str);
1793
1794                         // Replace german commata with decimal dot and cast it
1795                         $float = (float)str_replace(',', '.', $str);
1796                         break;
1797
1798                 default: // US and so on
1799                         // Remove thousand dots first and cast
1800                         $float = (float)str_replace(',', '', $str);
1801                         break;
1802         }
1803
1804         // Return float
1805         return $float;
1806 }
1807
1808 // Handle menu-depending failed logins and return the rendered content
1809 function handleLoginFailures ($accessLevel) {
1810         // Default output is empty ;-)
1811         $OUT = '';
1812
1813         // Is the session data set?
1814         if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1815                 // Ignore zero values
1816                 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1817                         // Non-guest has login failures found, get both data and prepare it for template
1818                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1819                         $content = array(
1820                                 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1821                                 'last_failure'   => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1822                         );
1823
1824                         // Load template
1825                         $OUT = loadTemplate('login_failures', true, $content);
1826                 } // END - if
1827
1828                 // Reset session data
1829                 setSession('mailer_' . $accessLevel . '_failures', '');
1830                 setSession('mailer_' . $accessLevel . '_last_failure', '');
1831         } // END - if
1832
1833         // Return rendered content
1834         return $OUT;
1835 }
1836
1837 // Rebuild cache
1838 function rebuildCache ($cache, $inc = '', $force = false) {
1839         // Debug message
1840         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1841
1842         // Shall I remove the cache file?
1843         if (isCacheInstanceValid()) {
1844                 // Rebuild cache
1845                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1846                         // Destroy it
1847                         $GLOBALS['cache_instance']->removeCacheFile($force);
1848                 } // END - if
1849
1850                 // Include file given?
1851                 if (!empty($inc)) {
1852                         // Construct FQFN
1853                         $inc = sprintf("inc/loader/load-%s.php", $inc);
1854
1855                         // Is the include there?
1856                         if (isIncludeReadable($inc)) {
1857                                 // And rebuild it from scratch
1858                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1859                                 loadInclude($inc);
1860                         } else {
1861                                 // Include not found
1862                                 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1863                         }
1864                 } // END - if
1865         } // END - if
1866 }
1867
1868 // Determines the real remote address
1869 function determineRealRemoteAddress ($remoteAddr = false) {
1870         // Is a proxy in use?
1871         if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1872                 // Proxy was used
1873                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1874         } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1875                 // Yet, another proxy
1876                 $address = $_SERVER['HTTP_CLIENT_IP'];
1877         } else {
1878                 // The regular address when no proxy was used
1879                 $address = $_SERVER['REMOTE_ADDR'];
1880         }
1881
1882         // This strips out the real address from proxy output
1883         if (strstr($address, ',')) {
1884                 $addressArray = explode(',', $address);
1885                 $address = $addressArray[0];
1886         } // END - if
1887
1888         // Return the result
1889         return $address;
1890 }
1891
1892 // Adds a bonus mail to the queue
1893 // This is a high-level function!
1894 function addNewBonusMail ($data, $mode = '', $output = true) {
1895         // Use mode from data if not set and availble ;-)
1896         if ((empty($mode)) && (isset($data['mode']))) {
1897                 $mode = $data['mode'];
1898         } // END - if
1899
1900         // Generate receiver list
1901         $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1902
1903         // Receivers added?
1904         if (!empty($receiver)) {
1905                 // Add bonus mail to queue
1906                 addBonusMailToQueue(
1907                         $data['subject'],
1908                         $data['text'],
1909                         $receiver,
1910                         $data['points'],
1911                         $data['seconds'],
1912                         $data['url'],
1913                         $data['cat'],
1914                         $mode,
1915                         $data['receiver']
1916                 );
1917
1918                 // Mail inserted into bonus pool
1919                 if ($output === true) {
1920                         loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
1921                 } // END - if
1922         } elseif ($output === true) {
1923                 // More entered than can be reached!
1924                 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
1925         } else {
1926                 // Debug log
1927                 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1928         }
1929 }
1930
1931 // Determines referal id and sets it
1932 function determineReferalId () {
1933         // Skip this in non-html-mode and outside ref.php
1934         if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) {
1935                 return false;
1936         } // END - if
1937
1938         // Check if refid is set
1939         if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1940                 // This is fine...
1941         } elseif (isPostRequestParameterSet('refid')) {
1942                 // Get referal id from POST element refid
1943                 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1944         } elseif (isGetRequestParameterSet('refid')) {
1945                 // Get referal id from GET parameter refid
1946                 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1947         } elseif (isGetRequestParameterSet('ref')) {
1948                 // Set refid=ref (the referal link uses such variable)
1949                 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1950         } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1951                 // The variable user comes from  click.php
1952                 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1953         } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1954                 // Set session refid als global
1955                 $GLOBALS['refid'] = bigintval(getSession('refid'));
1956         } elseif (isRandomReferalIdEnabled()) {
1957                 // Select a random user which has confirmed enougth mails
1958                 $GLOBALS['refid'] = determineRandomReferalId();
1959         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
1960                 // Set default refid as refid in URL
1961                 $GLOBALS['refid'] = getDefRefid();
1962         } else {
1963                 // No default id when sql_patches is not installed or none set
1964                 $GLOBALS['refid'] = null;
1965         }
1966
1967         // Set cookie when default refid > 0
1968         if (!isSessionVariableSet('refid') || (isValidUserId($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
1969                 // Default is not found
1970                 $found = false;
1971
1972                 // Do we have nickname or userid set?
1973                 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1974                         // Nickname in URL, so load the id
1975                         $found = fetchUserData($GLOBALS['refid'], 'nickname');
1976                 } elseif (isValidUserId($GLOBALS['refid'])) {
1977                         // Direct userid entered
1978                         $found = fetchUserData($GLOBALS['refid']);
1979                 }
1980
1981                 // Is the record valid?
1982                 if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
1983                         // No, then reset referal id
1984                         $GLOBALS['refid'] = getDefRefid();
1985                 } // END - if
1986
1987                 // Set cookie
1988                 setSession('refid', $GLOBALS['refid']);
1989         } // END - if
1990
1991         // Return determined refid
1992         return $GLOBALS['refid'];
1993 }
1994
1995 // Enables the reset mode and runs it
1996 function doReset () {
1997         // Enable the reset mode
1998         $GLOBALS['reset_enabled'] = true;
1999
2000         // Run filters
2001         runFilterChain('reset');
2002 }
2003
2004 // Our shutdown-function
2005 function shutdown () {
2006         // Call the filter chain 'shutdown'
2007         runFilterChain('shutdown', null);
2008
2009         // Check if not in installation phase and the link is up
2010         if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
2011                 // Close link
2012                 SQL_CLOSE(__FUNCTION__, __LINE__);
2013         } elseif (!isInstallationPhase()) {
2014                 // No database link
2015                 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
2016         }
2017
2018         // Stop executing here
2019         exit;
2020 }
2021
2022 // Init member id
2023 function initMemberId () {
2024         $GLOBALS['member_id'] = '0';
2025 }
2026
2027 // Setter for member id
2028 function setMemberId ($memberid) {
2029         // We should not set member id to zero
2030         if ($memberid == '0') {
2031                 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
2032         } // END - if
2033
2034         // Set it secured
2035         $GLOBALS['member_id'] = bigintval($memberid);
2036 }
2037
2038 // Getter for member id or returns zero
2039 function getMemberId () {
2040         // Default member id
2041         $memberid = '0';
2042
2043         // Is the member id set?
2044         if (isMemberIdSet()) {
2045                 // Then use it
2046                 $memberid = $GLOBALS['member_id'];
2047         } // END - if
2048
2049         // Return it
2050         return $memberid;
2051 }
2052
2053 // Checks ether the member id is set
2054 function isMemberIdSet () {
2055         return (isset($GLOBALS['member_id']));
2056 }
2057
2058 // Setter for extra title
2059 function setExtraTitle ($extraTitle) {
2060         $GLOBALS['extra_title'] = $extraTitle;
2061 }
2062
2063 // Getter for extra title
2064 function getExtraTitle () {
2065         // Is the extra title set?
2066         if (!isExtraTitleSet()) {
2067                 // No, then abort here
2068                 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
2069         } // END - if
2070
2071         // Return it
2072         return $GLOBALS['extra_title'];
2073 }
2074
2075 // Checks if the extra title is set
2076 function isExtraTitleSet () {
2077         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
2078 }
2079
2080 // Reads a directory recursively by default and searches for files not matching
2081 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
2082 // a whole directory.
2083 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
2084         // Add default entries we should exclude
2085         $excludeArray[] = '.';
2086         $excludeArray[] = '..';
2087         $excludeArray[] = '.svn';
2088         $excludeArray[] = '.htaccess';
2089
2090         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
2091         // Init includes
2092         $files = array();
2093
2094         // Open directory
2095         $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
2096
2097         // Read all entries
2098         while ($baseFile = readdir($dirPointer)) {
2099                 // Exclude '.', '..' and entries in $excludeArray automatically
2100                 if (in_array($baseFile, $excludeArray, true))  {
2101                         // Exclude them
2102                         //* DEBUG: */ debugOutput('excluded=' . $baseFile);
2103                         continue;
2104                 } // END - if
2105
2106                 // Construct include filename and FQFN
2107                 $fileName = $baseDir . $baseFile;
2108                 $FQFN = getPath() . $fileName;
2109
2110                 // Remove double slashes
2111                 $FQFN = str_replace('//', '/', $FQFN);
2112
2113                 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
2114                 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
2115                         // These Lines are only for debugging!!
2116                         //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
2117                         //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
2118                         //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
2119
2120                         // Exclude this one
2121                         continue;
2122                 } // END - if
2123
2124                 // Skip also files with non-matching prefix genericly
2125                 if (($recursive === true) && (isDirectory($FQFN))) {
2126                         // Is a redirectory so read it as well
2127                         $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
2128
2129                         // And skip further processing
2130                         continue;
2131                 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
2132                         // Skip this file
2133                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
2134                         continue;
2135                 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
2136                         // Skip wrong suffix as well
2137                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
2138                         continue;
2139                 } elseif (!isFileReadable($FQFN)) {
2140                         // Not readable so skip it
2141                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
2142                         continue;
2143                 }
2144
2145                 // Get file' extension (last 4 chars)
2146                 $fileExtension = substr($baseFile, -4, 4);
2147
2148                 // Is the file a PHP script or other?
2149                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
2150                 if (($fileExtension == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
2151                         // Is this a valid include file?
2152                         if ($extension == '.php') {
2153                                 // Remove both for extension name
2154                                 $extName = substr($baseFile, strlen($prefix), -4);
2155
2156                                 // Add file with or without base path
2157                                 if ($addBaseDir === true) {
2158                                         // With base path
2159                                         $files[] = $fileName;
2160                                 } else {
2161                                         // No base path
2162                                         $files[] = $baseFile;
2163                                 }
2164                         } else {
2165                                 // We found .php file but should not search for them, why?
2166                                 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
2167                         }
2168                 } elseif ($fileExtension == $extension) {
2169                         // Other, generic file found
2170                         $files[] = $fileName;
2171                 }
2172         } // END - while
2173
2174         // Close directory
2175         closedir($dirPointer);
2176
2177         // Sort array
2178         sort($files);
2179
2180         // Return array with include files
2181         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
2182         return $files;
2183 }
2184
2185 // Checks wether $prefix is found in $fileName
2186 function isFilePrefixFound ($fileName, $prefix) {
2187         // @TODO Find a way to cache this
2188         return (substr($fileName, 0, strlen($prefix)) == $prefix);
2189 }
2190
2191 // Maps a module name into a database table name
2192 function mapModuleToTable ($moduleName) {
2193         // Map only these, still lame code...
2194         switch ($moduleName) {
2195                 // 'index' is the guest's menu
2196                 case 'index': $moduleName = 'guest';  break;
2197                 // ... and 'login' the member's menu
2198                 case 'login': $moduleName = 'member'; break;
2199                 // Anything else will not be mapped, silently.
2200         } // END - switch
2201
2202         // Return result
2203         return $moduleName;
2204 }
2205
2206 // Add SQL debug data to array for later output
2207 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
2208         // Do we have cache?
2209         if (!isset($GLOBALS['debug_sql_available'])) {
2210                 // Check it and cache it in $GLOBALS
2211                 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
2212         } // END - if
2213         
2214         // Don't execute anything here if we don't need or ext-other is missing
2215         if ($GLOBALS['debug_sql_available'] === false) {
2216                 return;
2217         } // END - if
2218
2219         // Already executed?
2220         if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
2221                 // Then abort here, we don't need to profile a query twice
2222                 return;
2223         } // END - if
2224
2225         // Remeber this as profiled (or not, but we don't care here)
2226         $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
2227
2228         // Generate record
2229         $record = array(
2230                 'num_rows' => SQL_NUMROWS($result),
2231                 'affected' => SQL_AFFECTEDROWS(),
2232                 'sql_str'  => $sqlString,
2233                 'timing'   => $timing,
2234                 'file'     => basename($F),
2235                 'line'     => $L
2236         );
2237
2238         // Add it
2239         $GLOBALS['debug_sqls'][] = $record;
2240 }
2241
2242 // Initializes the cache instance
2243 function initCacheInstance () {
2244         // Check for double-initialization
2245         if (isset($GLOBALS['cache_instance'])) {
2246                 // This should not happen and must be fixed
2247                 debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
2248         } // END - if
2249
2250         // Load include for CacheSystem class
2251         loadIncludeOnce('inc/classes/cachesystem.class.php');
2252
2253         // Initialize cache system only when it's needed
2254         $GLOBALS['cache_instance'] = new CacheSystem();
2255
2256         // Did it work?
2257         if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
2258                 // Failed to initialize cache sustem
2259                 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2260         } // END - if
2261 }
2262
2263 // Getter for message from array or raw message
2264 function getMessageFromIndexedArray ($message, $pos, $array) {
2265         // Check if the requested message was found in array
2266         if (isset($array[$pos])) {
2267                 // ... if yes then use it!
2268                 $ret = $array[$pos];
2269         } else {
2270                 // ... else use default message
2271                 $ret = $message;
2272         }
2273
2274         // Return result
2275         return $ret;
2276 }
2277
2278 // Convert ';' to ', ' for e.g. receiver list
2279 function convertReceivers ($old) {
2280         return str_replace(';', ', ', $old);
2281 }
2282
2283 // Get a module from filename and access level
2284 function getModuleFromFileName ($file, $accessLevel) {
2285         // Default is 'invalid';
2286         $modCheck = 'invalid';
2287
2288         // @TODO This is still very static, rewrite it somehow
2289         switch ($accessLevel) {
2290                 case 'admin':
2291                         $modCheck = 'admin';
2292                         break;
2293
2294                 case 'sponsor':
2295                 case 'guest':
2296                 case 'member':
2297                         $modCheck = getModule();
2298                         break;
2299
2300                 default: // Unsupported file name / access level
2301                         debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2302                         break;
2303         }
2304
2305         // Return result
2306         return $modCheck;
2307 }
2308
2309 // Encodes an URL for adding session id, etc.
2310 function encodeUrl ($url, $outputMode = '0') {
2311         // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2312         if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) {
2313                 // Raw output mode detected or session_name() found in URL
2314                 return $url;
2315         } // END - if
2316
2317         // Do we have a valid session?
2318         if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2319                 // Invalid session
2320                 // Determine right seperator
2321                 $seperator = '&amp;';
2322                 if (strpos($url, '?') === false) {
2323                         // No question mark
2324                         $seperator = '?';
2325                 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2326                         // Non-HTML mode (or forced non-HTML mode
2327                         $seperator = '&';
2328                 }
2329
2330                 // Add it to URL
2331                 if (session_id() != '') {
2332                         $url .= $seperator . session_name() . '=' . session_id();
2333                 } // END - if
2334         } // END - if
2335
2336         // Add {?URL?} ?
2337         if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2338                 // Add it
2339                 $url = '{?URL?}/' . $url;
2340         } // END - if
2341
2342         // Return the URL
2343         return $url;
2344 }
2345
2346 // Simple check for spider
2347 function isSpider () {
2348         // Get the UA and trim it down
2349         $userAgent = trim(strtolower(detectUserAgent(true)));
2350
2351         // It should not be empty, if so it is better a spider/bot
2352         if (empty($userAgent)) {
2353                 // It is a spider/bot
2354                 return true;
2355         } // END - if
2356
2357         // Is it a spider?
2358         return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2359 }
2360
2361 // Function to search for the last modified file
2362 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2363         // Get dir as array
2364         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2365         // Does it match what we are looking for? (We skip a lot files already!)
2366         // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
2367         $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2368
2369         $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2370         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2371
2372         // Walk through all entries
2373         foreach ($ds as $d) {
2374                 // Generate proper FQFN
2375                 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2376
2377                 // Is it a file and readable?
2378                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2379                 if (isFileReadable($FQFN)) {
2380                         // $FQFN is a readable file so extract the requested data from it
2381                         $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2382                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2383
2384                         // Is the file more recent?
2385                         if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2386                                 // This file is newer as the file before
2387                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2388                                 $last_changed['path_name'] = $FQFN;
2389                                 $last_changed[$lookFor] = $check;
2390                         } // END - if
2391                 } else {
2392                         // Not readable
2393                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2394                 }
2395         } // END - foreach
2396 }
2397
2398 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2399 function handleFieldWithBraces ($field) {
2400         // Are there braces [] at the end?
2401         if (substr($field, -2, 2) == '[]') {
2402                 // Try to find one and replace it. I do it this way to allow easy
2403                 // extending of this code.
2404                 foreach (array('admin_list_builder_id_value') as $key) {
2405                         // Is the cache entry set?
2406                         if (isset($GLOBALS[$key])) {
2407                                 // Insert it
2408                                 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2409
2410                                 // And abort
2411                                 break;
2412                         } // END - if
2413                 } // END - foreach
2414         } // END - if
2415
2416         // Return it
2417         return $field;
2418 }
2419
2420 // Converts a userid so it can be used in SQL queries
2421 function makeDatabaseUserId ($userid) {
2422         // Is it a valid username?
2423         if (isValidUserId($userid)) {
2424                 // Always secure it
2425                 $userid = bigintval($userid);
2426         } else {
2427                 // Is not valid or zero
2428                 $userid = 'NULL';
2429         }
2430
2431         // Return it
2432         return $userid;
2433 }
2434
2435 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2436 // Note: This function is cached
2437 function capitalizeUnderscoreString ($str) {
2438         // Do we have cache?
2439         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2440                 // Init target string
2441                 $capitalized = '';
2442
2443                 // Explode it with the underscore, but rewrite dashes to underscore before
2444                 $strArray = explode('_', str_replace('-', '_', $str));
2445
2446                 // "Walk" through all elements and make them lower-case but first upper-case
2447                 foreach ($strArray as $part) {
2448                         // Capitalize the string part
2449                         $capitalized .= firstCharUpperCase($part);
2450                 } // END - foreach
2451
2452                 // Store the converted string in cache array
2453                 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2454         } // END - if
2455
2456         // Return cache
2457         return $GLOBALS[__FUNCTION__][$str];
2458 }
2459
2460 // Generate admin links for mail order
2461 // mailType can be: 'mid' or 'bid'
2462 function generateAdminMailLinks ($mailType, $mailId) {
2463         // Init variables
2464         $OUT = '';
2465         $table = '';
2466
2467         // Default column for mail status is 'data_type'
2468         // @TODO Rename column data_type to e.g. mail_status
2469         $statusColumn = 'data_type';
2470
2471         // Which mail do we have?
2472         switch ($mailType) {
2473                 case 'bid': // Bonus mail
2474                         $table = 'bonus';
2475                         break;
2476
2477                 case 'mid': // Member mail
2478                         $table = 'pool';
2479                         break;
2480
2481                 default: // Handle unsupported types
2482                         logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2483                         $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2484                         break;
2485         } // END - switch
2486
2487         // Is the mail type supported?
2488         if (!empty($table)) {
2489                 // Query for the mail
2490                 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2491                         array($statusColumn, $table, bigintval($mailId)), __FILE__, __LINE__);
2492
2493                 // Do we have one entry there?
2494                 if (SQL_NUMROWS($result) == 1) {
2495                         // Load the entry
2496                         $content = SQL_FETCHARRAY($result);
2497                         die('<pre>'.print_r($content, true).'</pre>');
2498                 } // END - if
2499
2500                 // Free result
2501                 SQL_FREERESULT($result);
2502         } // END - if
2503
2504         // Return generated HTML code
2505         return $OUT;
2506 }
2507
2508 //-----------------------------------------------------------------------------
2509 // Automatically re-created functions, all taken from user comments on www.php.net
2510 //-----------------------------------------------------------------------------
2511 //
2512 if (!function_exists('html_entity_decode')) {
2513         // Taken from documentation on www.php.net
2514         function html_entity_decode ($string) {
2515                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2516                 $trans_tbl = array_flip($trans_tbl);
2517                 return strtr($string, $trans_tbl);
2518         }
2519 } // END - if
2520
2521 if (!function_exists('http_build_query')) {
2522         // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
2523         function http_build_query($data, $prefix = '', $sep = '', $key = '') {
2524                 $ret = array();
2525                 foreach ((array) $data as $k => $v) {
2526                         if (is_int($k) && $prefix != null) {
2527                                 $k = urlencode($prefix . $k);
2528                         } // END - if
2529
2530                         if ((!empty($key)) || ($key === 0))  $k = $key . '[' . urlencode($k) . ']';
2531
2532                         if (is_array($v) || is_object($v)) {
2533                                 array_push($ret, http_build_query($v, '', $sep, $k));
2534                         } else {
2535                                 array_push($ret, $k.'='.urlencode($v));
2536                         }
2537                 } // END - foreach
2538
2539                 if (empty($sep)) $sep = ini_get('arg_separator.output');
2540
2541                 return implode($sep, $ret);
2542         }
2543 } // END - if
2544
2545 // [EOF]
2546 ?>