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