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