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