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