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