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