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