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 // Not in PHPMailer-Mode
135 if (empty($mailHeader)) {
136 // Load email header template
137 $mailHeader = loadEmailTemplate('header');
140 $mailHeader .= loadEmailTemplate('header');
144 // Fix HTML parameter (default is no!)
145 if (empty($isHtml)) $isHtml = 'N';
147 // Debug mode enabled?
148 if (isDebugModeEnabled()) {
149 // In debug mode we want to display the mail instead of sending it away so we can debug this part
151 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
152 To : ' . htmlentities(utf8_decode($toEmail)) . '
153 Subject : ' . htmlentities(utf8_decode($subject)) . '
154 Message : ' . htmlentities(utf8_decode($message)) . '
157 // This is always fine
159 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
160 // Send mail as HTML away
161 return sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
162 } elseif (!empty($toEmail)) {
164 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
165 } elseif ($isHtml != 'Y') {
167 return sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
170 // Why did we end up here? This should not happen
171 debug_report_bug(__FUNCTION__, __LINE__, 'Ending up: template=' . $template);
174 // Check to use wether legacy mail() command or PHPMailer class
175 // @TODO Rewrite this to an extension 'smtp'
177 function checkPhpMailerUsage() {
178 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
181 // Send out a raw email with PHPMailer class or legacy mail() command
182 function sendRawEmail ($toEmail, $subject, $message, $headers) {
183 // Just compile all to put out all configs, etc.
184 $eval = '$toEmail = decodeEntities("' . doFinalCompilation(compileRawCode(escapeQuotes($toEmail)), false) . '"); ';
185 $eval .= '$subject = decodeEntities("' . doFinalCompilation(compileRawCode(escapeQuotes($subject)), false) . '"); ';
186 $eval .= '$headers = decodeEntities("' . doFinalCompilation(compileRawCode(escapeQuotes($headers)), false) . '"); ';
188 // Do not decode entities in the message because we also send HTML mails through this function
189 $eval .= '$message = "' . doFinalCompilation(compileRawCode(escapeQuotes($message)), false) . '";';
191 // Run the final eval() command
194 // Shall we use PHPMailer class or legacy mode?
195 if (checkPhpMailerUsage()) {
196 // Use PHPMailer class with SMTP enabled
197 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
198 loadIncludeOnce('inc/phpmailer/class.smtp.php');
201 $mail = new PHPMailer();
203 // Set charset to UTF-8
204 $mail->CharSet = 'UTF-8';
206 // Path for PHPMailer
207 $mail->PluginDir = sprintf("%sinc/phpmailer/", getPath());
210 $mail->SMTPAuth = true;
211 $mail->Host = getConfig('SMTP_HOSTNAME');
213 $mail->Username = getConfig('SMTP_USER');
214 $mail->Password = getConfig('SMTP_PASSWORD');
215 if (empty($headers)) {
216 $mail->From = getConfig('WEBMASTER');
218 $mail->From = $headers;
220 $mail->FromName = getMainTitle();
221 $mail->Subject = $subject;
222 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
223 $mail->Body = $message;
224 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
225 $mail->WordWrap = 70;
228 $mail->Body = decodeEntities($message);
231 $mail->AddAddress($toEmail, '');
232 $mail->AddReplyTo(getConfig('WEBMASTER'), getMainTitle());
233 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
234 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
235 $mail->AddCustomHeader('Bounces-To:' . getConfig('WEBMASTER'));
238 // Has an error occured?
239 if (!empty($mail->ErrorInfo)) {
241 logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
250 // Use legacy mail() command
251 return mail($toEmail, $subject, decodeEntities($message), $headers);
255 // Generate a password in a specified length or use default password length
256 function generatePassword ($length = '0') {
257 // Auto-fix invalid length of zero
258 if ($length == '0') $length = getConfig('pass_len');
260 // Initialize array with all allowed chars
261 $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,-,+,_,/,.');
263 // Start creating password
265 for ($i = '0'; $i < $length; $i++) {
266 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
269 // When the size is below 40 we can also add additional security by scrambling
270 // it. Otherwise we may corrupt hashes
271 if (strlen($PASS) <= 40) {
272 // Also scramble the password
273 $PASS = scrambleString($PASS);
276 // Return the password
280 // Generates a human-readable timestamp from the Uni* stamp
281 function generateDateTime ($time, $mode = '0') {
282 // If the stamp is zero it mostly didn't "happen"
285 return '{--NEVER_HAPPENED--}';
288 // Filter out numbers
289 $time = bigintval($time);
292 if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
294 return $GLOBALS[__FUNCTION__][$time][$mode];
298 switch (getLanguage()) {
299 case 'de': // German date / time format
301 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
302 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
303 case '2': $ret = date('d.m.Y|H:i', $time); break;
304 case '3': $ret = date('d.m.Y', $time); break;
305 case '4': $ret = date('d.m.Y|H:i:s', $time); break;
306 case '5': $ret = date('d-m-Y (l-F-T)', $time); break;
307 case '6': $ret = date('Ymd', $time); break;
309 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
314 default: // Default is the US date / time format!
316 case '0': $ret = date('r', $time); break;
317 case '1': $ret = strtolower(date('Y-m-d - g:i A', $time)); break;
318 case '2': $ret = date('y-m-d|H:i', $time); break;
319 case '3': $ret = date('y-m-d', $time); break;
320 case '4': $ret = date('d.m.Y|H:i:s', $time); break;
321 case '5': $ret = date('d-m-Y (l-F-T)', $time); break;
322 case '6': $ret = date('Ymd', $time); break;
324 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
330 $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
336 // Translates Y/N to yes/no
337 function translateYesNo ($yn) {
339 if (!isset($GLOBALS[__FUNCTION__][$yn])) {
341 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
343 case 'Y': $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; break;
344 case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break;
347 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
353 return $GLOBALS[__FUNCTION__][$yn];
356 // Translates the "pool type" into human-readable
357 function translatePoolType ($type) {
358 // Return "translation"
359 return sprintf("{--POOL_TYPE_%s--}", $type);
362 // Translates the american decimal dot into a german comma
363 function translateComma ($dotted, $cut = true, $max = '0') {
364 // First, cast all to double, due to PHP changes
365 $dotted = (double) $dotted;
367 // Default is 3 you can change this in admin area "Misc -> Misc Options"
368 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
370 // Use from config is default
371 $maxComma = getConfig('max_comma');
373 // Use from parameter?
374 if ($max > 0) $maxComma = $max;
377 if (($cut === true) && ($max == '0')) {
378 // Test for commata if in cut-mode
379 $com = explode('.', $dotted);
380 if (count($com) < 2) {
381 // Don't display commatas even if there are none... ;-)
389 $translated = $dotted;
390 switch (getLanguage()) {
391 case 'de': // German language
392 $translated = number_format($dotted, $maxComma, ',', '.');
395 default: // All others
396 $translated = number_format($dotted, $maxComma, '.', ',');
400 // Return translated value
401 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
405 // Translate Uni*-like gender to human-readable
406 function translateGender ($gender) {
408 $ret = '!' . $gender . '!';
410 // Male/female or company?
415 $ret = sprintf("{--GENDER_%s--}", $gender);
419 // Please report bugs on unknown genders
420 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
424 // Return translated gender
428 // "Translates" the user status
429 function translateUserStatus ($status) {
430 // Generate message depending on status
435 $ret = sprintf("{--ACCOUNT_STATUS_%s--}", $status);
440 $ret = '{--ACCOUNT_STATUS_DELETED--}';
444 // Please report all unknown status
445 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
453 // "Translates" 'visible' and 'locked' to a CSS class
454 function translateMenuVisibleLocked ($content, $prefix = '') {
455 // Translate 'visible' and keep an eye on the prefix
456 switch ($content['visible']) {
458 case 'Y': $content['visible_css'] = $prefix . 'menu_visible' ; break;
459 case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break;
461 // Please report this
462 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, true) . '</pre>');
466 // Translate 'locked' and keep an eye on the prefix
467 switch ($content['locked']) {
469 case 'Y': $content['locked_css'] = $prefix . 'menu_locked' ; break;
470 case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break;
472 // Please report this
473 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, true) . '</pre>');
477 // Return the resulting array
481 // Generates an URL for the dereferer
482 function generateDerefererUrl ($URL) {
483 // Don't de-refer our own links!
484 if (substr($URL, 0, strlen(getUrl())) != getUrl()) {
485 // De-refer this link
486 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
493 // Generates an URL for the frametester
494 function generateFrametesterUrl ($URL) {
495 // Prepare frametester URL
496 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
497 encodeString(compileUriCode($URL))
500 // Return the new URL
501 return $frametesterUrl;
504 // Count entries from e.g. a selection box
505 function countSelection ($array) {
507 if (!is_array($array)) {
509 debug_report_bug(__FUNCTION__, __LINE__, 'No array provided.');
516 foreach ($array as $key => $selected) {
518 if (!empty($selected)) $ret++;
521 // Return counted selections
525 // Generates a timestamp (some wrapper for mktime())
526 function makeTime ($hours, $minutes, $seconds, $stamp) {
527 // Extract day, month and year from given timestamp
528 $days = getDay($stamp);
529 $months = getMonth($stamp);
530 $years = getYear($stamp);
532 // Create timestamp for wished time which depends on extracted date
543 // Redirects to an URL and if neccessarry extends it with own base URL
544 function redirectToUrl ($URL, $allowSpider = true) {
546 if (substr($URL, 0, 6) == '{%url=') $URL = substr($URL, 6, -2);
549 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
551 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
552 $rel = ' rel="external"';
554 // Do we have internal or external URL?
555 if (substr($URL, 0, strlen(getUrl())) == getUrl()) {
556 // Own (=internal) URL
560 // Three different ways to debug...
561 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'URL=' . $URL);
562 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
563 //* DEBUG: */ die($URL);
565 // Simple probe for bots/spiders from search engines
566 if ((isSpider()) && ($allowSpider === true)) {
568 setHttpStatus('200 OK');
570 // Set content-type here to fix a missing array element
571 setContentType('text/html');
573 // Output new location link as anchor
574 outputHtml('<a href="' . $URL . '"' . $rel . '>' . secureString($URL) . '</a>');
575 } elseif (!headers_sent()) {
576 // Clear output buffer
579 // Clear own output buffer
580 $GLOBALS['output'] = '';
583 setHttpStatus('302 Found');
585 // Load URL when headers are not sent
586 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $URL), false));
588 // Output error message
589 loadInclude('inc/header.php');
590 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
591 loadInclude('inc/footer.php');
594 // Shut the mailer down here
598 /************************************************************************
600 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
601 * $a_sort sortiert: *
603 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
604 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
605 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
606 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
607 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
609 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
610 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
611 * Sie, dass es doch nicht so schwer ist! :-) *
613 ************************************************************************/
614 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
616 while ($primary_key < count($a_sort)) {
617 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
618 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
620 if ($nums === false) {
621 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
622 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
623 } elseif ($key != $key2) {
624 // Sort numbers (E.g.: 9 < 10)
625 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
626 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
630 // We have found two different values, so let's sort whole array
631 foreach ($dummy as $sort_key => $sort_val) {
632 $t = $dummy[$sort_key][$key];
633 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
634 $dummy[$sort_key][$key2] = $t;
645 // Write back sorted array
651 // Deprecated : $length
654 function generateRandomCode ($length, $code, $userid, $DATA = '') {
655 // Build server string
656 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
659 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY');
660 if (isConfigEntrySet('secret_key')) $keys .= getEncryptSeperator().getSecretKey();
661 if (isConfigEntrySet('file_hash')) $keys .= getEncryptSeperator().getFileHash();
662 $keys .= getEncryptSeperator() . getDateFromPatchTime();
663 if (isConfigEntrySet('master_salt')) $keys .= getEncryptSeperator().getMasterSalt();
665 // Build string from misc data
666 $data = $code . getEncryptSeperator() . $userid . getEncryptSeperator() . $DATA;
668 // Add more additional data
669 if (isSessionVariableSet('u_hash')) $data .= getEncryptSeperator() . getSession('u_hash');
671 // Add referal id, language, theme and userid
672 $data .= getEncryptSeperator() . determineReferalId();
673 $data .= getEncryptSeperator() . getLanguage();
674 $data .= getEncryptSeperator() . getCurrentTheme();
675 $data .= getEncryptSeperator() . getMemberId();
677 // Calculate number for generating the code
678 $a = $code + getConfig('_ADD') - 1;
680 if (isConfigEntrySet('master_salt')) {
681 // Generate hash with master salt from modula of number with the prime number and other data
682 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, getMasterSalt());
684 // Create number from hash
685 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
687 // Generate hash with "hash of site key" 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, substr(sha1(getConfig('SITE_KEY')), 0, getSaltLength()));
690 // Create number from hash
691 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
694 // At least 10 numbers shall be secure enought!
695 $len = getConfig('code_length');
696 if ($len == '0') $len = $length;
697 if ($len == '0') $len = 10;
699 // Cut off requested counts of number
700 $return = substr(str_replace('.', '', $rcode), 0, $len);
702 // Done building code
706 // Does only allow numbers
707 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
708 // Filter all numbers out
709 $ret = preg_replace('/[^0123456789]/', '', $num);
712 if ($castValue === true) $ret = (double)$ret;
714 // Has the whole value changed?
715 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
717 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret=' . $ret . ', num='. $num);
724 // Creates a Uni* timestamp from given selection data and prefix
725 function createTimestampFromSelections ($prefix, $postData) {
726 // Initial return value
729 // Do we have a leap year?
731 $TEST = getYear() / 4;
734 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
735 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
737 // First add years...
738 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
741 $ret += $postData[$prefix . '_mo'] * 2628000;
744 $ret += $postData[$prefix . '_we'] * 604800;
747 $ret += $postData[$prefix . '_da'] * 86400;
750 $ret += $postData[$prefix . '_ho'] * 3600;
753 $ret += $postData[$prefix . '_mi'] * 60;
755 // And at last seconds...
756 $ret += $postData[$prefix . '_se'];
758 // Return calculated value
762 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
763 function createFancyTime ($stamp) {
764 // Get data array with years/months/weeks/days/...
765 $data = createTimeSelections($stamp, '', '', '', true);
767 foreach($data as $k => $v) {
769 // Value is greater than 0 "eval" data to return string
770 $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
775 // Do we have something there?
776 if (strlen($ret) > 0) {
777 // Remove leading commata and space
778 $ret = substr($ret, 2);
781 $ret = '0 {--_SECONDS--}';
784 // Return fancy time string
788 // Extract host from script name
789 function extractHostnameFromUrl (&$script) {
790 // Use default SERVER_URL by default... ;) So?
791 $url = getServerUrl();
793 // Is this URL valid?
794 if (substr($script, 0, 7) == 'http://') {
795 // Use the hostname from script URL as new hostname
796 $url = substr($script, 7);
797 $extract = explode('/', $url);
799 // Done extracting the URL :)
803 $host = str_replace('http://', '', $url);
804 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
806 // Generate relative URL
807 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
808 if (substr(strtolower($script), 0, 7) == 'http://') {
809 // But only if http:// is in front!
810 $script = substr($script, (strlen($url) + 7));
811 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
813 $script = substr($script, (strlen($url) + 8));
816 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
817 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
823 // Send a GET request
824 function sendGetRequest ($script, $data = array()) {
825 // Extract host name from script
826 $host = extractHostnameFromUrl($script);
829 $body = http_build_query($data, '', '&');
831 // Do we have a question-mark in the script?
832 if (strpos($script, '?') === false) {
833 // No, so first char must be question mark
843 // Remove trailed & to make it more conform
844 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
846 // Generate GET request header
847 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
848 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
849 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
850 if (isConfigEntrySet('FULL_VERSION')) {
851 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
853 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
855 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
856 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
857 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
858 $request .= 'Connection: close' . getConfig('HTTP_EOL');
859 $request .= getConfig('HTTP_EOL');
861 // Send the raw request
862 $response = sendRawRequest($host, $request);
864 // Return the result to the caller function
868 // Send a POST request
869 function sendPostRequest ($script, $postData) {
870 // Is postData an array?
871 if (!is_array($postData)) {
873 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
874 return array('', '', '');
877 // Extract host name from script
878 $host = extractHostnameFromUrl($script);
880 // Construct request body
881 $body = http_build_query($postData, '', '&');
883 // Generate POST request header
884 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
885 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
886 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
887 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
888 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
889 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
890 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
891 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
892 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
893 $request .= 'Connection: close' . getConfig('HTTP_EOL');
894 $request .= getConfig('HTTP_EOL');
899 // Send the raw request
900 $response = sendRawRequest($host, $request);
902 // Return the result to the caller function
906 // Sends a raw request to another host
907 function sendRawRequest ($host, $request) {
908 // Init errno and errdesc with 'all fine' values
909 $errno = '0'; $errdesc = '';
912 $response = array('', '', '');
914 // Default is not to use proxy
917 // Are proxy settins set?
924 loadIncludeOnce('inc/classes/resolver.class.php');
926 // Get resolver instance
927 $resolver = new HostnameResolver();
930 //* DEBUG: */ die('SCRIPT=' . $script);
931 if ($useProxy === true) {
932 // Resolve hostname into IP address
933 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
935 // Connect to host through proxy connection
936 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
938 // Resolve hostname into IP address
939 $ip = $resolver->resolveHostname($host);
941 // Connect to host directly
942 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
946 if (!is_resource($fp)) {
948 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
950 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
951 // Cannot set non-blocking mode or timeout
952 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
957 if ($useProxy === true) {
958 // Setup proxy tunnel
959 $response = setupProxyTunnel($host, $fp);
961 // If the response is invalid, abort
962 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
964 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
970 fwrite($fp, $request);
973 $start = microtime(true);
977 // Get info from stream
978 $info = stream_get_meta_data($fp);
980 // Is it timed out? 15 seconds is a really patient...
981 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
983 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
989 // Get line from stream
990 $line = fgets($fp, 128);
992 // Ignore empty lines because of non-blocking mode
994 // uslepp a little to avoid 100% CPU load
1001 // Add it to response
1002 $response[] = trim($line);
1008 // Time request if debug-mode is enabled
1009 if (isDebugModeEnabled()) {
1010 // Add debug message...
1011 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1014 // Skip first empty lines
1016 foreach ($resp as $idx => $line) {
1018 $line = trim($line);
1020 // Is this line empty?
1023 array_shift($response);
1025 // Abort on first non-empty line
1030 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1031 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1033 // Proxy agent found or something went wrong?
1034 if (!isset($response[0])) {
1035 // No response, maybe timeout
1036 $response = array('', '', '');
1037 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1038 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1039 // Proxy header detected, so remove two lines
1040 array_shift($response);
1041 array_shift($response);
1044 // Was the request successfull?
1045 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1046 // Not found / access forbidden
1047 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1048 $response = array('', '', '');
1055 // Sets up a proxy tunnel for given hostname and through resource
1056 function setupProxyTunnel ($host, $resource) {
1058 $response = array('', '', '');
1060 // Generate CONNECT request header
1061 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1062 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1064 // Use login data to proxy? (username at least!)
1065 if (getConfig('proxy_username') != '') {
1067 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1068 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1071 // Add last new-line
1072 $proxyTunnel .= getConfig('HTTP_EOL');
1073 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1076 fwrite($fp, $proxyTunnel);
1080 // No response received
1084 // Read the first line
1085 $resp = trim(fgets($fp, 10240));
1086 $respArray = explode(' ', $resp);
1087 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1088 // Invalid response!
1096 // Taken from www.php.net isInStringIgnoreCase() user comments
1097 function isEmailValid ($email) {
1098 // Check first part of email address
1099 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1102 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1105 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1107 // Return check result
1108 return preg_match($regex, $email);
1111 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1112 function isUrlValid ($URL, $compile=true) {
1113 // Trim URL a little
1114 $URL = trim(urldecode($URL));
1115 //* DEBUG: */ debugOutput($URL);
1117 // Compile some chars out...
1118 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1119 //* DEBUG: */ debugOutput($URL);
1121 // Check for the extension filter
1122 if (isExtensionActive('filter')) {
1123 // Use the extension's filter set
1124 return FILTER_VALIDATE_URL($URL, false);
1127 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1128 // https:// in front of the URLs
1129 return isUrlValidSimple($URL);
1132 // Generate a hash for extra-security for all passwords
1133 function generateHash ($plainText, $salt = '', $hash = true) {
1135 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
1137 // Is the required extension 'sql_patches' there and a salt is not given?
1138 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
1139 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
1140 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1141 if ($hash === true) {
1142 // Is plain password
1143 return md5($plainText);
1145 // Is already a hash
1150 // Do we miss an arry element here?
1151 if (!isConfigEntrySet('file_hash')) {
1153 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
1156 // When the salt is empty build a new one, else use the first x configured characters as the salt
1158 // Build server string for more entropy
1159 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
1162 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
1165 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
1167 // Calculate number for generating the code
1168 $a = time() + getConfig('_ADD') - 1;
1170 // Generate SHA1 sum from modula of number and the prime number
1171 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a);
1172 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
1173 $sha1 = scrambleString($sha1);
1174 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
1175 //* DEBUG: */ $sha1b = descrambleString($sha1);
1176 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
1178 // Generate the password salt string
1179 $salt = substr($sha1, 0, getSaltLength());
1180 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
1183 //* DEBUG: */ debugOutput('salt=' . $salt);
1184 $salt = substr($salt, 0, getSaltLength());
1185 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
1187 // Sanity check on salt
1188 if (strlen($salt) != getSaltLength()) {
1190 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
1194 // Generate final hash (for debug output)
1195 $finalHash = $salt . sha1($salt . $plainText);
1198 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
1204 // Scramble a string
1205 function scrambleString ($str) {
1209 // Final check, in case of failture it will return unscrambled string
1210 if (strlen($str) > 40) {
1211 // The string is to long
1213 } elseif (strlen($str) == 40) {
1215 $scrambleNums = explode(':', getPassScramble());
1217 // Generate new numbers
1218 $scrambleNums = explode(':', genScrambleString(strlen($str)));
1221 // Compare both lengths and abort if different
1222 if (strlen($str) != count($scrambleNums)) return $str;
1224 // Scramble string here
1225 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
1226 for ($idx = 0; $idx < strlen($str); $idx++) {
1227 // Get char on scrambled position
1228 $char = substr($str, $scrambleNums[$idx], 1);
1230 // Add it to final output string
1231 $scrambled .= $char;
1234 // Return scrambled string
1235 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
1239 // De-scramble a string scrambled by scrambleString()
1240 function descrambleString ($str) {
1241 // Scramble only 40 chars long strings
1242 if (strlen($str) != 40) return $str;
1244 // Load numbers from config
1245 $scrambleNums = explode(':', getPassScramble());
1248 if (count($scrambleNums) != 40) return $str;
1250 // Begin descrambling
1251 $orig = str_repeat(' ', 40);
1252 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
1253 for ($idx = 0; $idx < 40; $idx++) {
1254 $char = substr($str, $idx, 1);
1255 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1258 // Return scrambled string
1259 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1263 // Generated a "string" for scrambling
1264 function genScrambleString ($len) {
1265 // Prepare array for the numbers
1266 $scrambleNumbers = array();
1268 // First we need to setup randomized numbers from 0 to 31
1269 for ($idx = 0; $idx < $len; $idx++) {
1271 $rand = mt_rand(0, ($len -1));
1273 // Check for it by creating more numbers
1274 while (array_key_exists($rand, $scrambleNumbers)) {
1275 $rand = mt_rand(0, ($len -1));
1279 $scrambleNumbers[$rand] = $rand;
1282 // So let's create the string for storing it in database
1283 $scrambleString = implode(':', $scrambleNumbers);
1284 return $scrambleString;
1287 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1288 function encodeHashForCookie ($passHash) {
1289 // Return vanilla password hash
1292 // Is a secret key and master salt already initialized?
1293 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1294 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1295 // Only calculate when the secret key is generated
1296 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1297 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1298 // Both keys must have same length so return unencrypted
1299 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1303 $newHash = ''; $start = 9;
1304 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1305 for ($idx = 0; $idx < 20; $idx++) {
1306 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1307 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1308 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1309 $mod = dechex($idx);
1310 if ($part1 > $part2) {
1311 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1312 } elseif ($part2 > $part1) {
1313 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1315 $mod = substr($mod, 0, 2);
1316 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1317 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1318 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1323 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1324 $ret = generateHash($newHash, getMasterSalt());
1328 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1332 // Fix "deleted" cookies
1333 function fixDeletedCookies ($cookies) {
1334 // Is this an array with entries?
1335 if ((is_array($cookies)) && (count($cookies) > 0)) {
1336 // Then check all cookies if they are marked as deleted!
1337 foreach ($cookies as $cookieName) {
1338 // Is the cookie set to "deleted"?
1339 if (getSession($cookieName) == 'deleted') {
1340 setSession($cookieName, '');
1346 // Checks if a given apache module is loaded
1347 function isApacheModuleLoaded ($apacheModule) {
1348 // Check it and return result
1349 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1352 // Get current theme name
1353 function getCurrentTheme () {
1354 // The default theme is 'default'... ;-)
1357 // Do we have ext-theme installed and active?
1358 if (isExtensionActive('theme')) {
1359 // Call inner method
1360 $ret = getActualTheme();
1363 // Return theme value
1367 // Generates an error code from given account status
1368 function generateErrorCodeFromUserStatus ($status = '') {
1369 // If no status is provided, use the default, cached
1370 if ((empty($status)) && (isMember())) {
1372 $status = getUserData('status');
1375 // Default error code if unknown account status
1376 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1378 // Generate constant name
1379 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1381 // Is the constant there?
1382 if (isCodeSet($codeName)) {
1384 $errorCode = getCode($codeName);
1387 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1390 // Return error code
1394 // Back-ported from the new ship-simu engine. :-)
1395 function debug_get_printable_backtrace () {
1397 $backtrace = '<ol>';
1399 // Get and prepare backtrace for output
1400 $backtraceArray = debug_backtrace();
1401 foreach ($backtraceArray as $key => $trace) {
1402 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1403 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1404 if (!isset($trace['args'])) $trace['args'] = array();
1405 $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>';
1409 $backtrace .= '</ol>';
1411 // Return the backtrace
1415 // A mail-able backtrace
1416 function debug_get_mailable_backtrace () {
1420 // Get and prepare backtrace for output
1421 $backtraceArray = debug_backtrace();
1422 foreach ($backtraceArray as $key => $trace) {
1423 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1424 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1425 if (!isset($trace['args'])) $trace['args'] = array();
1426 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1429 // Return the backtrace
1433 // Generates a ***weak*** seed
1434 function generateSeed () {
1435 return microtime(true) * 100000;
1438 // Converts a message code to a human-readable message
1439 function getMessageFromErrorCode ($code) {
1443 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1444 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
1445 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1446 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1447 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1448 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1449 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1450 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1451 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1452 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1453 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1454 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1455 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1456 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1457 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1458 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1459 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1460 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1461 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1462 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1463 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1464 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1465 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1466 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1467 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1468 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1469 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1470 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1471 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1473 case getCode('ERROR_MAILID'):
1474 if (isExtensionActive('mailid', true)) {
1475 $message = '{--ERROR_CONFIRMING_MAIL--}';
1477 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', 'mailid');
1481 case getCode('EXTENSION_PROBLEM'):
1482 if (isGetRequestParameterSet('ext')) {
1483 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1485 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1489 case getCode('URL_TLOCK'):
1490 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1491 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1492 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1494 // Load timestamp from last order
1495 list($timestamp) = SQL_FETCHROW($result);
1498 SQL_FREERESULT($result);
1500 // Translate it for templates
1501 $timestamp = generateDateTime($timestamp, 1);
1503 // Calculate hours...
1504 $STD = round(getConfig('url_tlock') / 60 / 60);
1507 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
1510 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
1512 // Finally contruct the message
1513 // @TODO Rewrite this old lost code to a template
1514 $message = '{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ' . $STD . '
1515 {--_HOURS--}, ' . $MIN . ' {--_MINUTES--} {--_AND--} ' . $SEC . ' {--_SECONDS--}<br />
1516 {--MEMBER_LAST_TLOCK--}: ' . $timestamp;
1520 // Missing/invalid code
1521 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1524 logDebugMessage(__FUNCTION__, __LINE__, $message);
1528 // Return the message
1532 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1533 function isUrlValidSimple ($url) {
1535 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1537 // Allows http and https
1538 $http = "(http|https)+(:\/\/)";
1540 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1541 // Test double-domains (e.g. .de.vu)
1542 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1544 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1546 $dir = "((/)+([-_\.[:alnum:]])+)*";
1548 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1549 // ... and the string after and including question character
1550 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1551 // Pattern for URLs like http://url/dir/doc.html?var=value
1552 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1553 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1554 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1555 // Pattern for URLs like http://url/dir/?var=value
1556 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1557 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1558 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1559 // Pattern for URLs like http://url/dir/page.ext
1560 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1561 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1562 $pattern['ipdp'] = $http . $ip . $dir . $page;
1563 // Pattern for URLs like http://url/dir
1564 $pattern['d1d'] = $http . $domain1 . $dir;
1565 $pattern['d2d'] = $http . $domain2 . $dir;
1566 $pattern['ipd'] = $http . $ip . $dir;
1567 // Pattern for URLs like http://url/?var=value
1568 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1569 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1570 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1571 // Pattern for URLs like http://url?var=value
1572 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1573 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1574 $pattern['ipg12'] = $http . $ip . $getstring1;
1576 // Test all patterns
1578 foreach ($pattern as $key => $pat) {
1580 if (isDebugRegularExpressionEnabled()) {
1581 // @TODO Are these convertions still required?
1582 $pat = str_replace('.', '\.', $pat);
1583 $pat = str_replace('@', '\@', $pat);
1584 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1587 // Check if expression matches
1588 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1591 if ($reg === true) break;
1594 // Return true/false
1598 // Wtites data to a config.php-style file
1599 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1600 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1601 // Initialize some variables
1607 // Is the file there and read-/write-able?
1608 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1609 $search = 'CFG: ' . $comment;
1610 $tmp = $FQFN . '.tmp';
1612 // Open the source file
1613 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1615 // Is the resource valid?
1616 if (is_resource($fp)) {
1617 // Open temporary file
1618 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1620 // Is the resource again valid?
1621 if (is_resource($fp_tmp)) {
1622 // Mark temporary file as readable
1623 $GLOBALS['file_readable'][$tmp] = true;
1626 while (!feof($fp)) {
1627 // Read from source file
1628 $line = fgets ($fp, 1024);
1630 if (strpos($line, $search) > -1) {
1636 if ($next === $seek) {
1638 $line = $prefix . $DATA . $suffix . "\n";
1644 // Write to temp file
1645 fwrite($fp_tmp, $line);
1651 // Finished writing tmp file
1655 // Close source file
1658 if (($done === true) && ($found === true)) {
1659 // Copy back tmp file and delete tmp :-)
1660 copyFileVerified($tmp, $FQFN, 0644);
1661 return removeFile($tmp);
1662 } elseif ($found === false) {
1663 outputHtml('<strong>CHANGE:</strong> 404!');
1665 outputHtml('<strong>TMP:</strong> UNDONE!');
1669 // File not found, not readable or writeable
1670 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1673 // An error was detected!
1676 // Send notification to admin
1677 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
1678 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1680 sendAdminsEmails($subject, $templateName, $content, $userid);
1682 // Send out out-dated way
1683 $message = loadEmailTemplate($templateName, $content, $userid);
1684 sendAdminEmails($subject, $message);
1688 // Debug message logger
1689 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1690 // Is debug mode enabled?
1691 if ((isDebugModeEnabled()) || ($force === true)) {
1693 $message = str_replace("\r", '', str_replace("\n", '', $message));
1695 // Log this message away
1696 $fp = fopen(getCachePath() . 'debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write logfile debug.log!');
1697 fwrite($fp, generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
1702 // Handle extra values
1703 function handleExtraValues ($filterFunction, $value, $extraValue) {
1704 // Default is the value itself
1707 // Do we have a special filter function?
1708 if (!empty($filterFunction)) {
1709 // Does the filter function exist?
1710 if (function_exists($filterFunction)) {
1711 // Do we have extra parameters here?
1712 if (!empty($extraValue)) {
1713 // Put both parameters in one new array by default
1714 $args = array($value, $extraValue);
1716 // If we have an array simply use it and pre-extend it with our value
1717 if (is_array($extraValue)) {
1718 // Make the new args array
1719 $args = merge_array(array($value), $extraValue);
1722 // Call the multi-parameter call-back
1723 $ret = call_user_func_array($filterFunction, $args);
1725 // One parameter call
1726 $ret = call_user_func($filterFunction, $value);
1735 // Converts timestamp selections into a timestamp
1736 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1737 // Init test variable
1741 // Get last three chars
1742 $test = substr($id, -3);
1744 // Improved way of checking! :-)
1745 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1746 // Found a multi-selection for timings?
1747 $test = substr($id, 0, -3);
1748 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)) {
1749 // Generate timestamp
1750 $postData[$test] = createTimestampFromSelections($test, $postData);
1751 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1752 $GLOBALS['skip_config'][$test] = true;
1754 // Remove data from array
1755 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1756 unset($postData[$test . '_' . $rem]);
1767 // Reverts the german decimal comma into Computer decimal dot
1768 function convertCommaToDot ($str) {
1769 // Default float is not a float... ;-)
1772 // Which language is selected?
1773 switch (getLanguage()) {
1774 case 'de': // German language
1775 // Remove german thousand dots first
1776 $str = str_replace('.', '', $str);
1778 // Replace german commata with decimal dot and cast it
1779 $float = (float)str_replace(',', '.', $str);
1782 default: // US and so on
1783 // Remove thousand dots first and cast
1784 $float = (float)str_replace(',', '', $str);
1792 // Handle menu-depending failed logins and return the rendered content
1793 function handleLoginFailures ($accessLevel) {
1794 // Default output is empty ;-)
1797 // Is the session data set?
1798 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1799 // Ignore zero values
1800 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1801 // Non-guest has login failures found, get both data and prepare it for template
1802 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1804 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1805 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1809 $OUT = loadTemplate('login_failures', true, $content);
1812 // Reset session data
1813 setSession('mailer_' . $accessLevel . '_failures', '');
1814 setSession('mailer_' . $accessLevel . '_last_failure', '');
1817 // Return rendered content
1822 function rebuildCache ($cache, $inc = '', $force = false) {
1824 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1826 // Shall I remove the cache file?
1827 if (isCacheInstanceValid()) {
1829 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1831 $GLOBALS['cache_instance']->removeCacheFile($force);
1834 // Include file given?
1837 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
1839 // Is the include there?
1840 if (isIncludeReadable($inc)) {
1841 // And rebuild it from scratch
1842 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1845 // Include not found!
1846 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1852 // Determines the real remote address
1853 function determineRealRemoteAddress () {
1854 // Is a proxy in use?
1855 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1857 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1858 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
1859 // Yet, another proxy
1860 $address = $_SERVER['HTTP_CLIENT_IP'];
1862 // The regular address when no proxy was used
1863 $address = $_SERVER['REMOTE_ADDR'];
1866 // This strips out the real address from proxy output
1867 if (strstr($address, ',')) {
1868 $addressArray = explode(',', $address);
1869 $address = $addressArray[0];
1872 // Return the result
1876 // Adds a bonus mail to the queue
1877 // This is a high-level function!
1878 function addNewBonusMail ($data, $mode = '', $output=true) {
1879 // Use mode from data if not set and availble ;-)
1880 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
1882 // Generate receiver list
1883 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1886 if (!empty($receiver)) {
1887 // Add bonus mail to queue
1888 addBonusMailToQueue(
1900 // Mail inserted into bonus pool
1901 if ($output === true) {
1902 loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
1904 } elseif ($output === true) {
1905 // More entered than can be reached!
1906 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
1909 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1913 // Determines referal id and sets it
1914 function determineReferalId () {
1915 // Skip this in non-html-mode and outside ref.php
1916 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
1918 // Check if refid is set
1919 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1921 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1922 // The variable user comes from the click-counter script click.php and we only accept this here
1923 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1924 } elseif (isPostRequestParameterSet('refid')) {
1925 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
1926 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1927 } elseif (isGetRequestParameterSet('refid')) {
1928 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
1929 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1930 } elseif (isGetRequestParameterSet('ref')) {
1931 // Set refid=ref (the referal link uses such variable)
1932 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1933 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1934 // Set session refid als global
1935 $GLOBALS['refid'] = bigintval(getSession('refid'));
1936 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (isRandomReferalIdEnabled())) {
1937 // Select a random user which has confirmed enougth mails
1938 $GLOBALS['refid'] = determineRandomReferalId();
1939 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getConfig('def_refid')))) {
1940 // Set default refid as refid in URL
1941 $GLOBALS['refid'] = getConfig('def_refid');
1943 // No default id when sql_patches is not installed or none set
1944 $GLOBALS['refid'] = '0';
1947 // Set cookie when default refid > 0
1948 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isConfigEntrySet('def_refid')) && (isValidUserId(getConfig('def_refid'))))) {
1949 // Default is not found
1952 // Do we have nickname or userid set?
1953 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1954 // Nickname in URL, so load the id
1955 $found = fetchUserData($GLOBALS['refid'], 'nickname');
1956 } elseif ($GLOBALS['refid'] > 0) {
1957 // Direct userid entered
1958 $found = fetchUserData($GLOBALS['refid']);
1961 // Is the record valid?
1962 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
1963 // No, then reset referal id
1964 $GLOBALS['refid'] = getConfig('def_refid');
1968 setSession('refid', $GLOBALS['refid']);
1971 // Return determined refid
1972 return $GLOBALS['refid'];
1975 // Enables the reset mode and runs it
1976 function doReset () {
1977 // Enable the reset mode
1978 $GLOBALS['reset_enabled'] = true;
1981 runFilterChain('reset');
1984 // Our shutdown-function
1985 function shutdown () {
1986 // Call the filter chain 'shutdown'
1987 runFilterChain('shutdown', null);
1989 // Check if not in installation phase and the link is up
1990 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1992 SQL_CLOSE(__FUNCTION__, __LINE__);
1993 } elseif (!isInstallationPhase()) {
1995 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
1998 // Stop executing here
2003 function initMemberId () {
2004 $GLOBALS['member_id'] = '0';
2007 // Setter for member id
2008 function setMemberId ($memberid) {
2009 // We should not set member id to zero
2010 if ($memberid == '0') debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
2013 $GLOBALS['member_id'] = bigintval($memberid);
2016 // Getter for member id or returns zero
2017 function getMemberId () {
2018 // Default member id
2021 // Is the member id set?
2022 if (isMemberIdSet()) {
2024 $memberid = $GLOBALS['member_id'];
2031 // Checks ether the member id is set
2032 function isMemberIdSet () {
2033 return (isset($GLOBALS['member_id']));
2036 // Setter for extra title
2037 function setExtraTitle ($extraTitle) {
2038 $GLOBALS['extra_title'] = $extraTitle;
2041 // Getter for extra title
2042 function getExtraTitle () {
2043 // Is the extra title set?
2044 if (!isExtraTitleSet()) {
2045 // No, then abort here
2046 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
2050 return $GLOBALS['extra_title'];
2053 // Checks if the extra title is set
2054 function isExtraTitleSet () {
2055 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
2058 // Reads a directory recursively by default and searches for files not matching
2059 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
2060 // a whole directory.
2061 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
2062 // Add default entries we should exclude
2063 $excludeArray[] = '.';
2064 $excludeArray[] = '..';
2065 $excludeArray[] = '.svn';
2066 $excludeArray[] = '.htaccess';
2068 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
2073 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
2076 while ($baseFile = readdir($dirPointer)) {
2077 // Exclude '.', '..' and entries in $excludeArray automatically
2078 if (in_array($baseFile, $excludeArray, true)) {
2080 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
2084 // Construct include filename and FQFN
2085 $fileName = $baseDir . $baseFile;
2086 $FQFN = getPath() . $fileName;
2088 // Remove double slashes
2089 $FQFN = str_replace('//', '/', $FQFN);
2091 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
2092 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
2093 // These Lines are only for debugging!!
2094 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
2095 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
2096 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
2102 // Skip also files with non-matching prefix genericly
2103 if (($recursive === true) && (isDirectory($FQFN))) {
2104 // Is a redirectory so read it as well
2105 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
2107 // And skip further processing
2109 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
2111 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
2113 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
2114 // Skip wrong suffix as well
2115 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
2117 } elseif (!isFileReadable($FQFN)) {
2118 // Not readable so skip it
2119 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
2123 // Is the file a PHP script or other?
2124 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
2125 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
2126 // Is this a valid include file?
2127 if ($extension == '.php') {
2128 // Remove both for extension name
2129 $extName = substr($baseFile, strlen($prefix), -4);
2131 // Is the extension valid and active?
2132 if (isExtensionNameValid($extName)) {
2133 // Then add this file
2134 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
2135 $files[] = $fileName;
2137 // Add non-extension files as well
2138 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
2139 if ($addBaseDir === true) {
2140 $files[] = $fileName;
2142 $files[] = $baseFile;
2146 // We found .php file but should not search for them, why?
2147 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
2149 } elseif (substr($baseFile, -4, 4) == $extension) {
2150 // Other, generic file found
2151 $files[] = $fileName;
2156 closedir($dirPointer);
2161 // Return array with include files
2162 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
2166 // Maps a module name into a database table name
2167 function mapModuleToTable ($moduleName) {
2168 // Map only these, still lame code...
2169 switch ($moduleName) {
2170 // 'index' is the guest's menu
2171 case 'index': $moduleName = 'guest'; break;
2172 // ... and 'login' the member's menu
2173 case 'login': $moduleName = 'member'; break;
2174 // Anything else will not be mapped, silently.
2181 // Add SQL debug data to array for later output
2182 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
2183 // Do we have cache?
2184 if (!isset($GLOBALS['debug_sql_available'])) {
2185 // Check it and cache it in $GLOBALS
2186 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
2189 // Don't execute anything here if we don't need or ext-other is missing
2190 if ($GLOBALS['debug_sql_available'] === false) {
2194 // Already executed?
2195 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
2196 // Then abort here, we don't need to profile a query twice
2200 // Remeber this as profiled (or not, but we don't care here)
2201 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
2205 'num_rows' => SQL_NUMROWS($result),
2206 'affected' => SQL_AFFECTEDROWS(),
2207 'sql_str' => $sqlString,
2208 'timing' => $timing,
2209 'file' => basename($F),
2214 $GLOBALS['debug_sqls'][] = $record;
2217 // Initializes the cache instance
2218 function initCacheInstance () {
2219 // Load include for CacheSystem class
2220 loadIncludeOnce('inc/classes/cachesystem.class.php');
2222 // Initialize cache system only when it's needed
2223 $GLOBALS['cache_instance'] = new CacheSystem();
2224 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
2225 // Failed to initialize cache sustem
2226 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2230 // Getter for message from array or raw message
2231 function getMessageFromIndexedArray ($message, $pos, $array) {
2232 // Check if the requested message was found in array
2233 if (isset($array[$pos])) {
2234 // ... if yes then use it!
2235 $ret = $array[$pos];
2237 // ... else use default message
2245 // Convert ';' to ', ' for e.g. receiver list
2246 function convertReceivers ($old) {
2247 return str_replace(';', ', ', $old);
2250 // Get a module from filename and access level
2251 function getModuleFromFileName ($file, $accessLevel) {
2252 // Default is 'invalid';
2253 $modCheck = 'invalid';
2255 // @TODO This is still very static, rewrite it somehow
2256 switch ($accessLevel) {
2258 $modCheck = 'admin';
2264 $modCheck = getModule();
2267 default: // Unsupported file name / access level
2268 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2276 // Encodes an URL for adding session id, etc.
2277 function encodeUrl ($url, $outputMode = '0') {
2278 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2279 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) return $url;
2281 // Do we have a valid session?
2282 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2284 // Determine right seperator
2285 $seperator = '&';
2286 if (strpos($url, '?') === false) {
2289 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2295 if (session_id() != '') {
2296 $url .= $seperator . session_name() . '=' . session_id();
2301 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2303 $url = '{?URL?}/' . $url;
2310 // Simple check for spider
2311 function isSpider () {
2312 // Get the UA and trim it down
2313 $userAgent = trim(strtolower(detectUserAgent(true)));
2315 // It should not be empty, if so it is better a spider/bot
2316 if (empty($userAgent)) return true;
2319 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2322 // Function to search for the last modified file
2323 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2325 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2326 // Does it match what we are looking for? (We skip a lot files already!)
2327 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2328 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2330 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2331 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2333 // Walk through all entries
2334 foreach ($ds as $d) {
2335 // Generate proper FQFN
2336 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2338 // Is it a file and readable?
2339 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2340 if (isFileReadable($FQFN)) {
2341 // $FQFN is a readable file so extract the requested data from it
2342 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2343 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2345 // Is the file more recent?
2346 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2347 // This file is newer as the file before
2348 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2349 $last_changed['path_name'] = $FQFN;
2350 $last_changed[$lookFor] = $check;
2354 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2359 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2360 function handleFieldWithBraces ($field) {
2361 // Are there braces [] at the end?
2362 if (substr($field, -2, 2) == '[]') {
2363 // Try to find one and replace it. I do it this way to allow easy
2364 // extending of this code.
2365 foreach (array('admin_list_builder_id_value') as $key) {
2366 // Is the cache entry set?
2367 if (isset($GLOBALS[$key])) {
2369 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2381 // Converts a userid so it can be used in SQL queries
2382 function makeDatabaseUserId ($userid) {
2383 // Is it a valid username?
2384 if (isValidUserId($userid)) {
2386 $userid = bigintval($userid);
2388 // Is not valid or zero
2396 //-----------------------------------------------------------------------------
2397 // Automatically re-created functions, all taken from user comments on www.php.net
2398 //-----------------------------------------------------------------------------
2400 if (!function_exists('html_entity_decode')) {
2401 // Taken from documentation on www.php.net
2402 function html_entity_decode ($string) {
2403 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2404 $trans_tbl = array_flip($trans_tbl);
2405 return strtr($string, $trans_tbl);
2409 if (!function_exists('http_build_query')) {
2410 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
2411 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
2413 foreach ((array)$data as $k => $v) {
2414 if (is_int($k) && $prefix != null) {
2415 $k = urlencode($prefix . $k);
2418 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
2420 if (is_array($v) || is_object($v)) {
2421 array_push($ret, http_build_query($v, '', $sep, $k));
2423 array_push($ret, $k.'='.urlencode($v));
2427 if (empty($sep)) $sep = ini_get('arg_separator.output');
2429 return implode($sep, $ret);