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