2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/25/2003 *
4 * =================== Last change: 11/29/2005 *
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 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Sends out all headers required for HTTP/1.1 reply
46 function sendHttpHeaders () {
48 $now = gmdate('D, d M Y H:i:s') . ' GMT';
51 sendHeader('HTTP/1.1 ' . getHttpStatus());
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());
63 // Init fatal message array
64 function initFatalMessages () {
65 $GLOBALS['fatal_messages'] = array();
68 // Getter for whole fatal error messages
69 function getFatalArray () {
70 return $GLOBALS['fatal_messages'];
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);
83 // Add message to $GLOBALS['fatal_messages']
84 $GLOBALS['fatal_messages'][] = $message;
86 // Log fatal messages away
87 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
90 // Getter for total fatal message count
91 function getTotalFatalErrors () {
95 // Do we have at least the first entry?
96 if (!empty($GLOBALS['fatal_messages'][0])) {
98 $count = count($GLOBALS['fatal_messages']);
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);
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);
117 // Does the user exist?
118 if (fetchUserData($toEmail)) {
120 $toEmail = getUserData('email');
123 $toEmail = getConfig('WEBMASTER');
126 } elseif ($toEmail == '0') {
128 $toEmail = getConfig('WEBMASTER');
130 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
132 // Check for PHPMailer or debug-mode
133 if ((!checkPhpMailerUsage()) || (isDebugModeEnabled())) {
134 // Prefix is '' for text mails
138 if ($isHtml == 'Y') {
143 // Not in PHPMailer-Mode
144 if (empty($mailHeader)) {
145 // Load email header template
146 $mailHeader = loadEmailTemplate($prefix . 'header');
149 $mailHeader .= loadEmailTemplate($prefix . 'header');
153 // Fix HTML parameter (default is no!)
154 if (empty($isHtml)) $isHtml = 'N';
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
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)) . '
166 // This is always fine
168 } elseif (!empty($toEmail)) {
170 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
171 } elseif ($isHtml != 'Y') {
173 return sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
176 // Why did we end up here? This should not happen
177 debug_report_bug(__FUNCTION__, __LINE__, 'Ending up: template=' . $template);
180 // Check to use wether legacy mail() command or PHPMailer class
181 // @TODO Rewrite this to an extension 'smtp'
183 function checkPhpMailerUsage() {
184 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
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)) . '"); ';
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)) . '";';
197 // Run the final eval() command
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');
207 $mail = new PHPMailer();
209 // Set charset to UTF-8
210 $mail->CharSet = 'UTF-8';
212 // Path for PHPMailer
213 $mail->PluginDir = sprintf("%sinc/phpmailer/", getPath());
216 $mail->SMTPAuth = true;
217 $mail->Host = getConfig('SMTP_HOSTNAME');
219 $mail->Username = getConfig('SMTP_USER');
220 $mail->Password = getConfig('SMTP_PASSWORD');
221 if (empty($headers)) {
222 $mail->From = getConfig('WEBMASTER');
224 $mail->From = $headers;
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;
234 $mail->Body = decodeEntities($message);
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'));
244 // Has an error occured?
245 if (!empty($mail->ErrorInfo)) {
247 logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
256 // Use legacy mail() command
257 return mail($toEmail, $subject, decodeEntities($message), $headers);
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');
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,-,+,_,/,.');
269 // Start creating password
271 for ($i = '0'; $i < $length; $i++) {
272 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
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);
282 // Return the password
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"
291 return '{--NEVER_HAPPENED--}';
294 // Filter out numbers
295 $time = bigintval($time);
298 if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
300 return $GLOBALS[__FUNCTION__][$time][$mode];
304 switch (getLanguage()) {
305 case 'de': // German date / time format
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;
315 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
320 default: // Default is the US date / time format!
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;
330 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
336 $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
342 // Translates Y/N to yes/no
343 function translateYesNo ($yn) {
345 if (!isset($GLOBALS[__FUNCTION__][$yn])) {
347 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
349 case 'Y': $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; break;
350 case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break;
353 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
359 return $GLOBALS[__FUNCTION__][$yn];
362 // Translates the "pool type" into human-readable
363 function translatePoolType ($type) {
364 // Return "translation"
365 return sprintf("{--POOL_TYPE_%s--}", $type);
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;
373 // Default is 3 you can change this in admin area "Misc -> Misc Options"
374 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
376 // Use from config is default
377 $maxComma = getConfig('max_comma');
379 // Use from parameter?
380 if ($max > 0) $maxComma = $max;
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... ;-)
395 $translated = $dotted;
396 switch (getLanguage()) {
397 case 'de': // German language
398 $translated = number_format($dotted, $maxComma, ',', '.');
401 default: // All others
402 $translated = number_format($dotted, $maxComma, '.', ',');
406 // Return translated value
407 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
411 // Translate Uni*-like gender to human-readable
412 function translateGender ($gender) {
414 $ret = '!' . $gender . '!';
416 // Male/female or company?
421 $ret = sprintf("{--GENDER_%s--}", $gender);
425 // Please report bugs on unknown genders
426 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
430 // Return translated gender
434 // "Translates" the user status
435 function translateUserStatus ($status) {
436 // Generate message depending on status
441 $ret = sprintf("{--ACCOUNT_STATUS_%s--}", $status);
446 $ret = '{--ACCOUNT_STATUS_DELETED--}';
450 // Please report all unknown status
451 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
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']) {
464 case 'Y': $content['visible_css'] = $prefix . 'menu_visible' ; break;
465 case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break;
467 // Please report this
468 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, true) . '</pre>');
472 // Translate 'locked' and keep an eye on the prefix
473 switch ($content['locked']) {
475 case 'Y': $content['locked_css'] = $prefix . 'menu_locked' ; break;
476 case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break;
478 // Please report this
479 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, true) . '</pre>');
483 // Return the resulting array
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&url=' . encodeString(compileUriCode($URL)) . '%}';
499 // Generates an URL for the frametester
500 function generateFrametesterUrl ($URL) {
501 // Prepare frametester URL
502 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
503 encodeString(compileUriCode($URL))
506 // Return the new URL
507 return $frametesterUrl;
510 // Count entries from e.g. a selection box
511 function countSelection ($array) {
513 if (!is_array($array)) {
515 debug_report_bug(__FUNCTION__, __LINE__, 'No array provided.');
522 foreach ($array as $key => $selected) {
524 if (!empty($selected)) $ret++;
527 // Return counted selections
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);
538 // Create timestamp for wished time which depends on extracted date
549 // Redirects to an URL and if neccessarry extends it with own base URL
550 function redirectToUrl ($URL, $allowSpider = true) {
552 if (substr($URL, 0, 6) == '{%url=') $URL = substr($URL, 6, -2);
555 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
557 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
558 $rel = ' rel="external"';
560 // Do we have internal or external URL?
561 if (substr($URL, 0, strlen(getUrl())) == getUrl()) {
562 // Own (=internal) URL
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);
571 // Simple probe for bots/spiders from search engines
572 if ((isSpider()) && ($allowSpider === true)) {
574 setHttpStatus('200 OK');
576 // Set content-type here to fix a missing array element
577 setContentType('text/html');
579 // Output new location link as anchor
580 outputHtml('<a href="' . $URL . '"' . $rel . '>' . secureString($URL) . '</a>');
581 } elseif (!headers_sent()) {
582 // Clear output buffer
585 // Clear own output buffer
586 $GLOBALS['output'] = '';
588 // Load URL when headers are not sent
589 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $URL), false));
591 // Output error message
592 loadInclude('inc/header.php');
593 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
594 loadInclude('inc/footer.php');
597 // Shut the mailer down here
601 /************************************************************************
603 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
604 * $a_sort sortiert: *
606 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
607 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
608 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
609 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
610 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
612 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
613 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
614 * Sie, dass es doch nicht so schwer ist! :-) *
616 ************************************************************************/
617 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
619 while ($primary_key < count($a_sort)) {
620 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
621 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
623 if ($nums === false) {
624 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
625 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
626 } elseif ($key != $key2) {
627 // Sort numbers (E.g.: 9 < 10)
628 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
629 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
633 // We have found two different values, so let's sort whole array
634 foreach ($dummy as $sort_key => $sort_val) {
635 $t = $dummy[$sort_key][$key];
636 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
637 $dummy[$sort_key][$key2] = $t;
648 // Write back sorted array
654 // Deprecated : $length
657 function generateRandomCode ($length, $code, $userid, $DATA = '') {
658 // Build server string
659 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
662 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY');
663 if (isConfigEntrySet('secret_key')) $keys .= getEncryptSeperator().getSecretKey();
664 if (isConfigEntrySet('file_hash')) $keys .= getEncryptSeperator().getFileHash();
665 $keys .= getEncryptSeperator() . getDateFromPatchTime();
666 if (isConfigEntrySet('master_salt')) $keys .= getEncryptSeperator().getMasterSalt();
668 // Build string from misc data
669 $data = $code . getEncryptSeperator() . $userid . getEncryptSeperator() . $DATA;
671 // Add more additional data
672 if (isSessionVariableSet('u_hash')) $data .= getEncryptSeperator() . getSession('u_hash');
674 // Add referal id, language, theme and userid
675 $data .= getEncryptSeperator() . determineReferalId();
676 $data .= getEncryptSeperator() . getLanguage();
677 $data .= getEncryptSeperator() . getCurrentTheme();
678 $data .= getEncryptSeperator() . getMemberId();
680 // Calculate number for generating the code
681 $a = $code + getConfig('_ADD') - 1;
683 if (isConfigEntrySet('master_salt')) {
684 // Generate hash with master salt from modula of number with the prime number and other data
685 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, getMasterSalt());
687 // Create number from hash
688 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
690 // Generate hash with "hash of site key" from modula of number with the prime number and other data
691 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, substr(sha1(getConfig('SITE_KEY')), 0, getSaltLength()));
693 // Create number from hash
694 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
697 // At least 10 numbers shall be secure enought!
698 $len = getConfig('code_length');
699 if ($len == '0') $len = $length;
700 if ($len == '0') $len = 10;
702 // Cut off requested counts of number
703 $return = substr(str_replace('.', '', $rcode), 0, $len);
705 // Done building code
709 // Does only allow numbers
710 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
711 // Filter all numbers out
712 $ret = preg_replace('/[^0123456789]/', '', $num);
715 if ($castValue === true) $ret = (double)$ret;
717 // Has the whole value changed?
718 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
720 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret=' . $ret . ', num='. $num);
727 // Creates a Uni* timestamp from given selection data and prefix
728 function createTimestampFromSelections ($prefix, $postData) {
729 // Initial return value
732 // Do we have a leap year?
734 $TEST = getYear() / 4;
737 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
738 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
740 // First add years...
741 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
744 $ret += $postData[$prefix . '_mo'] * 2628000;
747 $ret += $postData[$prefix . '_we'] * 604800;
750 $ret += $postData[$prefix . '_da'] * 86400;
753 $ret += $postData[$prefix . '_ho'] * 3600;
756 $ret += $postData[$prefix . '_mi'] * 60;
758 // And at last seconds...
759 $ret += $postData[$prefix . '_se'];
761 // Return calculated value
765 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
766 function createFancyTime ($stamp) {
767 // Get data array with years/months/weeks/days/...
768 $data = createTimeSelections($stamp, '', '', '', true);
770 foreach($data as $k => $v) {
772 // Value is greater than 0 "eval" data to return string
773 $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
778 // Do we have something there?
779 if (strlen($ret) > 0) {
780 // Remove leading commata and space
781 $ret = substr($ret, 2);
784 $ret = '0 {--_SECONDS--}';
787 // Return fancy time string
791 // Extract host from script name
792 function extractHostnameFromUrl (&$script) {
793 // Use default SERVER_URL by default... ;) So?
794 $url = getServerUrl();
796 // Is this URL valid?
797 if (substr($script, 0, 7) == 'http://') {
798 // Use the hostname from script URL as new hostname
799 $url = substr($script, 7);
800 $extract = explode('/', $url);
802 // Done extracting the URL :)
806 $host = str_replace('http://', '', $url);
807 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
809 // Generate relative URL
810 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
811 if (substr(strtolower($script), 0, 7) == 'http://') {
812 // But only if http:// is in front!
813 $script = substr($script, (strlen($url) + 7));
814 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
816 $script = substr($script, (strlen($url) + 8));
819 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
820 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
826 // Send a GET request
827 function sendGetRequest ($script, $data = array()) {
828 // Extract host name from script
829 $host = extractHostnameFromUrl($script);
832 $body = http_build_query($data, '', '&');
834 // There should be data, else we don't need to extend $script with $body
836 // Do we have a question-mark in the script?
837 if (strpos($script, '?') === false) {
838 // No, so first char must be question mark
848 // Remove trailed & to make it more conform
849 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
852 // Generate GET request header
853 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
854 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
855 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
856 if (isConfigEntrySet('FULL_VERSION')) {
857 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
859 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
861 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
862 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
863 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
864 $request .= 'Connection: close' . getConfig('HTTP_EOL');
865 $request .= getConfig('HTTP_EOL');
867 // Send the raw request
868 $response = sendRawRequest($host, $request);
870 // Return the result to the caller function
874 // Send a POST request
875 function sendPostRequest ($script, $postData) {
876 // Is postData an array?
877 if (!is_array($postData)) {
879 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
880 return array('', '', '');
883 // Extract host name from script
884 $host = extractHostnameFromUrl($script);
886 // Construct request body
887 $body = http_build_query($postData, '', '&');
889 // Generate POST request header
890 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
891 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
892 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
893 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
894 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
895 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
896 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
897 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
898 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
899 $request .= 'Connection: close' . getConfig('HTTP_EOL');
900 $request .= getConfig('HTTP_EOL');
905 // Send the raw request
906 $response = sendRawRequest($host, $request);
908 // Return the result to the caller function
912 // Sends a raw request to another host
913 function sendRawRequest ($host, $request) {
914 // Init errno and errdesc with 'all fine' values
915 $errno = '0'; $errdesc = '';
918 $response = array('', '', '');
920 // Default is not to use proxy
923 // Are proxy settins set?
930 loadIncludeOnce('inc/classes/resolver.class.php');
932 // Get resolver instance
933 $resolver = new HostnameResolver();
936 //* DEBUG: */ die('SCRIPT=' . $script);
937 if ($useProxy === true) {
938 // Resolve hostname into IP address
939 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
941 // Connect to host through proxy connection
942 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
944 // Resolve hostname into IP address
945 $ip = $resolver->resolveHostname($host);
947 // Connect to host directly
948 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
952 if (!is_resource($fp)) {
954 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
956 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
957 // Cannot set non-blocking mode or timeout
958 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
963 if ($useProxy === true) {
964 // Setup proxy tunnel
965 $response = setupProxyTunnel($host, $fp);
967 // If the response is invalid, abort
968 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
970 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
976 fwrite($fp, $request);
979 $start = microtime(true);
983 // Get info from stream
984 $info = stream_get_meta_data($fp);
986 // Is it timed out? 15 seconds is a really patient...
987 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
989 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
995 // Get line from stream
996 $line = fgets($fp, 128);
998 // Ignore empty lines because of non-blocking mode
1000 // uslepp a little to avoid 100% CPU load
1007 // Add it to response
1008 $response[] = trim($line);
1014 // Time request if debug-mode is enabled
1015 if (isDebugModeEnabled()) {
1016 // Add debug message...
1017 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1020 // Skip first empty lines
1022 foreach ($resp as $idx => $line) {
1024 $line = trim($line);
1026 // Is this line empty?
1029 array_shift($response);
1031 // Abort on first non-empty line
1036 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1037 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1039 // Proxy agent found or something went wrong?
1040 if (!isset($response[0])) {
1041 // No response, maybe timeout
1042 $response = array('', '', '');
1043 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1044 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1045 // Proxy header detected, so remove two lines
1046 array_shift($response);
1047 array_shift($response);
1050 // Was the request successfull?
1051 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1052 // Not found / access forbidden
1053 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1054 $response = array('', '', '');
1061 // Sets up a proxy tunnel for given hostname and through resource
1062 function setupProxyTunnel ($host, $resource) {
1064 $response = array('', '', '');
1066 // Generate CONNECT request header
1067 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1068 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1070 // Use login data to proxy? (username at least!)
1071 if (getConfig('proxy_username') != '') {
1073 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1074 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1077 // Add last new-line
1078 $proxyTunnel .= getConfig('HTTP_EOL');
1079 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1082 fwrite($fp, $proxyTunnel);
1086 // No response received
1090 // Read the first line
1091 $resp = trim(fgets($fp, 10240));
1092 $respArray = explode(' ', $resp);
1093 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1094 // Invalid response!
1102 // Taken from www.php.net isInStringIgnoreCase() user comments
1103 function isEmailValid ($email) {
1104 // Check first part of email address
1105 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1108 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1111 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1113 // Return check result
1114 return preg_match($regex, $email);
1117 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1118 function isUrlValid ($URL, $compile=true) {
1119 // Trim URL a little
1120 $URL = trim(urldecode($URL));
1121 //* DEBUG: */ debugOutput($URL);
1123 // Compile some chars out...
1124 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1125 //* DEBUG: */ debugOutput($URL);
1127 // Check for the extension filter
1128 if (isExtensionActive('filter')) {
1129 // Use the extension's filter set
1130 return FILTER_VALIDATE_URL($URL, false);
1133 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1134 // https:// in front of the URLs
1135 return isUrlValidSimple($URL);
1138 // Generate a hash for extra-security for all passwords
1139 function generateHash ($plainText, $salt = '', $hash = true) {
1141 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
1143 // Is the required extension 'sql_patches' there and a salt is not given?
1144 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
1145 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
1146 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1147 if ($hash === true) {
1148 // Is plain password
1149 return md5($plainText);
1151 // Is already a hash
1156 // Do we miss an arry element here?
1157 if (!isConfigEntrySet('file_hash')) {
1159 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
1162 // When the salt is empty build a new one, else use the first x configured characters as the salt
1164 // Build server string for more entropy
1165 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
1168 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
1171 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
1173 // Calculate number for generating the code
1174 $a = time() + getConfig('_ADD') - 1;
1176 // Generate SHA1 sum from modula of number and the prime number
1177 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a);
1178 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
1179 $sha1 = scrambleString($sha1);
1180 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
1181 //* DEBUG: */ $sha1b = descrambleString($sha1);
1182 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
1184 // Generate the password salt string
1185 $salt = substr($sha1, 0, getSaltLength());
1186 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
1189 //* DEBUG: */ debugOutput('salt=' . $salt);
1190 $salt = substr($salt, 0, getSaltLength());
1191 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
1193 // Sanity check on salt
1194 if (strlen($salt) != getSaltLength()) {
1196 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
1200 // Generate final hash (for debug output)
1201 $finalHash = $salt . sha1($salt . $plainText);
1204 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
1210 // Scramble a string
1211 function scrambleString ($str) {
1215 // Final check, in case of failture it will return unscrambled string
1216 if (strlen($str) > 40) {
1217 // The string is to long
1219 } elseif (strlen($str) == 40) {
1221 $scrambleNums = explode(':', getPassScramble());
1223 // Generate new numbers
1224 $scrambleNums = explode(':', genScrambleString(strlen($str)));
1227 // Compare both lengths and abort if different
1228 if (strlen($str) != count($scrambleNums)) return $str;
1230 // Scramble string here
1231 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
1232 for ($idx = 0; $idx < strlen($str); $idx++) {
1233 // Get char on scrambled position
1234 $char = substr($str, $scrambleNums[$idx], 1);
1236 // Add it to final output string
1237 $scrambled .= $char;
1240 // Return scrambled string
1241 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
1245 // De-scramble a string scrambled by scrambleString()
1246 function descrambleString ($str) {
1247 // Scramble only 40 chars long strings
1248 if (strlen($str) != 40) return $str;
1250 // Load numbers from config
1251 $scrambleNums = explode(':', getPassScramble());
1254 if (count($scrambleNums) != 40) return $str;
1256 // Begin descrambling
1257 $orig = str_repeat(' ', 40);
1258 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
1259 for ($idx = 0; $idx < 40; $idx++) {
1260 $char = substr($str, $idx, 1);
1261 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1264 // Return scrambled string
1265 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1269 // Generated a "string" for scrambling
1270 function genScrambleString ($len) {
1271 // Prepare array for the numbers
1272 $scrambleNumbers = array();
1274 // First we need to setup randomized numbers from 0 to 31
1275 for ($idx = 0; $idx < $len; $idx++) {
1277 $rand = mt_rand(0, ($len -1));
1279 // Check for it by creating more numbers
1280 while (array_key_exists($rand, $scrambleNumbers)) {
1281 $rand = mt_rand(0, ($len -1));
1285 $scrambleNumbers[$rand] = $rand;
1288 // So let's create the string for storing it in database
1289 $scrambleString = implode(':', $scrambleNumbers);
1290 return $scrambleString;
1293 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1294 function encodeHashForCookie ($passHash) {
1295 // Return vanilla password hash
1298 // Is a secret key and master salt already initialized?
1299 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1300 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1301 // Only calculate when the secret key is generated
1302 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1303 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1304 // Both keys must have same length so return unencrypted
1305 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1309 $newHash = ''; $start = 9;
1310 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1311 for ($idx = 0; $idx < 20; $idx++) {
1312 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1313 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1314 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1315 $mod = dechex($idx);
1316 if ($part1 > $part2) {
1317 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1318 } elseif ($part2 > $part1) {
1319 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1321 $mod = substr($mod, 0, 2);
1322 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1323 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1324 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1329 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1330 $ret = generateHash($newHash, getMasterSalt());
1334 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1338 // Fix "deleted" cookies
1339 function fixDeletedCookies ($cookies) {
1340 // Is this an array with entries?
1341 if ((is_array($cookies)) && (count($cookies) > 0)) {
1342 // Then check all cookies if they are marked as deleted!
1343 foreach ($cookies as $cookieName) {
1344 // Is the cookie set to "deleted"?
1345 if (getSession($cookieName) == 'deleted') {
1346 setSession($cookieName, '');
1352 // Checks if a given apache module is loaded
1353 function isApacheModuleLoaded ($apacheModule) {
1354 // Check it and return result
1355 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1358 // Get current theme name
1359 function getCurrentTheme () {
1360 // The default theme is 'default'... ;-)
1363 // Do we have ext-theme installed and active?
1364 if (isExtensionActive('theme')) {
1365 // Call inner method
1366 $ret = getActualTheme();
1369 // Return theme value
1373 // Generates an error code from given account status
1374 function generateErrorCodeFromUserStatus ($status = '') {
1375 // If no status is provided, use the default, cached
1376 if ((empty($status)) && (isMember())) {
1378 $status = getUserData('status');
1381 // Default error code if unknown account status
1382 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1384 // Generate constant name
1385 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1387 // Is the constant there?
1388 if (isCodeSet($codeName)) {
1390 $errorCode = getCode($codeName);
1393 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1396 // Return error code
1400 // Back-ported from the new ship-simu engine. :-)
1401 function debug_get_printable_backtrace () {
1403 $backtrace = '<ol>';
1405 // Get and prepare backtrace for output
1406 $backtraceArray = debug_backtrace();
1407 foreach ($backtraceArray as $key => $trace) {
1408 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1409 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1410 if (!isset($trace['args'])) $trace['args'] = array();
1411 $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 $backtrace .= '</ol>';
1417 // Return the backtrace
1421 // A mail-able backtrace
1422 function debug_get_mailable_backtrace () {
1426 // Get and prepare backtrace for output
1427 $backtraceArray = debug_backtrace();
1428 foreach ($backtraceArray as $key => $trace) {
1429 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1430 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1431 if (!isset($trace['args'])) $trace['args'] = array();
1432 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1435 // Return the backtrace
1439 // Generates a ***weak*** seed
1440 function generateSeed () {
1441 return microtime(true) * 100000;
1444 // Converts a message code to a human-readable message
1445 function getMessageFromErrorCode ($code) {
1449 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1450 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
1451 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1452 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1453 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1454 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1455 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1456 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1457 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1458 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1459 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1460 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1461 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1462 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1463 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1464 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1465 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1466 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1467 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1468 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1469 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1470 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1471 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1472 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1473 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1474 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1475 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1476 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1477 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1479 case getCode('ERROR_MAILID'):
1480 if (isExtensionActive('mailid', true)) {
1481 $message = '{--ERROR_CONFIRMING_MAIL--}';
1483 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', 'mailid');
1487 case getCode('EXTENSION_PROBLEM'):
1488 if (isGetRequestParameterSet('ext')) {
1489 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1491 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1495 case getCode('URL_TLOCK'):
1496 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1497 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1498 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1500 // Load timestamp from last order
1501 list($timestamp) = SQL_FETCHROW($result);
1504 SQL_FREERESULT($result);
1506 // Translate it for templates
1507 $timestamp = generateDateTime($timestamp, 1);
1509 // Calculate hours...
1510 $STD = round(getConfig('url_tlock') / 60 / 60);
1513 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
1516 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
1518 // Finally contruct the message
1519 // @TODO Rewrite this old lost code to a template
1520 $message = '{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ' . $STD . '
1521 {--_HOURS--}, ' . $MIN . ' {--_MINUTES--} {--_AND--} ' . $SEC . ' {--_SECONDS--}<br />
1522 {--MEMBER_LAST_TLOCK--}: ' . $timestamp;
1526 // Missing/invalid code
1527 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1530 logDebugMessage(__FUNCTION__, __LINE__, $message);
1534 // Return the message
1538 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1539 function isUrlValidSimple ($url) {
1541 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1543 // Allows http and https
1544 $http = "(http|https)+(:\/\/)";
1546 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1547 // Test double-domains (e.g. .de.vu)
1548 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1550 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1552 $dir = "((/)+([-_\.[:alnum:]])+)*";
1554 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1555 // ... and the string after and including question character
1556 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1557 // Pattern for URLs like http://url/dir/doc.html?var=value
1558 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1559 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1560 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1561 // Pattern for URLs like http://url/dir/?var=value
1562 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1563 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1564 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1565 // Pattern for URLs like http://url/dir/page.ext
1566 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1567 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1568 $pattern['ipdp'] = $http . $ip . $dir . $page;
1569 // Pattern for URLs like http://url/dir
1570 $pattern['d1d'] = $http . $domain1 . $dir;
1571 $pattern['d2d'] = $http . $domain2 . $dir;
1572 $pattern['ipd'] = $http . $ip . $dir;
1573 // Pattern for URLs like http://url/?var=value
1574 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1575 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1576 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1577 // Pattern for URLs like http://url?var=value
1578 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1579 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1580 $pattern['ipg12'] = $http . $ip . $getstring1;
1582 // Test all patterns
1584 foreach ($pattern as $key => $pat) {
1586 if (isDebugRegularExpressionEnabled()) {
1587 // @TODO Are these convertions still required?
1588 $pat = str_replace('.', '\.', $pat);
1589 $pat = str_replace('@', '\@', $pat);
1590 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1593 // Check if expression matches
1594 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1597 if ($reg === true) break;
1600 // Return true/false
1604 // Wtites data to a config.php-style file
1605 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1606 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1607 // Initialize some variables
1613 // Is the file there and read-/write-able?
1614 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1615 $search = 'CFG: ' . $comment;
1616 $tmp = $FQFN . '.tmp';
1618 // Open the source file
1619 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1621 // Is the resource valid?
1622 if (is_resource($fp)) {
1623 // Open temporary file
1624 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1626 // Is the resource again valid?
1627 if (is_resource($fp_tmp)) {
1628 // Mark temporary file as readable
1629 $GLOBALS['file_readable'][$tmp] = true;
1632 while (!feof($fp)) {
1633 // Read from source file
1634 $line = fgets ($fp, 1024);
1636 if (strpos($line, $search) > -1) {
1642 if ($next === $seek) {
1644 $line = $prefix . $DATA . $suffix . "\n";
1650 // Write to temp file
1651 fwrite($fp_tmp, $line);
1657 // Finished writing tmp file
1661 // Close source file
1664 if (($done === true) && ($found === true)) {
1665 // Copy back tmp file and delete tmp :-)
1666 copyFileVerified($tmp, $FQFN, 0644);
1667 return removeFile($tmp);
1668 } elseif ($found === false) {
1669 outputHtml('<strong>CHANGE:</strong> 404!');
1671 outputHtml('<strong>TMP:</strong> UNDONE!');
1675 // File not found, not readable or writeable
1676 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1679 // An error was detected!
1682 // Send notification to admin
1683 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
1684 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1686 sendAdminsEmails($subject, $templateName, $content, $userid);
1688 // Send out out-dated way
1689 $message = loadEmailTemplate($templateName, $content, $userid);
1690 sendAdminEmails($subject, $message);
1694 // Debug message logger
1695 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1696 // Is debug mode enabled?
1697 if ((isDebugModeEnabled()) || ($force === true)) {
1699 $message = str_replace("\r", '', str_replace("\n", '', $message));
1701 // Log this message away
1702 $fp = fopen(getCachePath() . 'debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write logfile debug.log!');
1703 fwrite($fp, generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
1708 // Handle extra values
1709 function handleExtraValues ($filterFunction, $value, $extraValue) {
1710 // Default is the value itself
1713 // Do we have a special filter function?
1714 if (!empty($filterFunction)) {
1715 // Does the filter function exist?
1716 if (function_exists($filterFunction)) {
1717 // Do we have extra parameters here?
1718 if (!empty($extraValue)) {
1719 // Put both parameters in one new array by default
1720 $args = array($value, $extraValue);
1722 // If we have an array simply use it and pre-extend it with our value
1723 if (is_array($extraValue)) {
1724 // Make the new args array
1725 $args = merge_array(array($value), $extraValue);
1728 // Call the multi-parameter call-back
1729 $ret = call_user_func_array($filterFunction, $args);
1731 // One parameter call
1732 $ret = call_user_func($filterFunction, $value);
1741 // Converts timestamp selections into a timestamp
1742 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1743 // Init test variable
1747 // Get last three chars
1748 $test = substr($id, -3);
1750 // Improved way of checking! :-)
1751 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1752 // Found a multi-selection for timings?
1753 $test = substr($id, 0, -3);
1754 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)) {
1755 // Generate timestamp
1756 $postData[$test] = createTimestampFromSelections($test, $postData);
1757 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1758 $GLOBALS['skip_config'][$test] = true;
1760 // Remove data from array
1761 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1762 unset($postData[$test . '_' . $rem]);
1773 // Reverts the german decimal comma into Computer decimal dot
1774 function convertCommaToDot ($str) {
1775 // Default float is not a float... ;-)
1778 // Which language is selected?
1779 switch (getLanguage()) {
1780 case 'de': // German language
1781 // Remove german thousand dots first
1782 $str = str_replace('.', '', $str);
1784 // Replace german commata with decimal dot and cast it
1785 $float = (float)str_replace(',', '.', $str);
1788 default: // US and so on
1789 // Remove thousand dots first and cast
1790 $float = (float)str_replace(',', '', $str);
1798 // Handle menu-depending failed logins and return the rendered content
1799 function handleLoginFailures ($accessLevel) {
1800 // Default output is empty ;-)
1803 // Is the session data set?
1804 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1805 // Ignore zero values
1806 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1807 // Non-guest has login failures found, get both data and prepare it for template
1808 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1810 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1811 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1815 $OUT = loadTemplate('login_failures', true, $content);
1818 // Reset session data
1819 setSession('mailer_' . $accessLevel . '_failures', '');
1820 setSession('mailer_' . $accessLevel . '_last_failure', '');
1823 // Return rendered content
1828 function rebuildCache ($cache, $inc = '', $force = false) {
1830 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1832 // Shall I remove the cache file?
1833 if (isCacheInstanceValid()) {
1835 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1837 $GLOBALS['cache_instance']->removeCacheFile($force);
1840 // Include file given?
1843 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
1845 // Is the include there?
1846 if (isIncludeReadable($inc)) {
1847 // And rebuild it from scratch
1848 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1851 // Include not found!
1852 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1858 // Determines the real remote address
1859 function determineRealRemoteAddress () {
1860 // Is a proxy in use?
1861 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1863 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1864 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
1865 // Yet, another proxy
1866 $address = $_SERVER['HTTP_CLIENT_IP'];
1868 // The regular address when no proxy was used
1869 $address = $_SERVER['REMOTE_ADDR'];
1872 // This strips out the real address from proxy output
1873 if (strstr($address, ',')) {
1874 $addressArray = explode(',', $address);
1875 $address = $addressArray[0];
1878 // Return the result
1882 // Adds a bonus mail to the queue
1883 // This is a high-level function!
1884 function addNewBonusMail ($data, $mode = '', $output=true) {
1885 // Use mode from data if not set and availble ;-)
1886 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
1888 // Generate receiver list
1889 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1892 if (!empty($receiver)) {
1893 // Add bonus mail to queue
1894 addBonusMailToQueue(
1906 // Mail inserted into bonus pool
1907 if ($output === true) {
1908 loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
1910 } elseif ($output === true) {
1911 // More entered than can be reached!
1912 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
1915 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1919 // Determines referal id and sets it
1920 function determineReferalId () {
1921 // Skip this in non-html-mode and outside ref.php
1922 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
1924 // Check if refid is set
1925 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1927 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1928 // The variable user comes from the click-counter script click.php and we only accept this here
1929 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1930 } elseif (isPostRequestParameterSet('refid')) {
1931 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
1932 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1933 } elseif (isGetRequestParameterSet('refid')) {
1934 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
1935 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1936 } elseif (isGetRequestParameterSet('ref')) {
1937 // Set refid=ref (the referal link uses such variable)
1938 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1939 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1940 // Set session refid als global
1941 $GLOBALS['refid'] = bigintval(getSession('refid'));
1942 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (isRandomReferalIdEnabled())) {
1943 // Select a random user which has confirmed enougth mails
1944 $GLOBALS['refid'] = determineRandomReferalId();
1945 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getConfig('def_refid')))) {
1946 // Set default refid as refid in URL
1947 $GLOBALS['refid'] = getConfig('def_refid');
1949 // No default id when sql_patches is not installed or none set
1950 $GLOBALS['refid'] = '0';
1953 // Set cookie when default refid > 0
1954 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isConfigEntrySet('def_refid')) && (isValidUserId(getConfig('def_refid'))))) {
1955 // Default is not found
1958 // Do we have nickname or userid set?
1959 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1960 // Nickname in URL, so load the id
1961 $found = fetchUserData($GLOBALS['refid'], 'nickname');
1962 } elseif ($GLOBALS['refid'] > 0) {
1963 // Direct userid entered
1964 $found = fetchUserData($GLOBALS['refid']);
1967 // Is the record valid?
1968 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
1969 // No, then reset referal id
1970 $GLOBALS['refid'] = getConfig('def_refid');
1974 setSession('refid', $GLOBALS['refid']);
1977 // Return determined refid
1978 return $GLOBALS['refid'];
1981 // Enables the reset mode and runs it
1982 function doReset () {
1983 // Enable the reset mode
1984 $GLOBALS['reset_enabled'] = true;
1987 runFilterChain('reset');
1990 // Our shutdown-function
1991 function shutdown () {
1992 // Call the filter chain 'shutdown'
1993 runFilterChain('shutdown', null);
1995 // Check if not in installation phase and the link is up
1996 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1998 SQL_CLOSE(__FUNCTION__, __LINE__);
1999 } elseif (!isInstallationPhase()) {
2001 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
2004 // Stop executing here
2009 function initMemberId () {
2010 $GLOBALS['member_id'] = '0';
2013 // Setter for member id
2014 function setMemberId ($memberid) {
2015 // We should not set member id to zero
2016 if ($memberid == '0') {
2017 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
2021 $GLOBALS['member_id'] = bigintval($memberid);
2024 // Getter for member id or returns zero
2025 function getMemberId () {
2026 // Default member id
2029 // Is the member id set?
2030 if (isMemberIdSet()) {
2032 $memberid = $GLOBALS['member_id'];
2039 // Checks ether the member id is set
2040 function isMemberIdSet () {
2041 return (isset($GLOBALS['member_id']));
2044 // Setter for extra title
2045 function setExtraTitle ($extraTitle) {
2046 $GLOBALS['extra_title'] = $extraTitle;
2049 // Getter for extra title
2050 function getExtraTitle () {
2051 // Is the extra title set?
2052 if (!isExtraTitleSet()) {
2053 // No, then abort here
2054 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
2058 return $GLOBALS['extra_title'];
2061 // Checks if the extra title is set
2062 function isExtraTitleSet () {
2063 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
2066 // Reads a directory recursively by default and searches for files not matching
2067 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
2068 // a whole directory.
2069 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
2070 // Add default entries we should exclude
2071 $excludeArray[] = '.';
2072 $excludeArray[] = '..';
2073 $excludeArray[] = '.svn';
2074 $excludeArray[] = '.htaccess';
2076 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
2081 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
2084 while ($baseFile = readdir($dirPointer)) {
2085 // Exclude '.', '..' and entries in $excludeArray automatically
2086 if (in_array($baseFile, $excludeArray, true)) {
2088 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
2092 // Construct include filename and FQFN
2093 $fileName = $baseDir . $baseFile;
2094 $FQFN = getPath() . $fileName;
2096 // Remove double slashes
2097 $FQFN = str_replace('//', '/', $FQFN);
2099 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
2100 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
2101 // These Lines are only for debugging!!
2102 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
2103 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
2104 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
2110 // Skip also files with non-matching prefix genericly
2111 if (($recursive === true) && (isDirectory($FQFN))) {
2112 // Is a redirectory so read it as well
2113 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
2115 // And skip further processing
2117 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
2119 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
2121 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
2122 // Skip wrong suffix as well
2123 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
2125 } elseif (!isFileReadable($FQFN)) {
2126 // Not readable so skip it
2127 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
2131 // Is the file a PHP script or other?
2132 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
2133 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
2134 // Is this a valid include file?
2135 if ($extension == '.php') {
2136 // Remove both for extension name
2137 $extName = substr($baseFile, strlen($prefix), -4);
2139 // Is the extension valid and active?
2140 if (isExtensionNameValid($extName)) {
2141 // Then add this file
2142 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
2143 $files[] = $fileName;
2145 // Add non-extension files as well
2146 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
2147 if ($addBaseDir === true) {
2148 $files[] = $fileName;
2150 $files[] = $baseFile;
2154 // We found .php file but should not search for them, why?
2155 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
2157 } elseif (substr($baseFile, -4, 4) == $extension) {
2158 // Other, generic file found
2159 $files[] = $fileName;
2164 closedir($dirPointer);
2169 // Return array with include files
2170 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
2174 // Maps a module name into a database table name
2175 function mapModuleToTable ($moduleName) {
2176 // Map only these, still lame code...
2177 switch ($moduleName) {
2178 // 'index' is the guest's menu
2179 case 'index': $moduleName = 'guest'; break;
2180 // ... and 'login' the member's menu
2181 case 'login': $moduleName = 'member'; break;
2182 // Anything else will not be mapped, silently.
2189 // Add SQL debug data to array for later output
2190 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
2191 // Do we have cache?
2192 if (!isset($GLOBALS['debug_sql_available'])) {
2193 // Check it and cache it in $GLOBALS
2194 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
2197 // Don't execute anything here if we don't need or ext-other is missing
2198 if ($GLOBALS['debug_sql_available'] === false) {
2202 // Already executed?
2203 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
2204 // Then abort here, we don't need to profile a query twice
2208 // Remeber this as profiled (or not, but we don't care here)
2209 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
2213 'num_rows' => SQL_NUMROWS($result),
2214 'affected' => SQL_AFFECTEDROWS(),
2215 'sql_str' => $sqlString,
2216 'timing' => $timing,
2217 'file' => basename($F),
2222 $GLOBALS['debug_sqls'][] = $record;
2225 // Initializes the cache instance
2226 function initCacheInstance () {
2227 // Load include for CacheSystem class
2228 loadIncludeOnce('inc/classes/cachesystem.class.php');
2230 // Initialize cache system only when it's needed
2231 $GLOBALS['cache_instance'] = new CacheSystem();
2232 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
2233 // Failed to initialize cache sustem
2234 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2238 // Getter for message from array or raw message
2239 function getMessageFromIndexedArray ($message, $pos, $array) {
2240 // Check if the requested message was found in array
2241 if (isset($array[$pos])) {
2242 // ... if yes then use it!
2243 $ret = $array[$pos];
2245 // ... else use default message
2253 // Convert ';' to ', ' for e.g. receiver list
2254 function convertReceivers ($old) {
2255 return str_replace(';', ', ', $old);
2258 // Get a module from filename and access level
2259 function getModuleFromFileName ($file, $accessLevel) {
2260 // Default is 'invalid';
2261 $modCheck = 'invalid';
2263 // @TODO This is still very static, rewrite it somehow
2264 switch ($accessLevel) {
2266 $modCheck = 'admin';
2272 $modCheck = getModule();
2275 default: // Unsupported file name / access level
2276 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2284 // Encodes an URL for adding session id, etc.
2285 function encodeUrl ($url, $outputMode = '0') {
2286 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2287 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) return $url;
2289 // Do we have a valid session?
2290 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2292 // Determine right seperator
2293 $seperator = '&';
2294 if (strpos($url, '?') === false) {
2297 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2303 if (session_id() != '') {
2304 $url .= $seperator . session_name() . '=' . session_id();
2309 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2311 $url = '{?URL?}/' . $url;
2318 // Simple check for spider
2319 function isSpider () {
2320 // Get the UA and trim it down
2321 $userAgent = trim(strtolower(detectUserAgent(true)));
2323 // It should not be empty, if so it is better a spider/bot
2324 if (empty($userAgent)) return true;
2327 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2330 // Function to search for the last modified file
2331 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2333 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2334 // Does it match what we are looking for? (We skip a lot files already!)
2335 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2336 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2338 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2339 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2341 // Walk through all entries
2342 foreach ($ds as $d) {
2343 // Generate proper FQFN
2344 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2346 // Is it a file and readable?
2347 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2348 if (isFileReadable($FQFN)) {
2349 // $FQFN is a readable file so extract the requested data from it
2350 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2351 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2353 // Is the file more recent?
2354 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2355 // This file is newer as the file before
2356 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2357 $last_changed['path_name'] = $FQFN;
2358 $last_changed[$lookFor] = $check;
2362 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2367 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2368 function handleFieldWithBraces ($field) {
2369 // Are there braces [] at the end?
2370 if (substr($field, -2, 2) == '[]') {
2371 // Try to find one and replace it. I do it this way to allow easy
2372 // extending of this code.
2373 foreach (array('admin_list_builder_id_value') as $key) {
2374 // Is the cache entry set?
2375 if (isset($GLOBALS[$key])) {
2377 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2389 // Converts a userid so it can be used in SQL queries
2390 function makeDatabaseUserId ($userid) {
2391 // Is it a valid username?
2392 if (isValidUserId($userid)) {
2394 $userid = bigintval($userid);
2396 // Is not valid or zero
2404 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2405 // Note: This function is cached
2406 function capitalizeUnderscoreString ($str) {
2407 // Do we have cache?
2408 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2409 // Init target string
2412 // Explode it with the underscore, but rewrite dashes to underscore before
2413 $strArray = explode('_', str_replace('-', '_', $str));
2415 // "Walk" through all elements and make them lower-case but first upper-case
2416 foreach ($strArray as $part) {
2417 // Capitalize the string part
2418 $capitalized .= ucfirst(strtolower($part));
2421 // Store the converted string in cache array
2422 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2426 return $GLOBALS[__FUNCTION__][$str];
2429 //-----------------------------------------------------------------------------
2430 // Automatically re-created functions, all taken from user comments on www.php.net
2431 //-----------------------------------------------------------------------------
2433 if (!function_exists('html_entity_decode')) {
2434 // Taken from documentation on www.php.net
2435 function html_entity_decode ($string) {
2436 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2437 $trans_tbl = array_flip($trans_tbl);
2438 return strtr($string, $trans_tbl);
2442 if (!function_exists('http_build_query')) {
2443 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
2444 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
2446 foreach ((array)$data as $k => $v) {
2447 if (is_int($k) && $prefix != null) {
2448 $k = urlencode($prefix . $k);
2451 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
2453 if (is_array($v) || is_object($v)) {
2454 array_push($ret, http_build_query($v, '', $sep, $k));
2456 array_push($ret, $k.'='.urlencode($v));
2460 if (empty($sep)) $sep = ini_get('arg_separator.output');
2462 return implode($sep, $ret);