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