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