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