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