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