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