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