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