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