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