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'] = '';
589 setHttpStatus('302 Found');
591 // Load URL when headers are not sent
592 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $URL), false));
594 // Output error message
595 loadInclude('inc/header.php');
596 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
597 loadInclude('inc/footer.php');
600 // Shut the mailer down here
604 /************************************************************************
606 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
607 * $a_sort sortiert: *
609 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
610 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
611 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
612 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
613 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
615 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
616 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
617 * Sie, dass es doch nicht so schwer ist! :-) *
619 ************************************************************************/
620 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
622 while ($primary_key < count($a_sort)) {
623 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
624 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
626 if ($nums === false) {
627 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
628 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
629 } elseif ($key != $key2) {
630 // Sort numbers (E.g.: 9 < 10)
631 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
632 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
636 // We have found two different values, so let's sort whole array
637 foreach ($dummy as $sort_key => $sort_val) {
638 $t = $dummy[$sort_key][$key];
639 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
640 $dummy[$sort_key][$key2] = $t;
651 // Write back sorted array
657 // Deprecated : $length
660 function generateRandomCode ($length, $code, $userid, $DATA = '') {
661 // Build server string
662 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
665 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY');
666 if (isConfigEntrySet('secret_key')) $keys .= getEncryptSeperator().getSecretKey();
667 if (isConfigEntrySet('file_hash')) $keys .= getEncryptSeperator().getFileHash();
668 $keys .= getEncryptSeperator() . getDateFromPatchTime();
669 if (isConfigEntrySet('master_salt')) $keys .= getEncryptSeperator().getMasterSalt();
671 // Build string from misc data
672 $data = $code . getEncryptSeperator() . $userid . getEncryptSeperator() . $DATA;
674 // Add more additional data
675 if (isSessionVariableSet('u_hash')) $data .= getEncryptSeperator() . getSession('u_hash');
677 // Add referal id, language, theme and userid
678 $data .= getEncryptSeperator() . determineReferalId();
679 $data .= getEncryptSeperator() . getLanguage();
680 $data .= getEncryptSeperator() . getCurrentTheme();
681 $data .= getEncryptSeperator() . getMemberId();
683 // Calculate number for generating the code
684 $a = $code + getConfig('_ADD') - 1;
686 if (isConfigEntrySet('master_salt')) {
687 // Generate hash with master salt from modula of number with the prime number and other data
688 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, getMasterSalt());
690 // Create number from hash
691 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
693 // Generate hash with "hash of site key" from modula of number with the prime number and other data
694 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, substr(sha1(getConfig('SITE_KEY')), 0, getSaltLength()));
696 // Create number from hash
697 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
700 // At least 10 numbers shall be secure enought!
701 $len = getConfig('code_length');
702 if ($len == '0') $len = $length;
703 if ($len == '0') $len = 10;
705 // Cut off requested counts of number
706 $return = substr(str_replace('.', '', $rcode), 0, $len);
708 // Done building code
712 // Does only allow numbers
713 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
714 // Filter all numbers out
715 $ret = preg_replace('/[^0123456789]/', '', $num);
718 if ($castValue === true) $ret = (double)$ret;
720 // Has the whole value changed?
721 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
723 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret=' . $ret . ', num='. $num);
730 // Creates a Uni* timestamp from given selection data and prefix
731 function createTimestampFromSelections ($prefix, $postData) {
732 // Initial return value
735 // Do we have a leap year?
737 $TEST = getYear() / 4;
740 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
741 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
743 // First add years...
744 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
747 $ret += $postData[$prefix . '_mo'] * 2628000;
750 $ret += $postData[$prefix . '_we'] * 604800;
753 $ret += $postData[$prefix . '_da'] * 86400;
756 $ret += $postData[$prefix . '_ho'] * 3600;
759 $ret += $postData[$prefix . '_mi'] * 60;
761 // And at last seconds...
762 $ret += $postData[$prefix . '_se'];
764 // Return calculated value
768 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
769 function createFancyTime ($stamp) {
770 // Get data array with years/months/weeks/days/...
771 $data = createTimeSelections($stamp, '', '', '', true);
773 foreach($data as $k => $v) {
775 // Value is greater than 0 "eval" data to return string
776 $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
781 // Do we have something there?
782 if (strlen($ret) > 0) {
783 // Remove leading commata and space
784 $ret = substr($ret, 2);
787 $ret = '0 {--_SECONDS--}';
790 // Return fancy time string
794 // Extract host from script name
795 function extractHostnameFromUrl (&$script) {
796 // Use default SERVER_URL by default... ;) So?
797 $url = getServerUrl();
799 // Is this URL valid?
800 if (substr($script, 0, 7) == 'http://') {
801 // Use the hostname from script URL as new hostname
802 $url = substr($script, 7);
803 $extract = explode('/', $url);
805 // Done extracting the URL :)
809 $host = str_replace('http://', '', $url);
810 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
812 // Generate relative URL
813 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
814 if (substr(strtolower($script), 0, 7) == 'http://') {
815 // But only if http:// is in front!
816 $script = substr($script, (strlen($url) + 7));
817 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
819 $script = substr($script, (strlen($url) + 8));
822 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
823 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
829 // Send a GET request
830 function sendGetRequest ($script, $data = array()) {
831 // Extract host name from script
832 $host = extractHostnameFromUrl($script);
835 $body = http_build_query($data, '', '&');
837 // There should be data, else we don't need to extend $script with $body
839 // Do we have a question-mark in the script?
840 if (strpos($script, '?') === false) {
841 // No, so first char must be question mark
851 // Remove trailed & to make it more conform
852 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
855 // Generate GET request header
856 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
857 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
858 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
859 if (isConfigEntrySet('FULL_VERSION')) {
860 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
862 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
864 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
865 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
866 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
867 $request .= 'Connection: close' . getConfig('HTTP_EOL');
868 $request .= getConfig('HTTP_EOL');
870 // Send the raw request
871 $response = sendRawRequest($host, $request);
873 // Return the result to the caller function
877 // Send a POST request
878 function sendPostRequest ($script, $postData) {
879 // Is postData an array?
880 if (!is_array($postData)) {
882 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
883 return array('', '', '');
886 // Extract host name from script
887 $host = extractHostnameFromUrl($script);
889 // Construct request body
890 $body = http_build_query($postData, '', '&');
892 // Generate POST request header
893 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
894 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
895 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
896 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
897 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
898 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
899 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
900 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
901 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
902 $request .= 'Connection: close' . getConfig('HTTP_EOL');
903 $request .= getConfig('HTTP_EOL');
908 // Send the raw request
909 $response = sendRawRequest($host, $request);
911 // Return the result to the caller function
915 // Sends a raw request to another host
916 function sendRawRequest ($host, $request) {
917 // Init errno and errdesc with 'all fine' values
918 $errno = '0'; $errdesc = '';
921 $response = array('', '', '');
923 // Default is not to use proxy
926 // Are proxy settins set?
933 loadIncludeOnce('inc/classes/resolver.class.php');
935 // Get resolver instance
936 $resolver = new HostnameResolver();
939 //* DEBUG: */ die('SCRIPT=' . $script);
940 if ($useProxy === true) {
941 // Resolve hostname into IP address
942 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
944 // Connect to host through proxy connection
945 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
947 // Resolve hostname into IP address
948 $ip = $resolver->resolveHostname($host);
950 // Connect to host directly
951 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
955 if (!is_resource($fp)) {
957 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
959 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
960 // Cannot set non-blocking mode or timeout
961 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
966 if ($useProxy === true) {
967 // Setup proxy tunnel
968 $response = setupProxyTunnel($host, $fp);
970 // If the response is invalid, abort
971 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
973 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
979 fwrite($fp, $request);
982 $start = microtime(true);
986 // Get info from stream
987 $info = stream_get_meta_data($fp);
989 // Is it timed out? 15 seconds is a really patient...
990 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
992 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
998 // Get line from stream
999 $line = fgets($fp, 128);
1001 // Ignore empty lines because of non-blocking mode
1003 // uslepp a little to avoid 100% CPU load
1010 // Add it to response
1011 $response[] = trim($line);
1017 // Time request if debug-mode is enabled
1018 if (isDebugModeEnabled()) {
1019 // Add debug message...
1020 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1023 // Skip first empty lines
1025 foreach ($resp as $idx => $line) {
1027 $line = trim($line);
1029 // Is this line empty?
1032 array_shift($response);
1034 // Abort on first non-empty line
1039 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1040 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1042 // Proxy agent found or something went wrong?
1043 if (!isset($response[0])) {
1044 // No response, maybe timeout
1045 $response = array('', '', '');
1046 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1047 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1048 // Proxy header detected, so remove two lines
1049 array_shift($response);
1050 array_shift($response);
1053 // Was the request successfull?
1054 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1055 // Not found / access forbidden
1056 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1057 $response = array('', '', '');
1064 // Sets up a proxy tunnel for given hostname and through resource
1065 function setupProxyTunnel ($host, $resource) {
1067 $response = array('', '', '');
1069 // Generate CONNECT request header
1070 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1071 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1073 // Use login data to proxy? (username at least!)
1074 if (getConfig('proxy_username') != '') {
1076 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1077 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1080 // Add last new-line
1081 $proxyTunnel .= getConfig('HTTP_EOL');
1082 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1085 fwrite($fp, $proxyTunnel);
1089 // No response received
1093 // Read the first line
1094 $resp = trim(fgets($fp, 10240));
1095 $respArray = explode(' ', $resp);
1096 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1097 // Invalid response!
1105 // Taken from www.php.net isInStringIgnoreCase() user comments
1106 function isEmailValid ($email) {
1107 // Check first part of email address
1108 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1111 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1114 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1116 // Return check result
1117 return preg_match($regex, $email);
1120 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1121 function isUrlValid ($URL, $compile=true) {
1122 // Trim URL a little
1123 $URL = trim(urldecode($URL));
1124 //* DEBUG: */ debugOutput($URL);
1126 // Compile some chars out...
1127 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1128 //* DEBUG: */ debugOutput($URL);
1130 // Check for the extension filter
1131 if (isExtensionActive('filter')) {
1132 // Use the extension's filter set
1133 return FILTER_VALIDATE_URL($URL, false);
1136 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1137 // https:// in front of the URLs
1138 return isUrlValidSimple($URL);
1141 // Generate a hash for extra-security for all passwords
1142 function generateHash ($plainText, $salt = '', $hash = true) {
1144 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
1146 // Is the required extension 'sql_patches' there and a salt is not given?
1147 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
1148 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
1149 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1150 if ($hash === true) {
1151 // Is plain password
1152 return md5($plainText);
1154 // Is already a hash
1159 // Do we miss an arry element here?
1160 if (!isConfigEntrySet('file_hash')) {
1162 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
1165 // When the salt is empty build a new one, else use the first x configured characters as the salt
1167 // Build server string for more entropy
1168 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
1171 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
1174 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
1176 // Calculate number for generating the code
1177 $a = time() + getConfig('_ADD') - 1;
1179 // Generate SHA1 sum from modula of number and the prime number
1180 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a);
1181 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
1182 $sha1 = scrambleString($sha1);
1183 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
1184 //* DEBUG: */ $sha1b = descrambleString($sha1);
1185 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
1187 // Generate the password salt string
1188 $salt = substr($sha1, 0, getSaltLength());
1189 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
1192 //* DEBUG: */ debugOutput('salt=' . $salt);
1193 $salt = substr($salt, 0, getSaltLength());
1194 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
1196 // Sanity check on salt
1197 if (strlen($salt) != getSaltLength()) {
1199 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
1203 // Generate final hash (for debug output)
1204 $finalHash = $salt . sha1($salt . $plainText);
1207 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
1213 // Scramble a string
1214 function scrambleString ($str) {
1218 // Final check, in case of failture it will return unscrambled string
1219 if (strlen($str) > 40) {
1220 // The string is to long
1222 } elseif (strlen($str) == 40) {
1224 $scrambleNums = explode(':', getPassScramble());
1226 // Generate new numbers
1227 $scrambleNums = explode(':', genScrambleString(strlen($str)));
1230 // Compare both lengths and abort if different
1231 if (strlen($str) != count($scrambleNums)) return $str;
1233 // Scramble string here
1234 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
1235 for ($idx = 0; $idx < strlen($str); $idx++) {
1236 // Get char on scrambled position
1237 $char = substr($str, $scrambleNums[$idx], 1);
1239 // Add it to final output string
1240 $scrambled .= $char;
1243 // Return scrambled string
1244 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
1248 // De-scramble a string scrambled by scrambleString()
1249 function descrambleString ($str) {
1250 // Scramble only 40 chars long strings
1251 if (strlen($str) != 40) return $str;
1253 // Load numbers from config
1254 $scrambleNums = explode(':', getPassScramble());
1257 if (count($scrambleNums) != 40) return $str;
1259 // Begin descrambling
1260 $orig = str_repeat(' ', 40);
1261 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
1262 for ($idx = 0; $idx < 40; $idx++) {
1263 $char = substr($str, $idx, 1);
1264 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1267 // Return scrambled string
1268 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1272 // Generated a "string" for scrambling
1273 function genScrambleString ($len) {
1274 // Prepare array for the numbers
1275 $scrambleNumbers = array();
1277 // First we need to setup randomized numbers from 0 to 31
1278 for ($idx = 0; $idx < $len; $idx++) {
1280 $rand = mt_rand(0, ($len -1));
1282 // Check for it by creating more numbers
1283 while (array_key_exists($rand, $scrambleNumbers)) {
1284 $rand = mt_rand(0, ($len -1));
1288 $scrambleNumbers[$rand] = $rand;
1291 // So let's create the string for storing it in database
1292 $scrambleString = implode(':', $scrambleNumbers);
1293 return $scrambleString;
1296 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1297 function encodeHashForCookie ($passHash) {
1298 // Return vanilla password hash
1301 // Is a secret key and master salt already initialized?
1302 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1303 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1304 // Only calculate when the secret key is generated
1305 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1306 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1307 // Both keys must have same length so return unencrypted
1308 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1312 $newHash = ''; $start = 9;
1313 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1314 for ($idx = 0; $idx < 20; $idx++) {
1315 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1316 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1317 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1318 $mod = dechex($idx);
1319 if ($part1 > $part2) {
1320 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1321 } elseif ($part2 > $part1) {
1322 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1324 $mod = substr($mod, 0, 2);
1325 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1326 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1327 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1332 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1333 $ret = generateHash($newHash, getMasterSalt());
1337 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1341 // Fix "deleted" cookies
1342 function fixDeletedCookies ($cookies) {
1343 // Is this an array with entries?
1344 if ((is_array($cookies)) && (count($cookies) > 0)) {
1345 // Then check all cookies if they are marked as deleted!
1346 foreach ($cookies as $cookieName) {
1347 // Is the cookie set to "deleted"?
1348 if (getSession($cookieName) == 'deleted') {
1349 setSession($cookieName, '');
1355 // Checks if a given apache module is loaded
1356 function isApacheModuleLoaded ($apacheModule) {
1357 // Check it and return result
1358 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1361 // Get current theme name
1362 function getCurrentTheme () {
1363 // The default theme is 'default'... ;-)
1366 // Do we have ext-theme installed and active?
1367 if (isExtensionActive('theme')) {
1368 // Call inner method
1369 $ret = getActualTheme();
1372 // Return theme value
1376 // Generates an error code from given account status
1377 function generateErrorCodeFromUserStatus ($status = '') {
1378 // If no status is provided, use the default, cached
1379 if ((empty($status)) && (isMember())) {
1381 $status = getUserData('status');
1384 // Default error code if unknown account status
1385 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1387 // Generate constant name
1388 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1390 // Is the constant there?
1391 if (isCodeSet($codeName)) {
1393 $errorCode = getCode($codeName);
1396 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1399 // Return error code
1403 // Back-ported from the new ship-simu engine. :-)
1404 function debug_get_printable_backtrace () {
1406 $backtrace = '<ol>';
1408 // Get and prepare backtrace for output
1409 $backtraceArray = debug_backtrace();
1410 foreach ($backtraceArray as $key => $trace) {
1411 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1412 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1413 if (!isset($trace['args'])) $trace['args'] = array();
1414 $backtrace .= '<li class="debug_list"><span class="backtrace_file">' . basename($trace['file']) . '</span>:' . $trace['line'] . ', <span class="backtrace_function">' . $trace['function'] . '(' . count($trace['args']) . ')</span></li>';
1418 $backtrace .= '</ol>';
1420 // Return the backtrace
1424 // A mail-able backtrace
1425 function debug_get_mailable_backtrace () {
1429 // Get and prepare backtrace for output
1430 $backtraceArray = debug_backtrace();
1431 foreach ($backtraceArray as $key => $trace) {
1432 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1433 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1434 if (!isset($trace['args'])) $trace['args'] = array();
1435 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1438 // Return the backtrace
1442 // Generates a ***weak*** seed
1443 function generateSeed () {
1444 return microtime(true) * 100000;
1447 // Converts a message code to a human-readable message
1448 function getMessageFromErrorCode ($code) {
1452 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1453 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
1454 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1455 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1456 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1457 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1458 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1459 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1460 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1461 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1462 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1463 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1464 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1465 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1466 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1467 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1468 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1469 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1470 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1471 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1472 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1473 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1474 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1475 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1476 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1477 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1478 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1479 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1480 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1482 case getCode('ERROR_MAILID'):
1483 if (isExtensionActive('mailid', true)) {
1484 $message = '{--ERROR_CONFIRMING_MAIL--}';
1486 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', 'mailid');
1490 case getCode('EXTENSION_PROBLEM'):
1491 if (isGetRequestParameterSet('ext')) {
1492 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1494 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1498 case getCode('URL_TLOCK'):
1499 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1500 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1501 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1503 // Load timestamp from last order
1504 list($timestamp) = SQL_FETCHROW($result);
1507 SQL_FREERESULT($result);
1509 // Translate it for templates
1510 $timestamp = generateDateTime($timestamp, 1);
1512 // Calculate hours...
1513 $STD = round(getConfig('url_tlock') / 60 / 60);
1516 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
1519 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
1521 // Finally contruct the message
1522 // @TODO Rewrite this old lost code to a template
1523 $message = '{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ' . $STD . '
1524 {--_HOURS--}, ' . $MIN . ' {--_MINUTES--} {--_AND--} ' . $SEC . ' {--_SECONDS--}<br />
1525 {--MEMBER_LAST_TLOCK--}: ' . $timestamp;
1529 // Missing/invalid code
1530 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1533 logDebugMessage(__FUNCTION__, __LINE__, $message);
1537 // Return the message
1541 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1542 function isUrlValidSimple ($url) {
1544 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1546 // Allows http and https
1547 $http = "(http|https)+(:\/\/)";
1549 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1550 // Test double-domains (e.g. .de.vu)
1551 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1553 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1555 $dir = "((/)+([-_\.[:alnum:]])+)*";
1557 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1558 // ... and the string after and including question character
1559 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1560 // Pattern for URLs like http://url/dir/doc.html?var=value
1561 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1562 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1563 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1564 // Pattern for URLs like http://url/dir/?var=value
1565 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1566 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1567 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1568 // Pattern for URLs like http://url/dir/page.ext
1569 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1570 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1571 $pattern['ipdp'] = $http . $ip . $dir . $page;
1572 // Pattern for URLs like http://url/dir
1573 $pattern['d1d'] = $http . $domain1 . $dir;
1574 $pattern['d2d'] = $http . $domain2 . $dir;
1575 $pattern['ipd'] = $http . $ip . $dir;
1576 // Pattern for URLs like http://url/?var=value
1577 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1578 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1579 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1580 // Pattern for URLs like http://url?var=value
1581 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1582 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1583 $pattern['ipg12'] = $http . $ip . $getstring1;
1585 // Test all patterns
1587 foreach ($pattern as $key => $pat) {
1589 if (isDebugRegularExpressionEnabled()) {
1590 // @TODO Are these convertions still required?
1591 $pat = str_replace('.', '\.', $pat);
1592 $pat = str_replace('@', '\@', $pat);
1593 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1596 // Check if expression matches
1597 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1600 if ($reg === true) break;
1603 // Return true/false
1607 // Wtites data to a config.php-style file
1608 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1609 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1610 // Initialize some variables
1616 // Is the file there and read-/write-able?
1617 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1618 $search = 'CFG: ' . $comment;
1619 $tmp = $FQFN . '.tmp';
1621 // Open the source file
1622 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1624 // Is the resource valid?
1625 if (is_resource($fp)) {
1626 // Open temporary file
1627 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1629 // Is the resource again valid?
1630 if (is_resource($fp_tmp)) {
1631 // Mark temporary file as readable
1632 $GLOBALS['file_readable'][$tmp] = true;
1635 while (!feof($fp)) {
1636 // Read from source file
1637 $line = fgets ($fp, 1024);
1639 if (strpos($line, $search) > -1) {
1645 if ($next === $seek) {
1647 $line = $prefix . $DATA . $suffix . "\n";
1653 // Write to temp file
1654 fwrite($fp_tmp, $line);
1660 // Finished writing tmp file
1664 // Close source file
1667 if (($done === true) && ($found === true)) {
1668 // Copy back tmp file and delete tmp :-)
1669 copyFileVerified($tmp, $FQFN, 0644);
1670 return removeFile($tmp);
1671 } elseif ($found === false) {
1672 outputHtml('<strong>CHANGE:</strong> 404!');
1674 outputHtml('<strong>TMP:</strong> UNDONE!');
1678 // File not found, not readable or writeable
1679 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1682 // An error was detected!
1685 // Send notification to admin
1686 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
1687 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1689 sendAdminsEmails($subject, $templateName, $content, $userid);
1691 // Send out out-dated way
1692 $message = loadEmailTemplate($templateName, $content, $userid);
1693 sendAdminEmails($subject, $message);
1697 // Debug message logger
1698 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1699 // Is debug mode enabled?
1700 if ((isDebugModeEnabled()) || ($force === true)) {
1702 $message = str_replace("\r", '', str_replace("\n", '', $message));
1704 // Log this message away
1705 $fp = fopen(getCachePath() . 'debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write logfile debug.log!');
1706 fwrite($fp, generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
1711 // Handle extra values
1712 function handleExtraValues ($filterFunction, $value, $extraValue) {
1713 // Default is the value itself
1716 // Do we have a special filter function?
1717 if (!empty($filterFunction)) {
1718 // Does the filter function exist?
1719 if (function_exists($filterFunction)) {
1720 // Do we have extra parameters here?
1721 if (!empty($extraValue)) {
1722 // Put both parameters in one new array by default
1723 $args = array($value, $extraValue);
1725 // If we have an array simply use it and pre-extend it with our value
1726 if (is_array($extraValue)) {
1727 // Make the new args array
1728 $args = merge_array(array($value), $extraValue);
1731 // Call the multi-parameter call-back
1732 $ret = call_user_func_array($filterFunction, $args);
1734 // One parameter call
1735 $ret = call_user_func($filterFunction, $value);
1744 // Converts timestamp selections into a timestamp
1745 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1746 // Init test variable
1750 // Get last three chars
1751 $test = substr($id, -3);
1753 // Improved way of checking! :-)
1754 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1755 // Found a multi-selection for timings?
1756 $test = substr($id, 0, -3);
1757 if ((isset($postData[$test.'_ye'])) && (isset($postData[$test.'_mo'])) && (isset($postData[$test.'_we'])) && (isset($postData[$test.'_da'])) && (isset($postData[$test.'_ho'])) && (isset($postData[$test.'_mi'])) && (isset($postData[$test.'_se'])) && ($test != $test2)) {
1758 // Generate timestamp
1759 $postData[$test] = createTimestampFromSelections($test, $postData);
1760 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1761 $GLOBALS['skip_config'][$test] = true;
1763 // Remove data from array
1764 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1765 unset($postData[$test . '_' . $rem]);
1776 // Reverts the german decimal comma into Computer decimal dot
1777 function convertCommaToDot ($str) {
1778 // Default float is not a float... ;-)
1781 // Which language is selected?
1782 switch (getLanguage()) {
1783 case 'de': // German language
1784 // Remove german thousand dots first
1785 $str = str_replace('.', '', $str);
1787 // Replace german commata with decimal dot and cast it
1788 $float = (float)str_replace(',', '.', $str);
1791 default: // US and so on
1792 // Remove thousand dots first and cast
1793 $float = (float)str_replace(',', '', $str);
1801 // Handle menu-depending failed logins and return the rendered content
1802 function handleLoginFailures ($accessLevel) {
1803 // Default output is empty ;-)
1806 // Is the session data set?
1807 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1808 // Ignore zero values
1809 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1810 // Non-guest has login failures found, get both data and prepare it for template
1811 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1813 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1814 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1818 $OUT = loadTemplate('login_failures', true, $content);
1821 // Reset session data
1822 setSession('mailer_' . $accessLevel . '_failures', '');
1823 setSession('mailer_' . $accessLevel . '_last_failure', '');
1826 // Return rendered content
1831 function rebuildCache ($cache, $inc = '', $force = false) {
1833 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1835 // Shall I remove the cache file?
1836 if (isCacheInstanceValid()) {
1838 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1840 $GLOBALS['cache_instance']->removeCacheFile($force);
1843 // Include file given?
1846 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
1848 // Is the include there?
1849 if (isIncludeReadable($inc)) {
1850 // And rebuild it from scratch
1851 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1854 // Include not found!
1855 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1861 // Determines the real remote address
1862 function determineRealRemoteAddress () {
1863 // Is a proxy in use?
1864 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1866 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1867 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
1868 // Yet, another proxy
1869 $address = $_SERVER['HTTP_CLIENT_IP'];
1871 // The regular address when no proxy was used
1872 $address = $_SERVER['REMOTE_ADDR'];
1875 // This strips out the real address from proxy output
1876 if (strstr($address, ',')) {
1877 $addressArray = explode(',', $address);
1878 $address = $addressArray[0];
1881 // Return the result
1885 // Adds a bonus mail to the queue
1886 // This is a high-level function!
1887 function addNewBonusMail ($data, $mode = '', $output=true) {
1888 // Use mode from data if not set and availble ;-)
1889 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
1891 // Generate receiver list
1892 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1895 if (!empty($receiver)) {
1896 // Add bonus mail to queue
1897 addBonusMailToQueue(
1909 // Mail inserted into bonus pool
1910 if ($output === true) {
1911 loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
1913 } elseif ($output === true) {
1914 // More entered than can be reached!
1915 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
1918 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1922 // Determines referal id and sets it
1923 function determineReferalId () {
1924 // Skip this in non-html-mode and outside ref.php
1925 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
1927 // Check if refid is set
1928 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1930 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1931 // The variable user comes from the click-counter script click.php and we only accept this here
1932 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1933 } elseif (isPostRequestParameterSet('refid')) {
1934 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
1935 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1936 } elseif (isGetRequestParameterSet('refid')) {
1937 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
1938 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1939 } elseif (isGetRequestParameterSet('ref')) {
1940 // Set refid=ref (the referal link uses such variable)
1941 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1942 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1943 // Set session refid als global
1944 $GLOBALS['refid'] = bigintval(getSession('refid'));
1945 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (isRandomReferalIdEnabled())) {
1946 // Select a random user which has confirmed enougth mails
1947 $GLOBALS['refid'] = determineRandomReferalId();
1948 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getConfig('def_refid')))) {
1949 // Set default refid as refid in URL
1950 $GLOBALS['refid'] = getConfig('def_refid');
1952 // No default id when sql_patches is not installed or none set
1953 $GLOBALS['refid'] = '0';
1956 // Set cookie when default refid > 0
1957 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isConfigEntrySet('def_refid')) && (isValidUserId(getConfig('def_refid'))))) {
1958 // Default is not found
1961 // Do we have nickname or userid set?
1962 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1963 // Nickname in URL, so load the id
1964 $found = fetchUserData($GLOBALS['refid'], 'nickname');
1965 } elseif ($GLOBALS['refid'] > 0) {
1966 // Direct userid entered
1967 $found = fetchUserData($GLOBALS['refid']);
1970 // Is the record valid?
1971 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
1972 // No, then reset referal id
1973 $GLOBALS['refid'] = getConfig('def_refid');
1977 setSession('refid', $GLOBALS['refid']);
1980 // Return determined refid
1981 return $GLOBALS['refid'];
1984 // Enables the reset mode and runs it
1985 function doReset () {
1986 // Enable the reset mode
1987 $GLOBALS['reset_enabled'] = true;
1990 runFilterChain('reset');
1993 // Our shutdown-function
1994 function shutdown () {
1995 // Call the filter chain 'shutdown'
1996 runFilterChain('shutdown', null);
1998 // Check if not in installation phase and the link is up
1999 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
2001 SQL_CLOSE(__FUNCTION__, __LINE__);
2002 } elseif (!isInstallationPhase()) {
2004 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
2007 // Stop executing here
2012 function initMemberId () {
2013 $GLOBALS['member_id'] = '0';
2016 // Setter for member id
2017 function setMemberId ($memberid) {
2018 // We should not set member id to zero
2019 if ($memberid == '0') debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
2022 $GLOBALS['member_id'] = bigintval($memberid);
2025 // Getter for member id or returns zero
2026 function getMemberId () {
2027 // Default member id
2030 // Is the member id set?
2031 if (isMemberIdSet()) {
2033 $memberid = $GLOBALS['member_id'];
2040 // Checks ether the member id is set
2041 function isMemberIdSet () {
2042 return (isset($GLOBALS['member_id']));
2045 // Setter for extra title
2046 function setExtraTitle ($extraTitle) {
2047 $GLOBALS['extra_title'] = $extraTitle;
2050 // Getter for extra title
2051 function getExtraTitle () {
2052 // Is the extra title set?
2053 if (!isExtraTitleSet()) {
2054 // No, then abort here
2055 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
2059 return $GLOBALS['extra_title'];
2062 // Checks if the extra title is set
2063 function isExtraTitleSet () {
2064 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
2067 // Reads a directory recursively by default and searches for files not matching
2068 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
2069 // a whole directory.
2070 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
2071 // Add default entries we should exclude
2072 $excludeArray[] = '.';
2073 $excludeArray[] = '..';
2074 $excludeArray[] = '.svn';
2075 $excludeArray[] = '.htaccess';
2077 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
2082 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
2085 while ($baseFile = readdir($dirPointer)) {
2086 // Exclude '.', '..' and entries in $excludeArray automatically
2087 if (in_array($baseFile, $excludeArray, true)) {
2089 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
2093 // Construct include filename and FQFN
2094 $fileName = $baseDir . $baseFile;
2095 $FQFN = getPath() . $fileName;
2097 // Remove double slashes
2098 $FQFN = str_replace('//', '/', $FQFN);
2100 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
2101 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
2102 // These Lines are only for debugging!!
2103 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
2104 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
2105 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
2111 // Skip also files with non-matching prefix genericly
2112 if (($recursive === true) && (isDirectory($FQFN))) {
2113 // Is a redirectory so read it as well
2114 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
2116 // And skip further processing
2118 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
2120 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
2122 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
2123 // Skip wrong suffix as well
2124 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
2126 } elseif (!isFileReadable($FQFN)) {
2127 // Not readable so skip it
2128 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
2132 // Is the file a PHP script or other?
2133 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
2134 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
2135 // Is this a valid include file?
2136 if ($extension == '.php') {
2137 // Remove both for extension name
2138 $extName = substr($baseFile, strlen($prefix), -4);
2140 // Is the extension valid and active?
2141 if (isExtensionNameValid($extName)) {
2142 // Then add this file
2143 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
2144 $files[] = $fileName;
2146 // Add non-extension files as well
2147 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
2148 if ($addBaseDir === true) {
2149 $files[] = $fileName;
2151 $files[] = $baseFile;
2155 // We found .php file but should not search for them, why?
2156 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
2158 } elseif (substr($baseFile, -4, 4) == $extension) {
2159 // Other, generic file found
2160 $files[] = $fileName;
2165 closedir($dirPointer);
2170 // Return array with include files
2171 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
2175 // Maps a module name into a database table name
2176 function mapModuleToTable ($moduleName) {
2177 // Map only these, still lame code...
2178 switch ($moduleName) {
2179 // 'index' is the guest's menu
2180 case 'index': $moduleName = 'guest'; break;
2181 // ... and 'login' the member's menu
2182 case 'login': $moduleName = 'member'; break;
2183 // Anything else will not be mapped, silently.
2190 // Add SQL debug data to array for later output
2191 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
2192 // Do we have cache?
2193 if (!isset($GLOBALS['debug_sql_available'])) {
2194 // Check it and cache it in $GLOBALS
2195 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
2198 // Don't execute anything here if we don't need or ext-other is missing
2199 if ($GLOBALS['debug_sql_available'] === false) {
2203 // Already executed?
2204 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
2205 // Then abort here, we don't need to profile a query twice
2209 // Remeber this as profiled (or not, but we don't care here)
2210 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
2214 'num_rows' => SQL_NUMROWS($result),
2215 'affected' => SQL_AFFECTEDROWS(),
2216 'sql_str' => $sqlString,
2217 'timing' => $timing,
2218 'file' => basename($F),
2223 $GLOBALS['debug_sqls'][] = $record;
2226 // Initializes the cache instance
2227 function initCacheInstance () {
2228 // Load include for CacheSystem class
2229 loadIncludeOnce('inc/classes/cachesystem.class.php');
2231 // Initialize cache system only when it's needed
2232 $GLOBALS['cache_instance'] = new CacheSystem();
2233 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
2234 // Failed to initialize cache sustem
2235 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2239 // Getter for message from array or raw message
2240 function getMessageFromIndexedArray ($message, $pos, $array) {
2241 // Check if the requested message was found in array
2242 if (isset($array[$pos])) {
2243 // ... if yes then use it!
2244 $ret = $array[$pos];
2246 // ... else use default message
2254 // Convert ';' to ', ' for e.g. receiver list
2255 function convertReceivers ($old) {
2256 return str_replace(';', ', ', $old);
2259 // Get a module from filename and access level
2260 function getModuleFromFileName ($file, $accessLevel) {
2261 // Default is 'invalid';
2262 $modCheck = 'invalid';
2264 // @TODO This is still very static, rewrite it somehow
2265 switch ($accessLevel) {
2267 $modCheck = 'admin';
2273 $modCheck = getModule();
2276 default: // Unsupported file name / access level
2277 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2285 // Encodes an URL for adding session id, etc.
2286 function encodeUrl ($url, $outputMode = '0') {
2287 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2288 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) return $url;
2290 // Do we have a valid session?
2291 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2293 // Determine right seperator
2294 $seperator = '&';
2295 if (strpos($url, '?') === false) {
2298 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2304 if (session_id() != '') {
2305 $url .= $seperator . session_name() . '=' . session_id();
2310 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2312 $url = '{?URL?}/' . $url;
2319 // Simple check for spider
2320 function isSpider () {
2321 // Get the UA and trim it down
2322 $userAgent = trim(strtolower(detectUserAgent(true)));
2324 // It should not be empty, if so it is better a spider/bot
2325 if (empty($userAgent)) return true;
2328 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2331 // Function to search for the last modified file
2332 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2334 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2335 // Does it match what we are looking for? (We skip a lot files already!)
2336 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2337 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2339 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2340 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2342 // Walk through all entries
2343 foreach ($ds as $d) {
2344 // Generate proper FQFN
2345 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2347 // Is it a file and readable?
2348 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2349 if (isFileReadable($FQFN)) {
2350 // $FQFN is a readable file so extract the requested data from it
2351 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2352 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2354 // Is the file more recent?
2355 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2356 // This file is newer as the file before
2357 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2358 $last_changed['path_name'] = $FQFN;
2359 $last_changed[$lookFor] = $check;
2363 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2368 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2369 function handleFieldWithBraces ($field) {
2370 // Are there braces [] at the end?
2371 if (substr($field, -2, 2) == '[]') {
2372 // Try to find one and replace it. I do it this way to allow easy
2373 // extending of this code.
2374 foreach (array('admin_list_builder_id_value') as $key) {
2375 // Is the cache entry set?
2376 if (isset($GLOBALS[$key])) {
2378 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2390 // Converts a userid so it can be used in SQL queries
2391 function makeDatabaseUserId ($userid) {
2392 // Is it a valid username?
2393 if (isValidUserId($userid)) {
2395 $userid = bigintval($userid);
2397 // Is not valid or zero
2405 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2406 // Note: This function is cached
2407 function capitalizeUnderscoreString ($str) {
2408 // Do we have cache?
2409 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2410 // Init target string
2413 // Explode it with the underscore, but rewrite dashes to underscore before
2414 $strArray = explode('_', str_replace('-', '_', $str));
2416 // "Walk" through all elements and make them lower-case but first upper-case
2417 foreach ($strArray as $part) {
2418 // Capitalize the string part
2419 $capitalized .= ucfirst(strtolower($part));
2422 // Store the converted string in cache array
2423 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2427 return $GLOBALS[__FUNCTION__][$str];
2430 //-----------------------------------------------------------------------------
2431 // Automatically re-created functions, all taken from user comments on www.php.net
2432 //-----------------------------------------------------------------------------
2434 if (!function_exists('html_entity_decode')) {
2435 // Taken from documentation on www.php.net
2436 function html_entity_decode ($string) {
2437 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2438 $trans_tbl = array_flip($trans_tbl);
2439 return strtr($string, $trans_tbl);
2443 if (!function_exists('http_build_query')) {
2444 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
2445 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
2447 foreach ((array)$data as $k => $v) {
2448 if (is_int($k) && $prefix != null) {
2449 $k = urlencode($prefix . $k);
2452 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
2454 if (is_array($v) || is_object($v)) {
2455 array_push($ret, http_build_query($v, '', $sep, $k));
2457 array_push($ret, $k.'='.urlencode($v));
2461 if (empty($sep)) $sep = ini_get('arg_separator.output');
2463 return implode($sep, $ret);