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