]> git.mxchange.org Git - mailer.git/blob - inc/functions.php
bc397426cfbe564414d6b866e518e24d5fa68bff
[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 createTimestampFromSelections ($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'))  $SWITCH = getOneDay();
731
732         // First add years...
733         $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
734
735         // Next months...
736         $ret += $postData[$prefix . '_mo'] * 2628000;
737
738         // Next weeks
739         $ret += $postData[$prefix . '_we'] * 604800;
740
741         // Next days...
742         $ret += $postData[$prefix . '_da'] * 86400;
743
744         // Next hours...
745         $ret += $postData[$prefix . '_ho'] * 3600;
746
747         // Next minutes..
748         $ret += $postData[$prefix . '_mi'] * 60;
749
750         // And at last seconds...
751         $ret += $postData[$prefix . '_se'];
752
753         // Return calculated value
754         return $ret;
755 }
756
757 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
758 function createFancyTime ($stamp) {
759         // Get data array with years/months/weeks/days/...
760         $data = createTimeSelections($stamp, '', '', '', true);
761         $ret = '';
762         foreach ($data as $k => $v) {
763                 if ($v > 0) {
764                         // Value is greater than 0 "eval" data to return string
765                         $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
766                         break;
767                 } // END - if
768         } // END - foreach
769
770         // Do we have something there?
771         if (strlen($ret) > 0) {
772                 // Remove leading commata and space
773                 $ret = substr($ret, 2);
774         } else {
775                 // Zero seconds
776                 $ret = '0 {--_SECONDS--}';
777         }
778
779         // Return fancy time string
780         return $ret;
781 }
782
783 // Extract host from script name
784 function extractHostnameFromUrl (&$script) {
785         // Use default SERVER_URL by default... ;) So?
786         $url = getServerUrl();
787
788         // Is this URL valid?
789         if (substr($script, 0, 7) == 'http://') {
790                 // Use the hostname from script URL as new hostname
791                 $url = substr($script, 7);
792                 $extract = explode('/', $url);
793                 $url = $extract[0];
794                 // Done extracting the URL :)
795         } // END - if
796
797         // Extract host name
798         $host = str_replace('http://', '', $url);
799         if (isInString('/', $host)) {
800                 $host = substr($host, 0, strpos($host, '/'));
801         } // END - if
802
803         // Generate relative URL
804         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
805         if (substr(strtolower($script), 0, 7) == 'http://') {
806                 // But only if http:// is in front!
807                 $script = substr($script, (strlen($url) + 7));
808         } elseif (substr(strtolower($script), 0, 8) == 'https://') {
809                 // Does this work?!
810                 $script = substr($script, (strlen($url) + 8));
811         }
812
813         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
814         if (substr($script, 0, 1) == '/') {
815                 $script = substr($script, 1);
816         } // END - if
817
818         // Return host name
819         return $host;
820 }
821
822 // Taken from www.php.net isInStringIgnoreCase() user comments
823 function isEmailValid ($email) {
824         // Check first part of email address
825         $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
826
827         //  Check domain
828         $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
829
830         // Generate pattern
831         $regex = '@^' . $first . '\@' . $domain . '$@iU';
832
833         // Return check result
834         return preg_match($regex, $email);
835 }
836
837 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
838 function isUrlValid ($URL, $compile=true) {
839         // Trim URL a little
840         $URL = trim(urldecode($URL));
841         //* DEBUG: */ debugOutput($URL);
842
843         // Compile some chars out...
844         if ($compile === true) $URL = compileUriCode($URL, false, false, false);
845         //* DEBUG: */ debugOutput($URL);
846
847         // Check for the extension filter
848         if (isExtensionActive('filter')) {
849                 // Use the extension's filter set
850                 return FILTER_VALIDATE_URL($URL, false);
851         } // END - if
852
853         // If not installed, perform a simple test. Just make it sure there is always a http:// or
854         // https:// in front of the URLs
855         return isUrlValidSimple($URL);
856 }
857
858 // Generate a hash for extra-security for all passwords
859 function generateHash ($plainText, $salt = '', $hash = true) {
860         // Debug output
861         //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
862
863         // Is the required extension 'sql_patches' there and a salt is not given?
864         // 123                            4                      43    3     4     432    2                  3             32    2                             3                32    2      3     3      21
865         if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
866                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
867                 if ($hash === true) {
868                         // Is plain password
869                         return md5($plainText);
870                 } else {
871                         // Is already a hash
872                         return $plainText;
873                 }
874         } // END - if
875
876         // Do we miss an arry element here?
877         if (!isConfigEntrySet('file_hash')) {
878                 // Stop here
879                 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
880         } // END - if
881
882         // When the salt is empty build a new one, else use the first x configured characters as the salt
883         if (empty($salt)) {
884                 // Build server string for more entropy
885                 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
886
887                 // Build key string
888                 $keys   = getSiteKey() . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
889
890                 // Additional data
891                 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
892
893                 // Calculate number for generating the code
894                 $a = time() + getConfig('_ADD') - 1;
895
896                 // Generate SHA1 sum from modula of number and the prime number
897                 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a);
898                 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
899                 $sha1 = scrambleString($sha1);
900                 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
901                 //* DEBUG: */ $sha1b = descrambleString($sha1);
902                 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
903
904                 // Generate the password salt string
905                 $salt = substr($sha1, 0, getSaltLength());
906                 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
907         } else {
908                 // Use given salt
909                 //* DEBUG: */ debugOutput('salt=' . $salt);
910                 $salt = substr($salt, 0, getSaltLength());
911                 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
912
913                 // Sanity check on salt
914                 if (strlen($salt) != getSaltLength()) {
915                         // Not the same!
916                         debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
917                 } // END - if
918         }
919
920         // Generate final hash (for debug output)
921         $finalHash = $salt . sha1($salt . $plainText);
922
923         // Debug output
924         //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
925
926         // Return hash
927         return $finalHash;
928 }
929
930 // Scramble a string
931 function scrambleString ($str) {
932         // Init
933         $scrambled = '';
934
935         // Final check, in case of failture it will return unscrambled string
936         if (strlen($str) > 40) {
937                 // The string is to long
938                 return $str;
939         } elseif (strlen($str) == 40) {
940                 // From database
941                 $scrambleNums = explode(':', getPassScramble());
942         } else {
943                 // Generate new numbers
944                 $scrambleNums = explode(':', genScrambleString(strlen($str)));
945         }
946
947         // Compare both lengths and abort if different
948         if (strlen($str) != count($scrambleNums)) return $str;
949
950         // Scramble string here
951         //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
952         for ($idx = 0; $idx < strlen($str); $idx++) {
953                 // Get char on scrambled position
954                 $char = substr($str, $scrambleNums[$idx], 1);
955
956                 // Add it to final output string
957                 $scrambled .= $char;
958         } // END - for
959
960         // Return scrambled string
961         //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
962         return $scrambled;
963 }
964
965 // De-scramble a string scrambled by scrambleString()
966 function descrambleString ($str) {
967         // Scramble only 40 chars long strings
968         if (strlen($str) != 40) return $str;
969
970         // Load numbers from config
971         $scrambleNums = explode(':', getPassScramble());
972
973         // Validate numbers
974         if (count($scrambleNums) != 40) return $str;
975
976         // Begin descrambling
977         $orig = str_repeat(' ', 40);
978         //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
979         for ($idx = 0; $idx < 40; $idx++) {
980                 $char = substr($str, $idx, 1);
981                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
982         } // END - for
983
984         // Return scrambled string
985         //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
986         return $orig;
987 }
988
989 // Generated a "string" for scrambling
990 function genScrambleString ($len) {
991         // Prepare array for the numbers
992         $scrambleNumbers = array();
993
994         // First we need to setup randomized numbers from 0 to 31
995         for ($idx = 0; $idx < $len; $idx++) {
996                 // Generate number
997                 $rand = mt_rand(0, ($len - 1));
998
999                 // Check for it by creating more numbers
1000                 while (array_key_exists($rand, $scrambleNumbers)) {
1001                         $rand = mt_rand(0, ($len - 1));
1002                 } // END - while
1003
1004                 // Add number
1005                 $scrambleNumbers[$rand] = $rand;
1006         } // END - for
1007
1008         // So let's create the string for storing it in database
1009         $scrambleString = implode(':', $scrambleNumbers);
1010         return $scrambleString;
1011 }
1012
1013 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1014 function encodeHashForCookie ($passHash) {
1015         // Return vanilla password hash
1016         $ret = $passHash;
1017
1018         // Is a secret key and master salt already initialized?
1019         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1020         if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1021                 // Only calculate when the secret key is generated
1022                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1023                 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1024                         // Both keys must have same length so return unencrypted
1025                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1026                         return $ret;
1027                 } // END - if
1028
1029                 $newHash = ''; $start = 9;
1030                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1031                 for ($idx = 0; $idx < 20; $idx++) {
1032                         $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1033                         $part2 = hexdec(substr(getSecretKey(), $start, 2));
1034                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1035                         $mod = dechex($idx);
1036                         if ($part1 > $part2) {
1037                                 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1038                         } elseif ($part2 > $part1) {
1039                                 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1040                         }
1041                         $mod = substr($mod, 0, 2);
1042                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1043                         $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1044                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1045                         $start += 2;
1046                         $newHash .= $mod;
1047                 } // END - for
1048
1049                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1050                 $ret = generateHash($newHash, getMasterSalt());
1051         } // END - if
1052
1053         // Return result
1054         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1055         return $ret;
1056 }
1057
1058 // Fix "deleted" cookies
1059 function fixDeletedCookies ($cookies) {
1060         // Is this an array with entries?
1061         if ((is_array($cookies)) && (count($cookies) > 0)) {
1062                 // Then check all cookies if they are marked as deleted!
1063                 foreach ($cookies as $cookieName) {
1064                         // Is the cookie set to "deleted"?
1065                         if (getSession($cookieName) == 'deleted') {
1066                                 setSession($cookieName, '');
1067                         } // END - if
1068                 } // END - foreach
1069         } // END - if
1070 }
1071
1072 // Checks if a given apache module is loaded
1073 function isApacheModuleLoaded ($apacheModule) {
1074         // Check it and return result
1075         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1076 }
1077
1078 // Get current theme name
1079 function getCurrentTheme () {
1080         // The default theme is 'default'... ;-)
1081         $ret = 'default';
1082
1083         // Do we have ext-theme installed and active?
1084         if (isExtensionActive('theme')) {
1085                 // Call inner method
1086                 $ret = getActualTheme();
1087         } // END - if
1088
1089         // Return theme value
1090         return $ret;
1091 }
1092
1093 // Generates an error code from given account status
1094 function generateErrorCodeFromUserStatus ($status = '') {
1095         // If no status is provided, use the default, cached
1096         if ((empty($status)) && (isMember())) {
1097                 // Get user status
1098                 $status = getUserData('status');
1099         } // END - if
1100
1101         // Default error code if unknown account status
1102         $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1103
1104         // Generate constant name
1105         $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1106
1107         // Is the constant there?
1108         if (isCodeSet($codeName)) {
1109                 // Then get it!
1110                 $errorCode = getCode($codeName);
1111         } else {
1112                 // Unknown status
1113                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1114         }
1115
1116         // Return error code
1117         return $errorCode;
1118 }
1119
1120 // Back-ported from the new ship-simu engine. :-)
1121 function debug_get_printable_backtrace () {
1122         // Init variable
1123         $backtrace = '<ol>';
1124
1125         // Get and prepare backtrace for output
1126         $backtraceArray = debug_backtrace();
1127         foreach ($backtraceArray as $key => $trace) {
1128                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1129                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1130                 if (!isset($trace['args'])) $trace['args'] = array();
1131                 $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>';
1132         } // END - foreach
1133
1134         // Close it
1135         $backtrace .= '</ol>';
1136
1137         // Return the backtrace
1138         return $backtrace;
1139 }
1140
1141 // A mail-able backtrace
1142 function debug_get_mailable_backtrace () {
1143         // Init variable
1144         $backtrace = '';
1145
1146         // Get and prepare backtrace for output
1147         $backtraceArray = debug_backtrace();
1148         foreach ($backtraceArray as $key => $trace) {
1149                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1150                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1151                 if (!isset($trace['args'])) $trace['args'] = array();
1152                 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1153         } // END - foreach
1154
1155         // Return the backtrace
1156         return $backtrace;
1157 }
1158
1159 // Generates a ***weak*** seed
1160 function generateSeed () {
1161         return microtime(true) * 100000;
1162 }
1163
1164 // Converts a message code to a human-readable message
1165 function getMessageFromErrorCode ($code) {
1166         $message = '';
1167         switch ($code) {
1168                 case '': break;
1169                 case getCode('LOGOUT_DONE')        : $message = '{--LOGOUT_DONE--}'; break;
1170                 case getCode('LOGOUT_FAILED')      : $message = '<span class="notice">{--LOGOUT_FAILED--}</span>'; break;
1171                 case getCode('DATA_INVALID')       : $message = '{--MAIL_DATA_INVALID--}'; break;
1172                 case getCode('POSSIBLE_INVALID')   : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1173                 case getCode('USER_404')           : $message = '{--USER_404--}'; break;
1174                 case getCode('STATS_404')          : $message = '{--MAIL_STATS_404--}'; break;
1175                 case getCode('ALREADY_CONFIRMED')  : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1176                 case getCode('WRONG_PASS')         : $message = '{--LOGIN_WRONG_PASS--}'; break;
1177                 case getCode('WRONG_ID')           : $message = '{--LOGIN_WRONG_ID--}'; break;
1178                 case getCode('ACCOUNT_LOCKED')     : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1179                 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1180                 case getCode('COOKIES_DISABLED')   : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1181                 case getCode('BEG_SAME_AS_OWN')    : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1182                 case getCode('LOGIN_FAILED')       : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1183                 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1184                 case getCode('OVERLENGTH')         : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1185                 case getCode('URL_FOUND')          : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1186                 case getCode('SUBJECT_URL')        : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1187                 case getCode('BLIST_URL')          : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1188                 case getCode('NO_RECS_LEFT')       : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1189                 case getCode('INVALID_TAGS')       : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1190                 case getCode('MORE_POINTS')        : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1191                 case getCode('MORE_RECEIVERS1')    : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1192                 case getCode('MORE_RECEIVERS2')    : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1193                 case getCode('MORE_RECEIVERS3')    : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1194                 case getCode('INVALID_URL')        : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1195                 case getCode('NO_MAIL_TYPE')       : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1196                 case getCode('UNKNOWN_ERROR')      : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1197                 case getCode('UNKNOWN_STATUS')     : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1198                 case getCode('PROFILE_UPDATED')    : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1199
1200                 case getCode('ERROR_MAILID'):
1201                         if (isExtensionActive('mailid', true)) {
1202                                 $message = '{--ERROR_CONFIRMING_MAIL--}';
1203                         } else {
1204                                 $message = generateExtensionInactiveNotInstalledMessage('mailid');
1205                         }
1206                         break;
1207
1208                 case getCode('EXTENSION_PROBLEM'):
1209                         if (isGetRequestParameterSet('ext')) {
1210                                 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1211                         } else {
1212                                 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1213                         }
1214                         break;
1215
1216                 case getCode('URL_TIME_LOCK'):
1217                         // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1218                         $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1219                                 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1220
1221                         // Load timestamp from last order
1222                         $content = SQL_FETCHARRAY($result);
1223
1224                         // Free memory
1225                         SQL_FREERESULT($result);
1226
1227                         // Translate it for templates
1228                         $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1229
1230                         // Calculate hours...
1231                         $content['hours'] = round(getUrlTlock() / 60 / 60);
1232
1233                         // Minutes...
1234                         $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1235
1236                         // And seconds
1237                         $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1238
1239                         // Finally contruct the message
1240                         $message = loadTemplate('tlock_message', true, $content);
1241                         break;
1242
1243                 default:
1244                         // Missing/invalid code
1245                         $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1246
1247                         // Log it
1248                         logDebugMessage(__FUNCTION__, __LINE__, $message);
1249                         break;
1250         } // END - switch
1251
1252         // Return the message
1253         return $message;
1254 }
1255
1256 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1257 function isUrlValidSimple ($url) {
1258         // Prepare URL
1259         $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1260
1261         // Allows http and https
1262         $http      = "(http|https)+(:\/\/)";
1263         // Test domain
1264         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1265         // Test double-domains (e.g. .de.vu)
1266         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1267         // Test IP number
1268         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1269         // ... directory
1270         $dir       = "((/)+([-_\.[:alnum:]])+)*";
1271         // ... page
1272         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1273         // ... and the string after and including question character
1274         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1275         // Pattern for URLs like http://url/dir/doc.html?var=value
1276         $pattern['d1dpg1']  = $http . $domain1 . $dir . $page . $getstring1;
1277         $pattern['d2dpg1']  = $http . $domain2 . $dir . $page . $getstring1;
1278         $pattern['ipdpg1']  = $http . $ip . $dir . $page . $getstring1;
1279         // Pattern for URLs like http://url/dir/?var=value
1280         $pattern['d1dg1']  = $http . $domain1 . $dir.'/' . $getstring1;
1281         $pattern['d2dg1']  = $http . $domain2 . $dir.'/' . $getstring1;
1282         $pattern['ipdg1']  = $http . $ip . $dir.'/' . $getstring1;
1283         // Pattern for URLs like http://url/dir/page.ext
1284         $pattern['d1dp']  = $http . $domain1 . $dir . $page;
1285         $pattern['d1dp']  = $http . $domain2 . $dir . $page;
1286         $pattern['ipdp']  = $http . $ip . $dir . $page;
1287         // Pattern for URLs like http://url/dir
1288         $pattern['d1d']  = $http . $domain1 . $dir;
1289         $pattern['d2d']  = $http . $domain2 . $dir;
1290         $pattern['ipd']  = $http . $ip . $dir;
1291         // Pattern for URLs like http://url/?var=value
1292         $pattern['d1g1']  = $http . $domain1 . '/' . $getstring1;
1293         $pattern['d2g1']  = $http . $domain2 . '/' . $getstring1;
1294         $pattern['ipg1']  = $http . $ip . '/' . $getstring1;
1295         // Pattern for URLs like http://url?var=value
1296         $pattern['d1g12']  = $http . $domain1 . $getstring1;
1297         $pattern['d2g12']  = $http . $domain2 . $getstring1;
1298         $pattern['ipg12']  = $http . $ip . $getstring1;
1299
1300         // Test all patterns
1301         $reg = false;
1302         foreach ($pattern as $key => $pat) {
1303                 // Debug regex?
1304                 if (isDebugRegularExpressionEnabled()) {
1305                         // @TODO Are these convertions still required?
1306                         $pat = str_replace('.', '&#92;&#46;', $pat);
1307                         $pat = str_replace('@', '&#92;&#64;', $pat);
1308                         //* DEBUG: */ debugOutput($key . '=&nbsp;' . $pat);
1309                 } // END - if
1310
1311                 // Check if expression matches
1312                 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1313
1314                 // Does it match?
1315                 if ($reg === true) break;
1316         }
1317
1318         // Return true/false
1319         return $reg;
1320 }
1321
1322 // Wtites data to a config.php-style file
1323 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1324 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1325         // Initialize some variables
1326         $done = false;
1327         $seek++;
1328         $next  = -1;
1329         $found = false;
1330
1331         // Is the file there and read-/write-able?
1332         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1333                 $search = 'CFG: ' . $comment;
1334                 $tmp = $FQFN . '.tmp';
1335
1336                 // Open the source file
1337                 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1338
1339                 // Is the resource valid?
1340                 if (is_resource($fp)) {
1341                         // Open temporary file
1342                         $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1343
1344                         // Is the resource again valid?
1345                         if (is_resource($fp_tmp)) {
1346                                 // Mark temporary file as readable
1347                                 $GLOBALS['file_readable'][$tmp] = true;
1348
1349                                 // Start reading
1350                                 while (!feof($fp)) {
1351                                         // Read from source file
1352                                         $line = fgets ($fp, 1024);
1353
1354                                         if (strpos($line, $search) > -1) { 
1355                                                 $next = '0';
1356                                                 $found = true;
1357                                         } // END - if
1358
1359                                         if ($next > -1) {
1360                                                 if ($next === $seek) {
1361                                                         $next = -1;
1362                                                         $line = $prefix . $DATA . $suffix . "\n";
1363                                                 } else {
1364                                                         $next++;
1365                                                 }
1366                                         } // END - if
1367
1368                                         // Write to temp file
1369                                         fwrite($fp_tmp, $line);
1370                                 } // END - while
1371
1372                                 // Close temp file
1373                                 fclose($fp_tmp);
1374
1375                                 // Finished writing tmp file
1376                                 $done = true;
1377                         } // END - if
1378
1379                         // Close source file
1380                         fclose($fp);
1381
1382                         if (($done === true) && ($found === true)) {
1383                                 // Copy back tmp file and delete tmp :-)
1384                                 copyFileVerified($tmp, $FQFN, 0644);
1385                                 return removeFile($tmp);
1386                         } elseif ($found === false) {
1387                                 outputHtml('<strong>CHANGE:</strong> 404!');
1388                         } else {
1389                                 outputHtml('<strong>TMP:</strong> UNDONE!');
1390                         }
1391                 }
1392         } else {
1393                 // File not found, not readable or writeable
1394                 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1395         }
1396
1397         // An error was detected!
1398         return false;
1399 }
1400
1401 // Send notification to admin
1402 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = '0') {
1403         if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1404                 // Send new way
1405                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName);
1406                 sendAdminsEmails($subject, $templateName, $content, $userid);
1407         } else {
1408                 // Send out-dated way
1409                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName);
1410                 $message = loadEmailTemplate($templateName, $content, $userid);
1411                 sendAdminEmails($subject, $message);
1412         }
1413 }
1414
1415 // Debug message logger
1416 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1417         // Is debug mode enabled?
1418         if ((isDebugModeEnabled()) || ($force === true)) {
1419                 // Remove CRLF
1420                 $message = str_replace("\r", '', str_replace("\n", '', $message));
1421
1422                 // Log this message away
1423                 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1424         } // END - if
1425 }
1426
1427 // Handle extra values
1428 function handleExtraValues ($filterFunction, $value, $extraValue) {
1429         // Default is the value itself
1430         $ret = $value;
1431
1432         // Do we have a special filter function?
1433         if (!empty($filterFunction)) {
1434                 // Does the filter function exist?
1435                 if (function_exists($filterFunction)) {
1436                         // Do we have extra parameters here?
1437                         if (!empty($extraValue)) {
1438                                 // Put both parameters in one new array by default
1439                                 $args = array($value, $extraValue);
1440
1441                                 // If we have an array simply use it and pre-extend it with our value
1442                                 if (is_array($extraValue)) {
1443                                         // Make the new args array
1444                                         $args = merge_array(array($value), $extraValue);
1445                                 } // END - if
1446
1447                                 // Call the multi-parameter call-back
1448                                 $ret = call_user_func_array($filterFunction, $args);
1449                         } else {
1450                                 // One parameter call
1451                                 $ret = call_user_func($filterFunction, $value);
1452                         }
1453                 } // END - if
1454         } // END - if
1455
1456         // Return the value
1457         return $ret;
1458 }
1459
1460 // Converts timestamp selections into a timestamp
1461 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1462         // Init test variable
1463         $skip  = false;
1464         $test2 = '';
1465
1466         // Get last three chars
1467         $test = substr($id, -3);
1468
1469         // Improved way of checking! :-)
1470         if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1471                 // Found a multi-selection for timings?
1472                 $test = substr($id, 0, -3);
1473                 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)) {
1474                         // Generate timestamp
1475                         $postData[$test] = createTimestampFromSelections($test, $postData);
1476                         $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1477                         $GLOBALS['skip_config'][$test] = true;
1478
1479                         // Remove data from array
1480                         foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1481                                 unset($postData[$test . '_' . $rem]);
1482                         } // END - foreach
1483
1484                         // Skip adding
1485                         unset($id);
1486                         $skip = true;
1487                         $test2 = $test;
1488                 } // END - if
1489         } // END - if
1490 }
1491
1492 // Reverts the german decimal comma into Computer decimal dot
1493 function convertCommaToDot ($str) {
1494         // Default float is not a float... ;-)
1495         $float = false;
1496
1497         // Which language is selected?
1498         switch (getLanguage()) {
1499                 case 'de': // German language
1500                         // Remove german thousand dots first
1501                         $str = str_replace('.', '', $str);
1502
1503                         // Replace german commata with decimal dot and cast it
1504                         $float = (float)str_replace(',', '.', $str);
1505                         break;
1506
1507                 default: // US and so on
1508                         // Remove thousand dots first and cast
1509                         $float = (float)str_replace(',', '', $str);
1510                         break;
1511         }
1512
1513         // Return float
1514         return $float;
1515 }
1516
1517 // Handle menu-depending failed logins and return the rendered content
1518 function handleLoginFailures ($accessLevel) {
1519         // Default output is empty ;-)
1520         $OUT = '';
1521
1522         // Is the session data set?
1523         if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1524                 // Ignore zero values
1525                 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1526                         // Non-guest has login failures found, get both data and prepare it for template
1527                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1528                         $content = array(
1529                                 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1530                                 'last_failure'   => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1531                         );
1532
1533                         // Load template
1534                         $OUT = loadTemplate('login_failures', true, $content);
1535                 } // END - if
1536
1537                 // Reset session data
1538                 setSession('mailer_' . $accessLevel . '_failures', '');
1539                 setSession('mailer_' . $accessLevel . '_last_failure', '');
1540         } // END - if
1541
1542         // Return rendered content
1543         return $OUT;
1544 }
1545
1546 // Rebuild cache
1547 function rebuildCache ($cache, $inc = '', $force = false) {
1548         // Debug message
1549         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1550
1551         // Shall I remove the cache file?
1552         if (isCacheInstanceValid()) {
1553                 // Rebuild cache
1554                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1555                         // Destroy it
1556                         $GLOBALS['cache_instance']->removeCacheFile($force);
1557                 } // END - if
1558
1559                 // Include file given?
1560                 if (!empty($inc)) {
1561                         // Construct FQFN
1562                         $inc = sprintf("inc/loader/load-%s.php", $inc);
1563
1564                         // Is the include there?
1565                         if (isIncludeReadable($inc)) {
1566                                 // And rebuild it from scratch
1567                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1568                                 loadInclude($inc);
1569                         } else {
1570                                 // Include not found
1571                                 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1572                         }
1573                 } // END - if
1574         } // END - if
1575 }
1576
1577 // Determines the real remote address
1578 function determineRealRemoteAddress ($remoteAddr = false) {
1579         // Is a proxy in use?
1580         if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1581                 // Proxy was used
1582                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1583         } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1584                 // Yet, another proxy
1585                 $address = $_SERVER['HTTP_CLIENT_IP'];
1586         } else {
1587                 // The regular address when no proxy was used
1588                 $address = $_SERVER['REMOTE_ADDR'];
1589         }
1590
1591         // This strips out the real address from proxy output
1592         if (strstr($address, ',')) {
1593                 $addressArray = explode(',', $address);
1594                 $address = $addressArray[0];
1595         } // END - if
1596
1597         // Return the result
1598         return $address;
1599 }
1600
1601 // Adds a bonus mail to the queue
1602 // This is a high-level function!
1603 function addNewBonusMail ($data, $mode = '', $output = true) {
1604         // Use mode from data if not set and availble ;-)
1605         if ((empty($mode)) && (isset($data['mode']))) {
1606                 $mode = $data['mode'];
1607         } // END - if
1608
1609         // Generate receiver list
1610         $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1611
1612         // Receivers added?
1613         if (!empty($receiver)) {
1614                 // Add bonus mail to queue
1615                 addBonusMailToQueue(
1616                         $data['subject'],
1617                         $data['text'],
1618                         $receiver,
1619                         $data['points'],
1620                         $data['seconds'],
1621                         $data['url'],
1622                         $data['cat'],
1623                         $mode,
1624                         $data['receiver']
1625                 );
1626
1627                 // Mail inserted into bonus pool
1628                 if ($output === true) {
1629                         displayMessage('{--ADMIN_BONUS_SEND--}');
1630                 } // END - if
1631         } elseif ($output === true) {
1632                 // More entered than can be reached!
1633                 displayMessage('{--ADMIN_MORE_SELECTED--}');
1634         } else {
1635                 // Debug log
1636                 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1637         }
1638 }
1639
1640 // Determines referal id and sets it
1641 function determineReferalId () {
1642         // Skip this in non-html-mode and outside ref.php
1643         if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) {
1644                 return false;
1645         } // END - if
1646
1647         // Check if refid is set
1648         if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1649                 // This is fine...
1650         } elseif (isPostRequestParameterSet('refid')) {
1651                 // Get referal id from POST element refid
1652                 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1653         } elseif (isGetRequestParameterSet('refid')) {
1654                 // Get referal id from GET parameter refid
1655                 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1656         } elseif (isGetRequestParameterSet('ref')) {
1657                 // Set refid=ref (the referal link uses such variable)
1658                 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1659         } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1660                 // The variable user comes from  click.php
1661                 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1662         } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1663                 // Set session refid als global
1664                 $GLOBALS['refid'] = bigintval(getSession('refid'));
1665         } elseif (isRandomReferalIdEnabled()) {
1666                 // Select a random user which has confirmed enougth mails
1667                 $GLOBALS['refid'] = determineRandomReferalId();
1668         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
1669                 // Set default refid as refid in URL
1670                 $GLOBALS['refid'] = getDefRefid();
1671         } else {
1672                 // No default id when sql_patches is not installed or none set
1673                 $GLOBALS['refid'] = null;
1674         }
1675
1676         // Set cookie when default refid > 0
1677         if (!isSessionVariableSet('refid') || (isValidUserId($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
1678                 // Default is not found
1679                 $found = false;
1680
1681                 // Do we have nickname or userid set?
1682                 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1683                         // Nickname in URL, so load the id
1684                         $found = fetchUserData($GLOBALS['refid'], 'nickname');
1685                 } elseif (isValidUserId($GLOBALS['refid'])) {
1686                         // Direct userid entered
1687                         $found = fetchUserData($GLOBALS['refid']);
1688                 }
1689
1690                 // Is the record valid?
1691                 if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
1692                         // No, then reset referal id
1693                         $GLOBALS['refid'] = getDefRefid();
1694                 } // END - if
1695
1696                 // Set cookie
1697                 setSession('refid', $GLOBALS['refid']);
1698         } // END - if
1699
1700         // Return determined refid
1701         return $GLOBALS['refid'];
1702 }
1703
1704 // Enables the reset mode and runs it
1705 function doReset () {
1706         // Enable the reset mode
1707         $GLOBALS['reset_enabled'] = true;
1708
1709         // Run filters
1710         runFilterChain('reset');
1711 }
1712
1713 // Enables the reset mode (hourly, weekly and monthly) and runs it
1714 function doHourly () {
1715         // Enable the hourly reset mode
1716         $GLOBALS['hourly_enabled'] = true;
1717
1718         // Run filters (one always!)
1719         runFilterChain('hourly');
1720 }
1721
1722 // Our shutdown-function
1723 function shutdown () {
1724         // Call the filter chain 'shutdown'
1725         runFilterChain('shutdown', null);
1726
1727         // Check if not in installation phase and the link is up
1728         if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1729                 // Close link
1730                 SQL_CLOSE(__FUNCTION__, __LINE__);
1731         } elseif (!isInstallationPhase()) {
1732                 // No database link
1733                 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
1734         }
1735
1736         // Stop executing here
1737         exit;
1738 }
1739
1740 // Init member id
1741 function initMemberId () {
1742         $GLOBALS['member_id'] = '0';
1743 }
1744
1745 // Setter for member id
1746 function setMemberId ($memberid) {
1747         // We should not set member id to zero
1748         if ($memberid == '0') {
1749                 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1750         } // END - if
1751
1752         // Set it secured
1753         $GLOBALS['member_id'] = bigintval($memberid);
1754 }
1755
1756 // Getter for member id or returns zero
1757 function getMemberId () {
1758         // Default member id
1759         $memberid = '0';
1760
1761         // Is the member id set?
1762         if (isMemberIdSet()) {
1763                 // Then use it
1764                 $memberid = $GLOBALS['member_id'];
1765         } // END - if
1766
1767         // Return it
1768         return $memberid;
1769 }
1770
1771 // Checks ether the member id is set
1772 function isMemberIdSet () {
1773         return (isset($GLOBALS['member_id']));
1774 }
1775
1776 // Setter for extra title
1777 function setExtraTitle ($extraTitle) {
1778         $GLOBALS['extra_title'] = $extraTitle;
1779 }
1780
1781 // Getter for extra title
1782 function getExtraTitle () {
1783         // Is the extra title set?
1784         if (!isExtraTitleSet()) {
1785                 // No, then abort here
1786                 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1787         } // END - if
1788
1789         // Return it
1790         return $GLOBALS['extra_title'];
1791 }
1792
1793 // Checks if the extra title is set
1794 function isExtraTitleSet () {
1795         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1796 }
1797
1798 // Reads a directory recursively by default and searches for files not matching
1799 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
1800 // a whole directory.
1801 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
1802         // Add default entries we should exclude
1803         $excludeArray[] = '.';
1804         $excludeArray[] = '..';
1805         $excludeArray[] = '.svn';
1806         $excludeArray[] = '.htaccess';
1807
1808         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1809         // Init includes
1810         $files = array();
1811
1812         // Open directory
1813         $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1814
1815         // Read all entries
1816         while ($baseFile = readdir($dirPointer)) {
1817                 // Exclude '.', '..' and entries in $excludeArray automatically
1818                 if (in_array($baseFile, $excludeArray, true))  {
1819                         // Exclude them
1820                         //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1821                         continue;
1822                 } // END - if
1823
1824                 // Construct include filename and FQFN
1825                 $fileName = $baseDir . $baseFile;
1826                 $FQFN = getPath() . $fileName;
1827
1828                 // Remove double slashes
1829                 $FQFN = str_replace('//', '/', $FQFN);
1830
1831                 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1832                 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1833                         // These Lines are only for debugging!!
1834                         //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
1835                         //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
1836                         //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
1837
1838                         // Exclude this one
1839                         continue;
1840                 } // END - if
1841
1842                 // Skip also files with non-matching prefix genericly
1843                 if (($recursive === true) && (isDirectory($FQFN))) {
1844                         // Is a redirectory so read it as well
1845                         $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1846
1847                         // And skip further processing
1848                         continue;
1849                 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1850                         // Skip this file
1851                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1852                         continue;
1853                 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1854                         // Skip wrong suffix as well
1855                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1856                         continue;
1857                 } elseif (!isFileReadable($FQFN)) {
1858                         // Not readable so skip it
1859                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1860                         continue;
1861                 }
1862
1863                 // Get file' extension (last 4 chars)
1864                 $fileExtension = substr($baseFile, -4, 4);
1865
1866                 // Is the file a PHP script or other?
1867                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1868                 if (($fileExtension == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
1869                         // Is this a valid include file?
1870                         if ($extension == '.php') {
1871                                 // Remove both for extension name
1872                                 $extName = substr($baseFile, strlen($prefix), -4);
1873
1874                                 // Add file with or without base path
1875                                 if ($addBaseDir === true) {
1876                                         // With base path
1877                                         $files[] = $fileName;
1878                                 } else {
1879                                         // No base path
1880                                         $files[] = $baseFile;
1881                                 }
1882                         } else {
1883                                 // We found .php file but should not search for them, why?
1884                                 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1885                         }
1886                 } elseif ($fileExtension == $extension) {
1887                         // Other, generic file found
1888                         $files[] = $fileName;
1889                 }
1890         } // END - while
1891
1892         // Close directory
1893         closedir($dirPointer);
1894
1895         // Sort array
1896         sort($files);
1897
1898         // Return array with include files
1899         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1900         return $files;
1901 }
1902
1903 // Checks wether $prefix is found in $fileName
1904 function isFilePrefixFound ($fileName, $prefix) {
1905         // @TODO Find a way to cache this
1906         return (substr($fileName, 0, strlen($prefix)) == $prefix);
1907 }
1908
1909 // Maps a module name into a database table name
1910 function mapModuleToTable ($moduleName) {
1911         // Map only these, still lame code...
1912         switch ($moduleName) {
1913                 // 'index' is the guest's menu
1914                 case 'index': $moduleName = 'guest';  break;
1915                 // ... and 'login' the member's menu
1916                 case 'login': $moduleName = 'member'; break;
1917                 // Anything else will not be mapped, silently.
1918         } // END - switch
1919
1920         // Return result
1921         return $moduleName;
1922 }
1923
1924 // Add SQL debug data to array for later output
1925 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1926         // Do we have cache?
1927         if (!isset($GLOBALS['debug_sql_available'])) {
1928                 // Check it and cache it in $GLOBALS
1929                 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1930         } // END - if
1931         
1932         // Don't execute anything here if we don't need or ext-other is missing
1933         if ($GLOBALS['debug_sql_available'] === false) {
1934                 return;
1935         } // END - if
1936
1937         // Already executed?
1938         if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1939                 // Then abort here, we don't need to profile a query twice
1940                 return;
1941         } // END - if
1942
1943         // Remeber this as profiled (or not, but we don't care here)
1944         $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
1945
1946         // Generate record
1947         $record = array(
1948                 'num_rows' => SQL_NUMROWS($result),
1949                 'affected' => SQL_AFFECTEDROWS(),
1950                 'sql_str'  => $sqlString,
1951                 'timing'   => $timing,
1952                 'file'     => basename($F),
1953                 'line'     => $L
1954         );
1955
1956         // Add it
1957         $GLOBALS['debug_sqls'][] = $record;
1958 }
1959
1960 // Initializes the cache instance
1961 function initCacheInstance () {
1962         // Check for double-initialization
1963         if (isset($GLOBALS['cache_instance'])) {
1964                 // This should not happen and must be fixed
1965                 debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1966         } // END - if
1967
1968         // Load include for CacheSystem class
1969         loadIncludeOnce('inc/classes/cachesystem.class.php');
1970
1971         // Initialize cache system only when it's needed
1972         $GLOBALS['cache_instance'] = new CacheSystem();
1973
1974         // Did it work?
1975         if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1976                 // Failed to initialize cache sustem
1977                 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
1978         } // END - if
1979 }
1980
1981 // Getter for message from array or raw message
1982 function getMessageFromIndexedArray ($message, $pos, $array) {
1983         // Check if the requested message was found in array
1984         if (isset($array[$pos])) {
1985                 // ... if yes then use it!
1986                 $ret = $array[$pos];
1987         } else {
1988                 // ... else use default message
1989                 $ret = $message;
1990         }
1991
1992         // Return result
1993         return $ret;
1994 }
1995
1996 // Convert ';' to ', ' for e.g. receiver list
1997 function convertReceivers ($old) {
1998         return str_replace(';', ', ', $old);
1999 }
2000
2001 // Get a module from filename and access level
2002 function getModuleFromFileName ($file, $accessLevel) {
2003         // Default is 'invalid';
2004         $modCheck = 'invalid';
2005
2006         // @TODO This is still very static, rewrite it somehow
2007         switch ($accessLevel) {
2008                 case 'admin':
2009                         $modCheck = 'admin';
2010                         break;
2011
2012                 case 'sponsor':
2013                 case 'guest':
2014                 case 'member':
2015                         $modCheck = getModule();
2016                         break;
2017
2018                 default: // Unsupported file name / access level
2019                         debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2020                         break;
2021         }
2022
2023         // Return result
2024         return $modCheck;
2025 }
2026
2027 // Encodes an URL for adding session id, etc.
2028 function encodeUrl ($url, $outputMode = '0') {
2029         // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2030         if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) {
2031                 // Raw output mode detected or session_name() found in URL
2032                 return $url;
2033         } // END - if
2034
2035         // Do we have a valid session?
2036         if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2037                 // Invalid session
2038                 // Determine right seperator
2039                 $seperator = '&amp;';
2040                 if (strpos($url, '?') === false) {
2041                         // No question mark
2042                         $seperator = '?';
2043                 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2044                         // Non-HTML mode (or forced non-HTML mode
2045                         $seperator = '&';
2046                 }
2047
2048                 // Add it to URL
2049                 if (session_id() != '') {
2050                         $url .= $seperator . session_name() . '=' . session_id();
2051                 } // END - if
2052         } // END - if
2053
2054         // Add {?URL?} ?
2055         if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2056                 // Add it
2057                 $url = '{?URL?}/' . $url;
2058         } // END - if
2059
2060         // Return the URL
2061         return $url;
2062 }
2063
2064 // Simple check for spider
2065 function isSpider () {
2066         // Get the UA and trim it down
2067         $userAgent = trim(strtolower(detectUserAgent(true)));
2068
2069         // It should not be empty, if so it is better a spider/bot
2070         if (empty($userAgent)) {
2071                 // It is a spider/bot
2072                 return true;
2073         } // END - if
2074
2075         // Is it a spider?
2076         return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2077 }
2078
2079 // Function to search for the last modified file
2080 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2081         // Get dir as array
2082         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2083         // Does it match what we are looking for? (We skip a lot files already!)
2084         // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
2085         $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2086
2087         $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2088         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2089
2090         // Walk through all entries
2091         foreach ($ds as $d) {
2092                 // Generate proper FQFN
2093                 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2094
2095                 // Is it a file and readable?
2096                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2097                 if (isFileReadable($FQFN)) {
2098                         // $FQFN is a readable file so extract the requested data from it
2099                         $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2100                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2101
2102                         // Is the file more recent?
2103                         if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2104                                 // This file is newer as the file before
2105                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2106                                 $last_changed['path_name'] = $FQFN;
2107                                 $last_changed[$lookFor] = $check;
2108                         } // END - if
2109                 } else {
2110                         // Not readable
2111                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2112                 }
2113         } // END - foreach
2114 }
2115
2116 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2117 function handleFieldWithBraces ($field) {
2118         // Are there braces [] at the end?
2119         if (substr($field, -2, 2) == '[]') {
2120                 // Try to find one and replace it. I do it this way to allow easy
2121                 // extending of this code.
2122                 foreach (array('admin_list_builder_id_value') as $key) {
2123                         // Is the cache entry set?
2124                         if (isset($GLOBALS[$key])) {
2125                                 // Insert it
2126                                 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2127
2128                                 // And abort
2129                                 break;
2130                         } // END - if
2131                 } // END - foreach
2132         } // END - if
2133
2134         // Return it
2135         return $field;
2136 }
2137
2138 // Converts a userid so it can be used in SQL queries
2139 function makeDatabaseUserId ($userid) {
2140         // Is it a valid username?
2141         if (isValidUserId($userid)) {
2142                 // Always secure it
2143                 $userid = bigintval($userid);
2144         } else {
2145                 // Is not valid or zero
2146                 $userid = 'NULL';
2147         }
2148
2149         // Return it
2150         return $userid;
2151 }
2152
2153 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2154 // Note: This function is cached
2155 function capitalizeUnderscoreString ($str) {
2156         // Do we have cache?
2157         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2158                 // Init target string
2159                 $capitalized = '';
2160
2161                 // Explode it with the underscore, but rewrite dashes to underscore before
2162                 $strArray = explode('_', str_replace('-', '_', $str));
2163
2164                 // "Walk" through all elements and make them lower-case but first upper-case
2165                 foreach ($strArray as $part) {
2166                         // Capitalize the string part
2167                         $capitalized .= firstCharUpperCase($part);
2168                 } // END - foreach
2169
2170                 // Store the converted string in cache array
2171                 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2172         } // END - if
2173
2174         // Return cache
2175         return $GLOBALS[__FUNCTION__][$str];
2176 }
2177
2178 // Generate admin links for mail order
2179 // mailType can be: 'mid' or 'bid'
2180 function generateAdminMailLinks ($mailType, $mailId) {
2181         // Init variables
2182         $OUT = '';
2183         $table = '';
2184
2185         // Default column for mail status is 'data_type'
2186         // @TODO Rename column data_type to e.g. mail_status
2187         $statusColumn = 'data_type';
2188
2189         // Which mail do we have?
2190         switch ($mailType) {
2191                 case 'bid': // Bonus mail
2192                         $table = 'bonus';
2193                         break;
2194
2195                 case 'mid': // Member mail
2196                         $table = 'pool';
2197                         break;
2198
2199                 default: // Handle unsupported types
2200                         logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2201                         $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2202                         break;
2203         } // END - switch
2204
2205         // Is the mail type supported?
2206         if (!empty($table)) {
2207                 // Query for the mail
2208                 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2209                         array($statusColumn, $table, bigintval($mailId)), __FILE__, __LINE__);
2210
2211                 // Do we have one entry there?
2212                 if (SQL_NUMROWS($result) == 1) {
2213                         // Load the entry
2214                         $content = SQL_FETCHARRAY($result);
2215                         die('Unfinished area:<br />'.__FUNCTION__.':<br />content=<pre>'.print_r($content, true).'</pre>');
2216                 } // END - if
2217
2218                 // Free result
2219                 SQL_FREERESULT($result);
2220         } // END - if
2221
2222         // Return generated HTML code
2223         return $OUT;
2224 }
2225
2226
2227 /**
2228  * determine if a string can represent a number in hexadecimal
2229  *
2230  * @param       $hex    A string to check if it is hex-encoded
2231  * @return      $foo    True if the string is a hex, otherwise false
2232  * @author      Marques Johansson
2233  * @link        http://php.net/manual/en/function.http-chunked-decode.php#89786
2234  */
2235 function isHexadecimal ($hex) {
2236         // Make it lowercase
2237         $hex = strtolower(trim(ltrim($hex, '0')));
2238
2239         // Fix empty strings to zero
2240         if (empty($hex)) {
2241                 $hex = 0;
2242         } // END - if
2243
2244         // Simply compare decode->encode result with original
2245         return ($hex == dechex(hexdec($hex)));
2246 }
2247
2248 // Replace "\r" with "[r]" and "\n" with "[n]" and add a final new-line to make
2249 // them visible to the developer. Use this function to debug e.g. buggy HTTP
2250 // response handler functions.
2251 function replaceReturnNewLine ($str) {
2252         return str_replace("\r", '[r]', str_replace("\n", '[n]
2253 ', $str));
2254 }
2255
2256 // Converts a given string by splitting it up with given delimiter similar to
2257 // explode(), but appending the delimiter again
2258 function stringToArray ($delimiter, $string) {
2259         // Init array
2260         $strArray = array();
2261
2262         // "Walk" through all entries
2263         foreach (explode($delimiter, $string) as $split) {
2264                 //  Append the delimiter and add it to the array
2265                 $strArray[] = $split . $delimiter;
2266         } // END - foreach
2267
2268         // Return array
2269         return $strArray;
2270 }
2271
2272 // Detects the prefix 'mb_' if a multi-byte string is given
2273 function detectMultiBytePrefix ($str) {
2274         // Default is without multi-byte
2275         $mbPrefix = '';
2276
2277         // Detect multi-byte (strictly)
2278         if (mb_detect_encoding($str, 'auto', true) !== false) {
2279                 // With multi-byte encoded string
2280                 $mbPrefix = 'mb_';
2281         } // END - if
2282
2283         // Return the prefix
2284         return $mbPrefix;
2285 }
2286
2287 // Searches the given array for a sub-string match and returns all found keys in an array
2288 function getArrayKeysFromSubStrArray ($heystack, array $needles, $offset = 0) {
2289         // Init array for all found keys
2290         $keys = array();
2291
2292         // Now check all entries
2293         foreach ($needles as $key => $needle) {
2294                 // Do we have found a partial string?
2295                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2296                 if (strpos($heystack, $needle, $offset) !== false) {
2297                         // Add the found key
2298                         $keys[] = $key;
2299                 } // END - if
2300         } // END - foreach
2301
2302         // Return the array
2303         return $keys;
2304 }
2305
2306 //-----------------------------------------------------------------------------
2307 // Automatically re-created functions, all taken from user comments on www.php.net
2308 //-----------------------------------------------------------------------------
2309 if (!function_exists('html_entity_decode')) {
2310         // Taken from documentation on www.php.net
2311         function html_entity_decode ($string) {
2312                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2313                 $trans_tbl = array_flip($trans_tbl);
2314                 return strtr($string, $trans_tbl);
2315         }
2316 } // END - if
2317
2318 // [EOF]
2319 ?>