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