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