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