1c748c4455fa419f6edf431ecba5cdd74b9fc585
[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 = getSiteKey() . getEncryptSeperator() . getDateKey();
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() . getDateKey() . getEncryptSeperator() . $a, getMasterSalt());
694
695                 // Create number from hash
696                 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getRandNo() - $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() . getDateKey() . getEncryptSeperator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
700
701                 // Create number from hash
702                 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
703         }
704
705         // At least 10 numbers shall be secure enought!
706         $len = getCodeLength();
707         if ($len == '0') {
708                 $len = $length;
709         } // END - if
710         if ($len == '0') {
711                 $len = 10;
712         } // END - if
713
714         // Cut off requested counts of number
715         $return = substr(str_replace('.', '', $rcode), 0, $len);
716
717         // Done building code
718         return $return;
719 }
720
721 // Does only allow numbers
722 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
723         // Filter all numbers out
724         $ret = preg_replace('/[^0123456789]/', '', $num);
725
726         // Shall we cast?
727         if ($castValue === true) {
728                 // Cast to biggest numeric type
729                 $ret = (double) $ret;
730         } // END - if
731
732         // Has the whole value changed?
733         if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true) && (!is_null($num))) {
734                 // Log the values
735                 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
736         } // END - if
737
738         // Return result
739         return $ret;
740 }
741
742 // Creates a Uni* timestamp from given selection data and prefix
743 function createTimestampFromSelections ($prefix, $postData) {
744         // Initial return value
745         $ret = '0';
746
747         // Do we have a leap year?
748         $SWITCH = '0';
749         $TEST = getYear() / 4;
750         $M1   = getMonth();
751
752         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
753         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02'))  $SWITCH = getOneDay();
754
755         // First add years...
756         $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
757
758         // Next months...
759         $ret += $postData[$prefix . '_mo'] * 2628000;
760
761         // Next weeks
762         $ret += $postData[$prefix . '_we'] * 604800;
763
764         // Next days...
765         $ret += $postData[$prefix . '_da'] * 86400;
766
767         // Next hours...
768         $ret += $postData[$prefix . '_ho'] * 3600;
769
770         // Next minutes..
771         $ret += $postData[$prefix . '_mi'] * 60;
772
773         // And at last seconds...
774         $ret += $postData[$prefix . '_se'];
775
776         // Return calculated value
777         return $ret;
778 }
779
780 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
781 function createFancyTime ($stamp) {
782         // Get data array with years/months/weeks/days/...
783         $data = createTimeSelections($stamp, '', '', '', true);
784         $ret = '';
785         foreach ($data as $k => $v) {
786                 if ($v > 0) {
787                         // Value is greater than 0 "eval" data to return string
788                         $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
789                         break;
790                 } // END - if
791         } // END - foreach
792
793         // Do we have something there?
794         if (strlen($ret) > 0) {
795                 // Remove leading commata and space
796                 $ret = substr($ret, 2);
797         } else {
798                 // Zero seconds
799                 $ret = '0 {--_SECONDS--}';
800         }
801
802         // Return fancy time string
803         return $ret;
804 }
805
806 // Extract host from script name
807 function extractHostnameFromUrl (&$script) {
808         // Use default SERVER_URL by default... ;) So?
809         $url = getServerUrl();
810
811         // Is this URL valid?
812         if (substr($script, 0, 7) == 'http://') {
813                 // Use the hostname from script URL as new hostname
814                 $url = substr($script, 7);
815                 $extract = explode('/', $url);
816                 $url = $extract[0];
817                 // Done extracting the URL :)
818         } // END - if
819
820         // Extract host name
821         $host = str_replace('http://', '', $url);
822         if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
823
824         // Generate relative URL
825         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
826         if (substr(strtolower($script), 0, 7) == 'http://') {
827                 // But only if http:// is in front!
828                 $script = substr($script, (strlen($url) + 7));
829         } elseif (substr(strtolower($script), 0, 8) == 'https://') {
830                 // Does this work?!
831                 $script = substr($script, (strlen($url) + 8));
832         }
833
834         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
835         if (substr($script, 0, 1) == '/') $script = substr($script, 1);
836
837         // Return host name
838         return $host;
839 }
840
841 // Send a GET request
842 function sendGetRequest ($script, $data = array()) {
843         // Extract host name from script
844         $host = extractHostnameFromUrl($script);
845
846         // Add data
847         $body = http_build_query($data, '', '&');
848
849         // There should be data, else we don't need to extend $script with $body
850         if (empty($body)) {
851                 // Do we have a question-mark in the script?
852                 if (strpos($script, '?') === false) {
853                         // No, so first char must be question mark
854                         $body = '?' . $body;
855                 } else {
856                         // Ok, add &
857                         $body = '&' . $body;
858                 }
859
860                 // Add script data
861                 $script .= $body;
862
863                 // Remove trailed & to make it more conform
864                 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
865         } // END - if
866
867         // Generate GET request header
868         $request  = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
869         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
870         $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
871         if (isConfigEntrySet('FULL_VERSION')) {
872                 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
873         } else {
874                 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
875         }
876         $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
877         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
878         $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
879         $request .= 'Connection: close' . getConfig('HTTP_EOL');
880         $request .= getConfig('HTTP_EOL');
881
882         // Send the raw request
883         $response = sendRawRequest($host, $request);
884
885         // Return the result to the caller function
886         return $response;
887 }
888
889 // Send a POST request
890 function sendPostRequest ($script, $postData) {
891         // Is postData an array?
892         if (!is_array($postData)) {
893                 // Abort here
894                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
895                 return array('', '', '');
896         } // END - if
897
898         // Extract host name from script
899         $host = extractHostnameFromUrl($script);
900
901         // Construct request body
902         $body = http_build_query($postData, '', '&');
903
904         // Generate POST request header
905         $request  = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
906         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
907         $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
908         $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
909         $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
910         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
911         $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
912         $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
913         $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
914         $request .= 'Connection: close' . getConfig('HTTP_EOL');
915         $request .= getConfig('HTTP_EOL');
916
917         // Add body
918         $request .= $body;
919
920         // Send the raw request
921         $response = sendRawRequest($host, $request);
922
923         // Return the result to the caller function
924         return $response;
925 }
926
927 // Sends a raw request to another host
928 function sendRawRequest ($host, $request) {
929         // Init errno and errdesc with 'all fine' values
930         $errno = '0'; $errdesc = '';
931
932         // Initialize array
933         $response = array('', '', '');
934
935         // Default is not to use proxy
936         $useProxy = false;
937
938         // Are proxy settins set?
939         if (isProxyUsed()) {
940                 // Then use it
941                 $useProxy = true;
942         } // END - if
943
944         // Load include
945         loadIncludeOnce('inc/classes/resolver.class.php');
946
947         // Get resolver instance
948         $resolver = new HostnameResolver();
949
950         // Open connection
951         //* DEBUG: */ die('SCRIPT=' . $script);
952         if ($useProxy === true) {
953                 // Resolve hostname into IP address
954                 $ip = $resolver->resolveHostname(compileRawCode(getProxyHost()));
955
956                 // Connect to host through proxy connection
957                 $fp = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
958         } else {
959                 // Resolve hostname into IP address
960                 $ip = $resolver->resolveHostname($host);
961
962                 // Connect to host directly
963                 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
964         }
965
966         // Is there a link?
967         if (!is_resource($fp)) {
968                 // Failed!
969                 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
970                 return $response;
971         } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
972                 // Cannot set non-blocking mode or timeout
973                 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
974                 return $response;
975         }
976
977         // Do we use proxy?
978         if ($useProxy === true) {
979                 // Setup proxy tunnel
980                 $response = setupProxyTunnel($host, $fp);
981
982                 // If the response is invalid, abort
983                 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
984                         // Invalid response!
985                         logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
986                         return $response;
987                 } // END - if
988         } // END - if
989
990         // Write request
991         fwrite($fp, $request);
992
993         // Start counting
994         $start = microtime(true);
995
996         // Read response
997         while (!feof($fp)) {
998                 // Get info from stream
999                 $info = stream_get_meta_data($fp);
1000
1001                 // Is it timed out? 15 seconds is a really patient...
1002                 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1003                         // Timeout
1004                         logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1005
1006                         // Abort here
1007                         break;
1008                 } // END - if
1009
1010                 // Get line from stream
1011                 $line = fgets($fp, 128);
1012
1013                 // Ignore empty lines because of non-blocking mode
1014                 if (empty($line)) {
1015                         // uslepp a little to avoid 100% CPU load
1016                         usleep(10);
1017
1018                         // Skip this
1019                         continue;
1020                 } // END - if
1021
1022                 // Add it to response
1023                 $response[] = trim($line);
1024         } // END - while
1025
1026         // Close socket
1027         fclose($fp);
1028
1029         // Time request if debug-mode is enabled
1030         if (isDebugModeEnabled()) {
1031                 // Add debug message...
1032                 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1033         } // END - if
1034
1035         // Skip first empty lines
1036         $resp = $response;
1037         foreach ($resp as $idx => $line) {
1038                 // Trim space away
1039                 $line = trim($line);
1040
1041                 // Is this line empty?
1042                 if (empty($line)) {
1043                         // Then remove it
1044                         array_shift($response);
1045                 } else {
1046                         // Abort on first non-empty line
1047                         break;
1048                 }
1049         } // END - foreach
1050
1051         //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1052         //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1053
1054         // Proxy agent found or something went wrong?
1055         if (!isset($response[0])) {
1056                 // No response, maybe timeout
1057                 $response = array('', '', '');
1058                 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1059         } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1060                 // Proxy header detected, so remove two lines
1061                 array_shift($response);
1062                 array_shift($response);
1063         } // END - if
1064
1065         // Was the request successfull?
1066         if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1067                 // Not found / access forbidden
1068                 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1069                 $response = array('', '', '');
1070         } // END - if
1071
1072         // Return response
1073         return $response;
1074 }
1075
1076 // Sets up a proxy tunnel for given hostname and through resource
1077 function setupProxyTunnel ($host, $resource) {
1078         // Initialize array
1079         $response = array('', '', '');
1080
1081         // Generate CONNECT request header
1082         $proxyTunnel  = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1083         $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1084
1085         // Use login data to proxy? (username at least!)
1086         if (getProxyUsername() != '') {
1087                 // Add it as well
1088                 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
1089                 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1090         } // END - if
1091
1092         // Add last new-line
1093         $proxyTunnel .= getConfig('HTTP_EOL');
1094         //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1095
1096         // Write request
1097         fwrite($fp, $proxyTunnel);
1098
1099         // Got response?
1100         if (feof($fp)) {
1101                 // No response received
1102                 return $response;
1103         } // END - if
1104
1105         // Read the first line
1106         $resp = trim(fgets($fp, 10240));
1107         $respArray = explode(' ', $resp);
1108         if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1109                 // Invalid response!
1110                 return $response;
1111         } // END - if
1112
1113         // All fine!
1114         return $respArray;
1115 }
1116
1117 // Taken from www.php.net isInStringIgnoreCase() user comments
1118 function isEmailValid ($email) {
1119         // Check first part of email address
1120         $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1121
1122         //  Check domain
1123         $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1124
1125         // Generate pattern
1126         $regex = '@^' . $first . '\@' . $domain . '$@iU';
1127
1128         // Return check result
1129         return preg_match($regex, $email);
1130 }
1131
1132 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1133 function isUrlValid ($URL, $compile=true) {
1134         // Trim URL a little
1135         $URL = trim(urldecode($URL));
1136         //* DEBUG: */ debugOutput($URL);
1137
1138         // Compile some chars out...
1139         if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1140         //* DEBUG: */ debugOutput($URL);
1141
1142         // Check for the extension filter
1143         if (isExtensionActive('filter')) {
1144                 // Use the extension's filter set
1145                 return FILTER_VALIDATE_URL($URL, false);
1146         } // END - if
1147
1148         // If not installed, perform a simple test. Just make it sure there is always a http:// or
1149         // https:// in front of the URLs
1150         return isUrlValidSimple($URL);
1151 }
1152
1153 // Generate a hash for extra-security for all passwords
1154 function generateHash ($plainText, $salt = '', $hash = true) {
1155         // Debug output
1156         //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
1157
1158         // Is the required extension 'sql_patches' there and a salt is not given?
1159         // 123                            4                      43    3     4     432    2                  3             32    2                             3                32    2      3     3      21
1160         if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
1161                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1162                 if ($hash === true) {
1163                         // Is plain password
1164                         return md5($plainText);
1165                 } else {
1166                         // Is already a hash
1167                         return $plainText;
1168                 }
1169         } // END - if
1170
1171         // Do we miss an arry element here?
1172         if (!isConfigEntrySet('file_hash')) {
1173                 // Stop here
1174                 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
1175         } // END - if
1176
1177         // When the salt is empty build a new one, else use the first x configured characters as the salt
1178         if (empty($salt)) {
1179                 // Build server string for more entropy
1180                 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
1181
1182                 // Build key string
1183                 $keys   = getSiteKey() . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
1184
1185                 // Additional data
1186                 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
1187
1188                 // Calculate number for generating the code
1189                 $a = time() + getConfig('_ADD') - 1;
1190
1191                 // Generate SHA1 sum from modula of number and the prime number
1192                 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a);
1193                 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
1194                 $sha1 = scrambleString($sha1);
1195                 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
1196                 //* DEBUG: */ $sha1b = descrambleString($sha1);
1197                 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
1198
1199                 // Generate the password salt string
1200                 $salt = substr($sha1, 0, getSaltLength());
1201                 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
1202         } else {
1203                 // Use given salt
1204                 //* DEBUG: */ debugOutput('salt=' . $salt);
1205                 $salt = substr($salt, 0, getSaltLength());
1206                 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
1207
1208                 // Sanity check on salt
1209                 if (strlen($salt) != getSaltLength()) {
1210                         // Not the same!
1211                         debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
1212                 } // END - if
1213         }
1214
1215         // Generate final hash (for debug output)
1216         $finalHash = $salt . sha1($salt . $plainText);
1217
1218         // Debug output
1219         //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
1220
1221         // Return hash
1222         return $finalHash;
1223 }
1224
1225 // Scramble a string
1226 function scrambleString ($str) {
1227         // Init
1228         $scrambled = '';
1229
1230         // Final check, in case of failture it will return unscrambled string
1231         if (strlen($str) > 40) {
1232                 // The string is to long
1233                 return $str;
1234         } elseif (strlen($str) == 40) {
1235                 // From database
1236                 $scrambleNums = explode(':', getPassScramble());
1237         } else {
1238                 // Generate new numbers
1239                 $scrambleNums = explode(':', genScrambleString(strlen($str)));
1240         }
1241
1242         // Compare both lengths and abort if different
1243         if (strlen($str) != count($scrambleNums)) return $str;
1244
1245         // Scramble string here
1246         //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
1247         for ($idx = 0; $idx < strlen($str); $idx++) {
1248                 // Get char on scrambled position
1249                 $char = substr($str, $scrambleNums[$idx], 1);
1250
1251                 // Add it to final output string
1252                 $scrambled .= $char;
1253         } // END - for
1254
1255         // Return scrambled string
1256         //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
1257         return $scrambled;
1258 }
1259
1260 // De-scramble a string scrambled by scrambleString()
1261 function descrambleString ($str) {
1262         // Scramble only 40 chars long strings
1263         if (strlen($str) != 40) return $str;
1264
1265         // Load numbers from config
1266         $scrambleNums = explode(':', getPassScramble());
1267
1268         // Validate numbers
1269         if (count($scrambleNums) != 40) return $str;
1270
1271         // Begin descrambling
1272         $orig = str_repeat(' ', 40);
1273         //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
1274         for ($idx = 0; $idx < 40; $idx++) {
1275                 $char = substr($str, $idx, 1);
1276                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1277         } // END - for
1278
1279         // Return scrambled string
1280         //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1281         return $orig;
1282 }
1283
1284 // Generated a "string" for scrambling
1285 function genScrambleString ($len) {
1286         // Prepare array for the numbers
1287         $scrambleNumbers = array();
1288
1289         // First we need to setup randomized numbers from 0 to 31
1290         for ($idx = 0; $idx < $len; $idx++) {
1291                 // Generate number
1292                 $rand = mt_rand(0, ($len - 1));
1293
1294                 // Check for it by creating more numbers
1295                 while (array_key_exists($rand, $scrambleNumbers)) {
1296                         $rand = mt_rand(0, ($len - 1));
1297                 } // END - while
1298
1299                 // Add number
1300                 $scrambleNumbers[$rand] = $rand;
1301         } // END - for
1302
1303         // So let's create the string for storing it in database
1304         $scrambleString = implode(':', $scrambleNumbers);
1305         return $scrambleString;
1306 }
1307
1308 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1309 function encodeHashForCookie ($passHash) {
1310         // Return vanilla password hash
1311         $ret = $passHash;
1312
1313         // Is a secret key and master salt already initialized?
1314         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1315         if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1316                 // Only calculate when the secret key is generated
1317                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1318                 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1319                         // Both keys must have same length so return unencrypted
1320                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1321                         return $ret;
1322                 } // END - if
1323
1324                 $newHash = ''; $start = 9;
1325                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1326                 for ($idx = 0; $idx < 20; $idx++) {
1327                         $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1328                         $part2 = hexdec(substr(getSecretKey(), $start, 2));
1329                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1330                         $mod = dechex($idx);
1331                         if ($part1 > $part2) {
1332                                 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1333                         } elseif ($part2 > $part1) {
1334                                 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1335                         }
1336                         $mod = substr($mod, 0, 2);
1337                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1338                         $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1339                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1340                         $start += 2;
1341                         $newHash .= $mod;
1342                 } // END - for
1343
1344                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1345                 $ret = generateHash($newHash, getMasterSalt());
1346         } // END - if
1347
1348         // Return result
1349         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1350         return $ret;
1351 }
1352
1353 // Fix "deleted" cookies
1354 function fixDeletedCookies ($cookies) {
1355         // Is this an array with entries?
1356         if ((is_array($cookies)) && (count($cookies) > 0)) {
1357                 // Then check all cookies if they are marked as deleted!
1358                 foreach ($cookies as $cookieName) {
1359                         // Is the cookie set to "deleted"?
1360                         if (getSession($cookieName) == 'deleted') {
1361                                 setSession($cookieName, '');
1362                         } // END - if
1363                 } // END - foreach
1364         } // END - if
1365 }
1366
1367 // Checks if a given apache module is loaded
1368 function isApacheModuleLoaded ($apacheModule) {
1369         // Check it and return result
1370         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1371 }
1372
1373 // Get current theme name
1374 function getCurrentTheme () {
1375         // The default theme is 'default'... ;-)
1376         $ret = 'default';
1377
1378         // Do we have ext-theme installed and active?
1379         if (isExtensionActive('theme')) {
1380                 // Call inner method
1381                 $ret = getActualTheme();
1382         } // END - if
1383
1384         // Return theme value
1385         return $ret;
1386 }
1387
1388 // Generates an error code from given account status
1389 function generateErrorCodeFromUserStatus ($status = '') {
1390         // If no status is provided, use the default, cached
1391         if ((empty($status)) && (isMember())) {
1392                 // Get user status
1393                 $status = getUserData('status');
1394         } // END - if
1395
1396         // Default error code if unknown account status
1397         $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1398
1399         // Generate constant name
1400         $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1401
1402         // Is the constant there?
1403         if (isCodeSet($codeName)) {
1404                 // Then get it!
1405                 $errorCode = getCode($codeName);
1406         } else {
1407                 // Unknown status
1408                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1409         }
1410
1411         // Return error code
1412         return $errorCode;
1413 }
1414
1415 // Back-ported from the new ship-simu engine. :-)
1416 function debug_get_printable_backtrace () {
1417         // Init variable
1418         $backtrace = '<ol>';
1419
1420         // Get and prepare backtrace for output
1421         $backtraceArray = debug_backtrace();
1422         foreach ($backtraceArray as $key => $trace) {
1423                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1424                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1425                 if (!isset($trace['args'])) $trace['args'] = array();
1426                 $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>';
1427         } // END - foreach
1428
1429         // Close it
1430         $backtrace .= '</ol>';
1431
1432         // Return the backtrace
1433         return $backtrace;
1434 }
1435
1436 // A mail-able backtrace
1437 function debug_get_mailable_backtrace () {
1438         // Init variable
1439         $backtrace = '';
1440
1441         // Get and prepare backtrace for output
1442         $backtraceArray = debug_backtrace();
1443         foreach ($backtraceArray as $key => $trace) {
1444                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1445                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1446                 if (!isset($trace['args'])) $trace['args'] = array();
1447                 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1448         } // END - foreach
1449
1450         // Return the backtrace
1451         return $backtrace;
1452 }
1453
1454 // Generates a ***weak*** seed
1455 function generateSeed () {
1456         return microtime(true) * 100000;
1457 }
1458
1459 // Converts a message code to a human-readable message
1460 function getMessageFromErrorCode ($code) {
1461         $message = '';
1462         switch ($code) {
1463                 case '': break;
1464                 case getCode('LOGOUT_DONE')        : $message = '{--LOGOUT_DONE--}'; break;
1465                 case getCode('LOGOUT_FAILED')      : $message = '<span class="notice">{--LOGOUT_FAILED--}</span>'; break;
1466                 case getCode('DATA_INVALID')       : $message = '{--MAIL_DATA_INVALID--}'; break;
1467                 case getCode('POSSIBLE_INVALID')   : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1468                 case getCode('USER_404')           : $message = '{--USER_404--}'; break;
1469                 case getCode('STATS_404')          : $message = '{--MAIL_STATS_404--}'; break;
1470                 case getCode('ALREADY_CONFIRMED')  : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1471                 case getCode('WRONG_PASS')         : $message = '{--LOGIN_WRONG_PASS--}'; break;
1472                 case getCode('WRONG_ID')           : $message = '{--LOGIN_WRONG_ID--}'; break;
1473                 case getCode('ACCOUNT_LOCKED')     : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1474                 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1475                 case getCode('COOKIES_DISABLED')   : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1476                 case getCode('BEG_SAME_AS_OWN')    : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1477                 case getCode('LOGIN_FAILED')       : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1478                 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1479                 case getCode('OVERLENGTH')         : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1480                 case getCode('URL_FOUND')          : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1481                 case getCode('SUBJECT_URL')        : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1482                 case getCode('BLIST_URL')          : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1483                 case getCode('NO_RECS_LEFT')       : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1484                 case getCode('INVALID_TAGS')       : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1485                 case getCode('MORE_POINTS')        : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1486                 case getCode('MORE_RECEIVERS1')    : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1487                 case getCode('MORE_RECEIVERS2')    : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1488                 case getCode('MORE_RECEIVERS3')    : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1489                 case getCode('INVALID_URL')        : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1490                 case getCode('NO_MAIL_TYPE')       : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1491                 case getCode('UNKNOWN_ERROR')      : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1492                 case getCode('UNKNOWN_STATUS')     : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1493                 case getCode('PROFILE_UPDATED')    : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1494
1495                 case getCode('ERROR_MAILID'):
1496                         if (isExtensionActive('mailid', true)) {
1497                                 $message = '{--ERROR_CONFIRMING_MAIL--}';
1498                         } else {
1499                                 $message = generateExtensionInactiveNotInstalledMessage('mailid');
1500                         }
1501                         break;
1502
1503                 case getCode('EXTENSION_PROBLEM'):
1504                         if (isGetRequestParameterSet('ext')) {
1505                                 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1506                         } else {
1507                                 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1508                         }
1509                         break;
1510
1511                 case getCode('URL_TIME_LOCK'):
1512                         // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1513                         $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1514                                 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1515
1516                         // Load timestamp from last order
1517                         $content = SQL_FETCHARRAY($result);
1518
1519                         // Free memory
1520                         SQL_FREERESULT($result);
1521
1522                         // Translate it for templates
1523                         $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1524
1525                         // Calculate hours...
1526                         $content['hours'] = round(getConfig('url_tlock') / 60 / 60);
1527
1528                         // Minutes...
1529                         $content['minutes'] = round((getConfig('url_tlock') - $content['hours'] * 60 * 60) / 60);
1530
1531                         // And seconds
1532                         $content['seconds'] = round(getConfig('url_tlock') - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1533
1534                         // Finally contruct the message
1535                         $message = loadTemplate('tlock_message', true, $content);
1536                         break;
1537
1538                 default:
1539                         // Missing/invalid code
1540                         $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1541
1542                         // Log it
1543                         logDebugMessage(__FUNCTION__, __LINE__, $message);
1544                         break;
1545         } // END - switch
1546
1547         // Return the message
1548         return $message;
1549 }
1550
1551 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1552 function isUrlValidSimple ($url) {
1553         // Prepare URL
1554         $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1555
1556         // Allows http and https
1557         $http      = "(http|https)+(:\/\/)";
1558         // Test domain
1559         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1560         // Test double-domains (e.g. .de.vu)
1561         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1562         // Test IP number
1563         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1564         // ... directory
1565         $dir       = "((/)+([-_\.[:alnum:]])+)*";
1566         // ... page
1567         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1568         // ... and the string after and including question character
1569         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1570         // Pattern for URLs like http://url/dir/doc.html?var=value
1571         $pattern['d1dpg1']  = $http . $domain1 . $dir . $page . $getstring1;
1572         $pattern['d2dpg1']  = $http . $domain2 . $dir . $page . $getstring1;
1573         $pattern['ipdpg1']  = $http . $ip . $dir . $page . $getstring1;
1574         // Pattern for URLs like http://url/dir/?var=value
1575         $pattern['d1dg1']  = $http . $domain1 . $dir.'/' . $getstring1;
1576         $pattern['d2dg1']  = $http . $domain2 . $dir.'/' . $getstring1;
1577         $pattern['ipdg1']  = $http . $ip . $dir.'/' . $getstring1;
1578         // Pattern for URLs like http://url/dir/page.ext
1579         $pattern['d1dp']  = $http . $domain1 . $dir . $page;
1580         $pattern['d1dp']  = $http . $domain2 . $dir . $page;
1581         $pattern['ipdp']  = $http . $ip . $dir . $page;
1582         // Pattern for URLs like http://url/dir
1583         $pattern['d1d']  = $http . $domain1 . $dir;
1584         $pattern['d2d']  = $http . $domain2 . $dir;
1585         $pattern['ipd']  = $http . $ip . $dir;
1586         // Pattern for URLs like http://url/?var=value
1587         $pattern['d1g1']  = $http . $domain1 . '/' . $getstring1;
1588         $pattern['d2g1']  = $http . $domain2 . '/' . $getstring1;
1589         $pattern['ipg1']  = $http . $ip . '/' . $getstring1;
1590         // Pattern for URLs like http://url?var=value
1591         $pattern['d1g12']  = $http . $domain1 . $getstring1;
1592         $pattern['d2g12']  = $http . $domain2 . $getstring1;
1593         $pattern['ipg12']  = $http . $ip . $getstring1;
1594
1595         // Test all patterns
1596         $reg = false;
1597         foreach ($pattern as $key => $pat) {
1598                 // Debug regex?
1599                 if (isDebugRegularExpressionEnabled()) {
1600                         // @TODO Are these convertions still required?
1601                         $pat = str_replace('.', '&#92;&#46;', $pat);
1602                         $pat = str_replace('@', '&#92;&#64;', $pat);
1603                         //* DEBUG: */ debugOutput($key . '=&nbsp;' . $pat);
1604                 } // END - if
1605
1606                 // Check if expression matches
1607                 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1608
1609                 // Does it match?
1610                 if ($reg === true) break;
1611         }
1612
1613         // Return true/false
1614         return $reg;
1615 }
1616
1617 // Wtites data to a config.php-style file
1618 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1619 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1620         // Initialize some variables
1621         $done = false;
1622         $seek++;
1623         $next  = -1;
1624         $found = false;
1625
1626         // Is the file there and read-/write-able?
1627         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1628                 $search = 'CFG: ' . $comment;
1629                 $tmp = $FQFN . '.tmp';
1630
1631                 // Open the source file
1632                 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1633
1634                 // Is the resource valid?
1635                 if (is_resource($fp)) {
1636                         // Open temporary file
1637                         $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1638
1639                         // Is the resource again valid?
1640                         if (is_resource($fp_tmp)) {
1641                                 // Mark temporary file as readable
1642                                 $GLOBALS['file_readable'][$tmp] = true;
1643
1644                                 // Start reading
1645                                 while (!feof($fp)) {
1646                                         // Read from source file
1647                                         $line = fgets ($fp, 1024);
1648
1649                                         if (strpos($line, $search) > -1) { 
1650                                                 $next = '0';
1651                                                 $found = true;
1652                                         } // END - if
1653
1654                                         if ($next > -1) {
1655                                                 if ($next === $seek) {
1656                                                         $next = -1;
1657                                                         $line = $prefix . $DATA . $suffix . "\n";
1658                                                 } else {
1659                                                         $next++;
1660                                                 }
1661                                         } // END - if
1662
1663                                         // Write to temp file
1664                                         fwrite($fp_tmp, $line);
1665                                 } // END - while
1666
1667                                 // Close temp file
1668                                 fclose($fp_tmp);
1669
1670                                 // Finished writing tmp file
1671                                 $done = true;
1672                         } // END - if
1673
1674                         // Close source file
1675                         fclose($fp);
1676
1677                         if (($done === true) && ($found === true)) {
1678                                 // Copy back tmp file and delete tmp :-)
1679                                 copyFileVerified($tmp, $FQFN, 0644);
1680                                 return removeFile($tmp);
1681                         } elseif ($found === false) {
1682                                 outputHtml('<strong>CHANGE:</strong> 404!');
1683                         } else {
1684                                 outputHtml('<strong>TMP:</strong> UNDONE!');
1685                         }
1686                 }
1687         } else {
1688                 // File not found, not readable or writeable
1689                 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1690         }
1691
1692         // An error was detected!
1693         return false;
1694 }
1695
1696 // Send notification to admin
1697 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = '0') {
1698         if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1699                 // Send new way
1700                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName);
1701                 sendAdminsEmails($subject, $templateName, $content, $userid);
1702         } else {
1703                 // Send out-dated way
1704                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName);
1705                 $message = loadEmailTemplate($templateName, $content, $userid);
1706                 sendAdminEmails($subject, $message);
1707         }
1708 }
1709
1710 // Debug message logger
1711 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1712         // Is debug mode enabled?
1713         if ((isDebugModeEnabled()) || ($force === true)) {
1714                 // Remove CRLF
1715                 $message = str_replace("\r", '', str_replace("\n", '', $message));
1716
1717                 // Log this message away
1718                 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1719         } // END - if
1720 }
1721
1722 // Handle extra values
1723 function handleExtraValues ($filterFunction, $value, $extraValue) {
1724         // Default is the value itself
1725         $ret = $value;
1726
1727         // Do we have a special filter function?
1728         if (!empty($filterFunction)) {
1729                 // Does the filter function exist?
1730                 if (function_exists($filterFunction)) {
1731                         // Do we have extra parameters here?
1732                         if (!empty($extraValue)) {
1733                                 // Put both parameters in one new array by default
1734                                 $args = array($value, $extraValue);
1735
1736                                 // If we have an array simply use it and pre-extend it with our value
1737                                 if (is_array($extraValue)) {
1738                                         // Make the new args array
1739                                         $args = merge_array(array($value), $extraValue);
1740                                 } // END - if
1741
1742                                 // Call the multi-parameter call-back
1743                                 $ret = call_user_func_array($filterFunction, $args);
1744                         } else {
1745                                 // One parameter call
1746                                 $ret = call_user_func($filterFunction, $value);
1747                         }
1748                 } // END - if
1749         } // END - if
1750
1751         // Return the value
1752         return $ret;
1753 }
1754
1755 // Converts timestamp selections into a timestamp
1756 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1757         // Init test variable
1758         $skip  = false;
1759         $test2 = '';
1760
1761         // Get last three chars
1762         $test = substr($id, -3);
1763
1764         // Improved way of checking! :-)
1765         if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1766                 // Found a multi-selection for timings?
1767                 $test = substr($id, 0, -3);
1768                 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)) {
1769                         // Generate timestamp
1770                         $postData[$test] = createTimestampFromSelections($test, $postData);
1771                         $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1772                         $GLOBALS['skip_config'][$test] = true;
1773
1774                         // Remove data from array
1775                         foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1776                                 unset($postData[$test . '_' . $rem]);
1777                         } // END - foreach
1778
1779                         // Skip adding
1780                         unset($id);
1781                         $skip = true;
1782                         $test2 = $test;
1783                 } // END - if
1784         } // END - if
1785 }
1786
1787 // Reverts the german decimal comma into Computer decimal dot
1788 function convertCommaToDot ($str) {
1789         // Default float is not a float... ;-)
1790         $float = false;
1791
1792         // Which language is selected?
1793         switch (getLanguage()) {
1794                 case 'de': // German language
1795                         // Remove german thousand dots first
1796                         $str = str_replace('.', '', $str);
1797
1798                         // Replace german commata with decimal dot and cast it
1799                         $float = (float)str_replace(',', '.', $str);
1800                         break;
1801
1802                 default: // US and so on
1803                         // Remove thousand dots first and cast
1804                         $float = (float)str_replace(',', '', $str);
1805                         break;
1806         }
1807
1808         // Return float
1809         return $float;
1810 }
1811
1812 // Handle menu-depending failed logins and return the rendered content
1813 function handleLoginFailures ($accessLevel) {
1814         // Default output is empty ;-)
1815         $OUT = '';
1816
1817         // Is the session data set?
1818         if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1819                 // Ignore zero values
1820                 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1821                         // Non-guest has login failures found, get both data and prepare it for template
1822                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1823                         $content = array(
1824                                 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1825                                 'last_failure'   => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1826                         );
1827
1828                         // Load template
1829                         $OUT = loadTemplate('login_failures', true, $content);
1830                 } // END - if
1831
1832                 // Reset session data
1833                 setSession('mailer_' . $accessLevel . '_failures', '');
1834                 setSession('mailer_' . $accessLevel . '_last_failure', '');
1835         } // END - if
1836
1837         // Return rendered content
1838         return $OUT;
1839 }
1840
1841 // Rebuild cache
1842 function rebuildCache ($cache, $inc = '', $force = false) {
1843         // Debug message
1844         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1845
1846         // Shall I remove the cache file?
1847         if (isCacheInstanceValid()) {
1848                 // Rebuild cache
1849                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1850                         // Destroy it
1851                         $GLOBALS['cache_instance']->removeCacheFile($force);
1852                 } // END - if
1853
1854                 // Include file given?
1855                 if (!empty($inc)) {
1856                         // Construct FQFN
1857                         $inc = sprintf("inc/loader/load-%s.php", $inc);
1858
1859                         // Is the include there?
1860                         if (isIncludeReadable($inc)) {
1861                                 // And rebuild it from scratch
1862                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1863                                 loadInclude($inc);
1864                         } else {
1865                                 // Include not found
1866                                 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1867                         }
1868                 } // END - if
1869         } // END - if
1870 }
1871
1872 // Determines the real remote address
1873 function determineRealRemoteAddress ($remoteAddr = false) {
1874         // Is a proxy in use?
1875         if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1876                 // Proxy was used
1877                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1878         } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1879                 // Yet, another proxy
1880                 $address = $_SERVER['HTTP_CLIENT_IP'];
1881         } else {
1882                 // The regular address when no proxy was used
1883                 $address = $_SERVER['REMOTE_ADDR'];
1884         }
1885
1886         // This strips out the real address from proxy output
1887         if (strstr($address, ',')) {
1888                 $addressArray = explode(',', $address);
1889                 $address = $addressArray[0];
1890         } // END - if
1891
1892         // Return the result
1893         return $address;
1894 }
1895
1896 // Adds a bonus mail to the queue
1897 // This is a high-level function!
1898 function addNewBonusMail ($data, $mode = '', $output = true) {
1899         // Use mode from data if not set and availble ;-)
1900         if ((empty($mode)) && (isset($data['mode']))) {
1901                 $mode = $data['mode'];
1902         } // END - if
1903
1904         // Generate receiver list
1905         $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1906
1907         // Receivers added?
1908         if (!empty($receiver)) {
1909                 // Add bonus mail to queue
1910                 addBonusMailToQueue(
1911                         $data['subject'],
1912                         $data['text'],
1913                         $receiver,
1914                         $data['points'],
1915                         $data['seconds'],
1916                         $data['url'],
1917                         $data['cat'],
1918                         $mode,
1919                         $data['receiver']
1920                 );
1921
1922                 // Mail inserted into bonus pool
1923                 if ($output === true) {
1924                         loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
1925                 } // END - if
1926         } elseif ($output === true) {
1927                 // More entered than can be reached!
1928                 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
1929         } else {
1930                 // Debug log
1931                 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1932         }
1933 }
1934
1935 // Determines referal id and sets it
1936 function determineReferalId () {
1937         // Skip this in non-html-mode and outside ref.php
1938         if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) {
1939                 return false;
1940         } // END - if
1941
1942         // Check if refid is set
1943         if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1944                 // This is fine...
1945         } elseif (isPostRequestParameterSet('refid')) {
1946                 // Get referal id from POST element refid
1947                 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1948         } elseif (isGetRequestParameterSet('refid')) {
1949                 // Get referal id from GET parameter refid
1950                 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1951         } elseif (isGetRequestParameterSet('ref')) {
1952                 // Set refid=ref (the referal link uses such variable)
1953                 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1954         } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1955                 // The variable user comes from  click.php
1956                 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1957         } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1958                 // Set session refid als global
1959                 $GLOBALS['refid'] = bigintval(getSession('refid'));
1960         } elseif (isRandomReferalIdEnabled()) {
1961                 // Select a random user which has confirmed enougth mails
1962                 $GLOBALS['refid'] = determineRandomReferalId();
1963         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
1964                 // Set default refid as refid in URL
1965                 $GLOBALS['refid'] = getDefRefid();
1966         } else {
1967                 // No default id when sql_patches is not installed or none set
1968                 $GLOBALS['refid'] = null;
1969         }
1970
1971         // Set cookie when default refid > 0
1972         if (!isSessionVariableSet('refid') || (isValidUserId($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
1973                 // Default is not found
1974                 $found = false;
1975
1976                 // Do we have nickname or userid set?
1977                 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1978                         // Nickname in URL, so load the id
1979                         $found = fetchUserData($GLOBALS['refid'], 'nickname');
1980                 } elseif (isValidUserId($GLOBALS['refid'])) {
1981                         // Direct userid entered
1982                         $found = fetchUserData($GLOBALS['refid']);
1983                 }
1984
1985                 // Is the record valid?
1986                 if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
1987                         // No, then reset referal id
1988                         $GLOBALS['refid'] = getDefRefid();
1989                 } // END - if
1990
1991                 // Set cookie
1992                 setSession('refid', $GLOBALS['refid']);
1993         } // END - if
1994
1995         // Return determined refid
1996         return $GLOBALS['refid'];
1997 }
1998
1999 // Enables the reset mode and runs it
2000 function doReset () {
2001         // Enable the reset mode
2002         $GLOBALS['reset_enabled'] = true;
2003
2004         // Run filters
2005         runFilterChain('reset');
2006 }
2007
2008 // Enables the reset mode (hourly, weekly and monthly) and runs it
2009 function doHourly () {
2010         // Enable the hourly reset mode
2011         $GLOBALS['hourly_enabled'] = true;
2012
2013         // Run filters (one always!)
2014         runFilterChain('hourly');
2015 }
2016
2017 // Our shutdown-function
2018 function shutdown () {
2019         // Call the filter chain 'shutdown'
2020         runFilterChain('shutdown', null);
2021
2022         // Check if not in installation phase and the link is up
2023         if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
2024                 // Close link
2025                 SQL_CLOSE(__FUNCTION__, __LINE__);
2026         } elseif (!isInstallationPhase()) {
2027                 // No database link
2028                 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
2029         }
2030
2031         // Stop executing here
2032         exit;
2033 }
2034
2035 // Init member id
2036 function initMemberId () {
2037         $GLOBALS['member_id'] = '0';
2038 }
2039
2040 // Setter for member id
2041 function setMemberId ($memberid) {
2042         // We should not set member id to zero
2043         if ($memberid == '0') {
2044                 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
2045         } // END - if
2046
2047         // Set it secured
2048         $GLOBALS['member_id'] = bigintval($memberid);
2049 }
2050
2051 // Getter for member id or returns zero
2052 function getMemberId () {
2053         // Default member id
2054         $memberid = '0';
2055
2056         // Is the member id set?
2057         if (isMemberIdSet()) {
2058                 // Then use it
2059                 $memberid = $GLOBALS['member_id'];
2060         } // END - if
2061
2062         // Return it
2063         return $memberid;
2064 }
2065
2066 // Checks ether the member id is set
2067 function isMemberIdSet () {
2068         return (isset($GLOBALS['member_id']));
2069 }
2070
2071 // Setter for extra title
2072 function setExtraTitle ($extraTitle) {
2073         $GLOBALS['extra_title'] = $extraTitle;
2074 }
2075
2076 // Getter for extra title
2077 function getExtraTitle () {
2078         // Is the extra title set?
2079         if (!isExtraTitleSet()) {
2080                 // No, then abort here
2081                 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
2082         } // END - if
2083
2084         // Return it
2085         return $GLOBALS['extra_title'];
2086 }
2087
2088 // Checks if the extra title is set
2089 function isExtraTitleSet () {
2090         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
2091 }
2092
2093 // Reads a directory recursively by default and searches for files not matching
2094 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
2095 // a whole directory.
2096 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
2097         // Add default entries we should exclude
2098         $excludeArray[] = '.';
2099         $excludeArray[] = '..';
2100         $excludeArray[] = '.svn';
2101         $excludeArray[] = '.htaccess';
2102
2103         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
2104         // Init includes
2105         $files = array();
2106
2107         // Open directory
2108         $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
2109
2110         // Read all entries
2111         while ($baseFile = readdir($dirPointer)) {
2112                 // Exclude '.', '..' and entries in $excludeArray automatically
2113                 if (in_array($baseFile, $excludeArray, true))  {
2114                         // Exclude them
2115                         //* DEBUG: */ debugOutput('excluded=' . $baseFile);
2116                         continue;
2117                 } // END - if
2118
2119                 // Construct include filename and FQFN
2120                 $fileName = $baseDir . $baseFile;
2121                 $FQFN = getPath() . $fileName;
2122
2123                 // Remove double slashes
2124                 $FQFN = str_replace('//', '/', $FQFN);
2125
2126                 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
2127                 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
2128                         // These Lines are only for debugging!!
2129                         //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
2130                         //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
2131                         //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
2132
2133                         // Exclude this one
2134                         continue;
2135                 } // END - if
2136
2137                 // Skip also files with non-matching prefix genericly
2138                 if (($recursive === true) && (isDirectory($FQFN))) {
2139                         // Is a redirectory so read it as well
2140                         $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
2141
2142                         // And skip further processing
2143                         continue;
2144                 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
2145                         // Skip this file
2146                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
2147                         continue;
2148                 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
2149                         // Skip wrong suffix as well
2150                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
2151                         continue;
2152                 } elseif (!isFileReadable($FQFN)) {
2153                         // Not readable so skip it
2154                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
2155                         continue;
2156                 }
2157
2158                 // Get file' extension (last 4 chars)
2159                 $fileExtension = substr($baseFile, -4, 4);
2160
2161                 // Is the file a PHP script or other?
2162                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
2163                 if (($fileExtension == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
2164                         // Is this a valid include file?
2165                         if ($extension == '.php') {
2166                                 // Remove both for extension name
2167                                 $extName = substr($baseFile, strlen($prefix), -4);
2168
2169                                 // Add file with or without base path
2170                                 if ($addBaseDir === true) {
2171                                         // With base path
2172                                         $files[] = $fileName;
2173                                 } else {
2174                                         // No base path
2175                                         $files[] = $baseFile;
2176                                 }
2177                         } else {
2178                                 // We found .php file but should not search for them, why?
2179                                 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
2180                         }
2181                 } elseif ($fileExtension == $extension) {
2182                         // Other, generic file found
2183                         $files[] = $fileName;
2184                 }
2185         } // END - while
2186
2187         // Close directory
2188         closedir($dirPointer);
2189
2190         // Sort array
2191         sort($files);
2192
2193         // Return array with include files
2194         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
2195         return $files;
2196 }
2197
2198 // Checks wether $prefix is found in $fileName
2199 function isFilePrefixFound ($fileName, $prefix) {
2200         // @TODO Find a way to cache this
2201         return (substr($fileName, 0, strlen($prefix)) == $prefix);
2202 }
2203
2204 // Maps a module name into a database table name
2205 function mapModuleToTable ($moduleName) {
2206         // Map only these, still lame code...
2207         switch ($moduleName) {
2208                 // 'index' is the guest's menu
2209                 case 'index': $moduleName = 'guest';  break;
2210                 // ... and 'login' the member's menu
2211                 case 'login': $moduleName = 'member'; break;
2212                 // Anything else will not be mapped, silently.
2213         } // END - switch
2214
2215         // Return result
2216         return $moduleName;
2217 }
2218
2219 // Add SQL debug data to array for later output
2220 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
2221         // Do we have cache?
2222         if (!isset($GLOBALS['debug_sql_available'])) {
2223                 // Check it and cache it in $GLOBALS
2224                 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
2225         } // END - if
2226         
2227         // Don't execute anything here if we don't need or ext-other is missing
2228         if ($GLOBALS['debug_sql_available'] === false) {
2229                 return;
2230         } // END - if
2231
2232         // Already executed?
2233         if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
2234                 // Then abort here, we don't need to profile a query twice
2235                 return;
2236         } // END - if
2237
2238         // Remeber this as profiled (or not, but we don't care here)
2239         $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
2240
2241         // Generate record
2242         $record = array(
2243                 'num_rows' => SQL_NUMROWS($result),
2244                 'affected' => SQL_AFFECTEDROWS(),
2245                 'sql_str'  => $sqlString,
2246                 'timing'   => $timing,
2247                 'file'     => basename($F),
2248                 'line'     => $L
2249         );
2250
2251         // Add it
2252         $GLOBALS['debug_sqls'][] = $record;
2253 }
2254
2255 // Initializes the cache instance
2256 function initCacheInstance () {
2257         // Check for double-initialization
2258         if (isset($GLOBALS['cache_instance'])) {
2259                 // This should not happen and must be fixed
2260                 debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
2261         } // END - if
2262
2263         // Load include for CacheSystem class
2264         loadIncludeOnce('inc/classes/cachesystem.class.php');
2265
2266         // Initialize cache system only when it's needed
2267         $GLOBALS['cache_instance'] = new CacheSystem();
2268
2269         // Did it work?
2270         if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
2271                 // Failed to initialize cache sustem
2272                 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2273         } // END - if
2274 }
2275
2276 // Getter for message from array or raw message
2277 function getMessageFromIndexedArray ($message, $pos, $array) {
2278         // Check if the requested message was found in array
2279         if (isset($array[$pos])) {
2280                 // ... if yes then use it!
2281                 $ret = $array[$pos];
2282         } else {
2283                 // ... else use default message
2284                 $ret = $message;
2285         }
2286
2287         // Return result
2288         return $ret;
2289 }
2290
2291 // Convert ';' to ', ' for e.g. receiver list
2292 function convertReceivers ($old) {
2293         return str_replace(';', ', ', $old);
2294 }
2295
2296 // Get a module from filename and access level
2297 function getModuleFromFileName ($file, $accessLevel) {
2298         // Default is 'invalid';
2299         $modCheck = 'invalid';
2300
2301         // @TODO This is still very static, rewrite it somehow
2302         switch ($accessLevel) {
2303                 case 'admin':
2304                         $modCheck = 'admin';
2305                         break;
2306
2307                 case 'sponsor':
2308                 case 'guest':
2309                 case 'member':
2310                         $modCheck = getModule();
2311                         break;
2312
2313                 default: // Unsupported file name / access level
2314                         debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2315                         break;
2316         }
2317
2318         // Return result
2319         return $modCheck;
2320 }
2321
2322 // Encodes an URL for adding session id, etc.
2323 function encodeUrl ($url, $outputMode = '0') {
2324         // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2325         if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) {
2326                 // Raw output mode detected or session_name() found in URL
2327                 return $url;
2328         } // END - if
2329
2330         // Do we have a valid session?
2331         if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2332                 // Invalid session
2333                 // Determine right seperator
2334                 $seperator = '&amp;';
2335                 if (strpos($url, '?') === false) {
2336                         // No question mark
2337                         $seperator = '?';
2338                 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2339                         // Non-HTML mode (or forced non-HTML mode
2340                         $seperator = '&';
2341                 }
2342
2343                 // Add it to URL
2344                 if (session_id() != '') {
2345                         $url .= $seperator . session_name() . '=' . session_id();
2346                 } // END - if
2347         } // END - if
2348
2349         // Add {?URL?} ?
2350         if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2351                 // Add it
2352                 $url = '{?URL?}/' . $url;
2353         } // END - if
2354
2355         // Return the URL
2356         return $url;
2357 }
2358
2359 // Simple check for spider
2360 function isSpider () {
2361         // Get the UA and trim it down
2362         $userAgent = trim(strtolower(detectUserAgent(true)));
2363
2364         // It should not be empty, if so it is better a spider/bot
2365         if (empty($userAgent)) {
2366                 // It is a spider/bot
2367                 return true;
2368         } // END - if
2369
2370         // Is it a spider?
2371         return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2372 }
2373
2374 // Function to search for the last modified file
2375 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2376         // Get dir as array
2377         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2378         // Does it match what we are looking for? (We skip a lot files already!)
2379         // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
2380         $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2381
2382         $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2383         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2384
2385         // Walk through all entries
2386         foreach ($ds as $d) {
2387                 // Generate proper FQFN
2388                 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2389
2390                 // Is it a file and readable?
2391                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2392                 if (isFileReadable($FQFN)) {
2393                         // $FQFN is a readable file so extract the requested data from it
2394                         $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2395                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2396
2397                         // Is the file more recent?
2398                         if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2399                                 // This file is newer as the file before
2400                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2401                                 $last_changed['path_name'] = $FQFN;
2402                                 $last_changed[$lookFor] = $check;
2403                         } // END - if
2404                 } else {
2405                         // Not readable
2406                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2407                 }
2408         } // END - foreach
2409 }
2410
2411 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2412 function handleFieldWithBraces ($field) {
2413         // Are there braces [] at the end?
2414         if (substr($field, -2, 2) == '[]') {
2415                 // Try to find one and replace it. I do it this way to allow easy
2416                 // extending of this code.
2417                 foreach (array('admin_list_builder_id_value') as $key) {
2418                         // Is the cache entry set?
2419                         if (isset($GLOBALS[$key])) {
2420                                 // Insert it
2421                                 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2422
2423                                 // And abort
2424                                 break;
2425                         } // END - if
2426                 } // END - foreach
2427         } // END - if
2428
2429         // Return it
2430         return $field;
2431 }
2432
2433 // Converts a userid so it can be used in SQL queries
2434 function makeDatabaseUserId ($userid) {
2435         // Is it a valid username?
2436         if (isValidUserId($userid)) {
2437                 // Always secure it
2438                 $userid = bigintval($userid);
2439         } else {
2440                 // Is not valid or zero
2441                 $userid = 'NULL';
2442         }
2443
2444         // Return it
2445         return $userid;
2446 }
2447
2448 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2449 // Note: This function is cached
2450 function capitalizeUnderscoreString ($str) {
2451         // Do we have cache?
2452         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2453                 // Init target string
2454                 $capitalized = '';
2455
2456                 // Explode it with the underscore, but rewrite dashes to underscore before
2457                 $strArray = explode('_', str_replace('-', '_', $str));
2458
2459                 // "Walk" through all elements and make them lower-case but first upper-case
2460                 foreach ($strArray as $part) {
2461                         // Capitalize the string part
2462                         $capitalized .= firstCharUpperCase($part);
2463                 } // END - foreach
2464
2465                 // Store the converted string in cache array
2466                 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2467         } // END - if
2468
2469         // Return cache
2470         return $GLOBALS[__FUNCTION__][$str];
2471 }
2472
2473 // Generate admin links for mail order
2474 // mailType can be: 'mid' or 'bid'
2475 function generateAdminMailLinks ($mailType, $mailId) {
2476         // Init variables
2477         $OUT = '';
2478         $table = '';
2479
2480         // Default column for mail status is 'data_type'
2481         // @TODO Rename column data_type to e.g. mail_status
2482         $statusColumn = 'data_type';
2483
2484         // Which mail do we have?
2485         switch ($mailType) {
2486                 case 'bid': // Bonus mail
2487                         $table = 'bonus';
2488                         break;
2489
2490                 case 'mid': // Member mail
2491                         $table = 'pool';
2492                         break;
2493
2494                 default: // Handle unsupported types
2495                         logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2496                         $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2497                         break;
2498         } // END - switch
2499
2500         // Is the mail type supported?
2501         if (!empty($table)) {
2502                 // Query for the mail
2503                 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2504                         array($statusColumn, $table, bigintval($mailId)), __FILE__, __LINE__);
2505
2506                 // Do we have one entry there?
2507                 if (SQL_NUMROWS($result) == 1) {
2508                         // Load the entry
2509                         $content = SQL_FETCHARRAY($result);
2510                         die('<pre>'.print_r($content, true).'</pre>');
2511                 } // END - if
2512
2513                 // Free result
2514                 SQL_FREERESULT($result);
2515         } // END - if
2516
2517         // Return generated HTML code
2518         return $OUT;
2519 }
2520
2521 //-----------------------------------------------------------------------------
2522 // Automatically re-created functions, all taken from user comments on www.php.net
2523 //-----------------------------------------------------------------------------
2524 //
2525 if (!function_exists('html_entity_decode')) {
2526         // Taken from documentation on www.php.net
2527         function html_entity_decode ($string) {
2528                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2529                 $trans_tbl = array_flip($trans_tbl);
2530                 return strtr($string, $trans_tbl);
2531         }
2532 } // END - if
2533
2534 if (!function_exists('http_build_query')) {
2535         // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
2536         function http_build_query($data, $prefix = '', $sep = '', $key = '') {
2537                 $ret = array();
2538                 foreach ((array) $data as $k => $v) {
2539                         if (is_int($k) && $prefix != null) {
2540                                 $k = urlencode($prefix . $k);
2541                         } // END - if
2542
2543                         if ((!empty($key)) || ($key === 0))  $k = $key . '[' . urlencode($k) . ']';
2544
2545                         if (is_array($v) || is_object($v)) {
2546                                 array_push($ret, http_build_query($v, '', $sep, $k));
2547                         } else {
2548                                 array_push($ret, $k.'='.urlencode($v));
2549                         }
2550                 } // END - foreach
2551
2552                 if (empty($sep)) $sep = ini_get('arg_separator.output');
2553
2554                 return implode($sep, $ret);
2555         }
2556 } // END - if
2557
2558 // [EOF]
2559 ?>