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