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