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