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