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