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