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("' . escapeQuotes(doFinalCompilation(compileRawCode($toEmail), false)) . '"); ';
185 $eval .= '$subject = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($subject), false)) . '"); ';
186 $eval .= '$headers = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($headers), false)) . '"); ';
188 // Do not decode entities in the message because we also send HTML mails through this function
189 $eval .= '$message = "' . escapeQuotes(doFinalCompilation(compileRawCode($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 // There should be data, else we don't need to extend $script with $body
833 // Do we have a question-mark in the script?
834 if (strpos($script, '?') === false) {
835 // No, so first char must be question mark
845 // Remove trailed & to make it more conform
846 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
849 // Generate GET request header
850 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
851 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
852 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
853 if (isConfigEntrySet('FULL_VERSION')) {
854 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
856 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
858 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
859 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
860 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
861 $request .= 'Connection: close' . getConfig('HTTP_EOL');
862 $request .= getConfig('HTTP_EOL');
864 // Send the raw request
865 $response = sendRawRequest($host, $request);
867 // Return the result to the caller function
871 // Send a POST request
872 function sendPostRequest ($script, $postData) {
873 // Is postData an array?
874 if (!is_array($postData)) {
876 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
877 return array('', '', '');
880 // Extract host name from script
881 $host = extractHostnameFromUrl($script);
883 // Construct request body
884 $body = http_build_query($postData, '', '&');
886 // Generate POST request header
887 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
888 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
889 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
890 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
891 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
892 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
893 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
894 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
895 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
896 $request .= 'Connection: close' . getConfig('HTTP_EOL');
897 $request .= getConfig('HTTP_EOL');
902 // Send the raw request
903 $response = sendRawRequest($host, $request);
905 // Return the result to the caller function
909 // Sends a raw request to another host
910 function sendRawRequest ($host, $request) {
911 // Init errno and errdesc with 'all fine' values
912 $errno = '0'; $errdesc = '';
915 $response = array('', '', '');
917 // Default is not to use proxy
920 // Are proxy settins set?
927 loadIncludeOnce('inc/classes/resolver.class.php');
929 // Get resolver instance
930 $resolver = new HostnameResolver();
933 //* DEBUG: */ die('SCRIPT=' . $script);
934 if ($useProxy === true) {
935 // Resolve hostname into IP address
936 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
938 // Connect to host through proxy connection
939 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
941 // Resolve hostname into IP address
942 $ip = $resolver->resolveHostname($host);
944 // Connect to host directly
945 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
949 if (!is_resource($fp)) {
951 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
953 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
954 // Cannot set non-blocking mode or timeout
955 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
960 if ($useProxy === true) {
961 // Setup proxy tunnel
962 $response = setupProxyTunnel($host, $fp);
964 // If the response is invalid, abort
965 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
967 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
973 fwrite($fp, $request);
976 $start = microtime(true);
980 // Get info from stream
981 $info = stream_get_meta_data($fp);
983 // Is it timed out? 15 seconds is a really patient...
984 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
986 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
992 // Get line from stream
993 $line = fgets($fp, 128);
995 // Ignore empty lines because of non-blocking mode
997 // uslepp a little to avoid 100% CPU load
1004 // Add it to response
1005 $response[] = trim($line);
1011 // Time request if debug-mode is enabled
1012 if (isDebugModeEnabled()) {
1013 // Add debug message...
1014 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1017 // Skip first empty lines
1019 foreach ($resp as $idx => $line) {
1021 $line = trim($line);
1023 // Is this line empty?
1026 array_shift($response);
1028 // Abort on first non-empty line
1033 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1034 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1036 // Proxy agent found or something went wrong?
1037 if (!isset($response[0])) {
1038 // No response, maybe timeout
1039 $response = array('', '', '');
1040 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1041 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1042 // Proxy header detected, so remove two lines
1043 array_shift($response);
1044 array_shift($response);
1047 // Was the request successfull?
1048 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1049 // Not found / access forbidden
1050 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1051 $response = array('', '', '');
1058 // Sets up a proxy tunnel for given hostname and through resource
1059 function setupProxyTunnel ($host, $resource) {
1061 $response = array('', '', '');
1063 // Generate CONNECT request header
1064 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1065 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1067 // Use login data to proxy? (username at least!)
1068 if (getConfig('proxy_username') != '') {
1070 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1071 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1074 // Add last new-line
1075 $proxyTunnel .= getConfig('HTTP_EOL');
1076 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1079 fwrite($fp, $proxyTunnel);
1083 // No response received
1087 // Read the first line
1088 $resp = trim(fgets($fp, 10240));
1089 $respArray = explode(' ', $resp);
1090 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1091 // Invalid response!
1099 // Taken from www.php.net isInStringIgnoreCase() user comments
1100 function isEmailValid ($email) {
1101 // Check first part of email address
1102 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1105 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1108 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1110 // Return check result
1111 return preg_match($regex, $email);
1114 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1115 function isUrlValid ($URL, $compile=true) {
1116 // Trim URL a little
1117 $URL = trim(urldecode($URL));
1118 //* DEBUG: */ debugOutput($URL);
1120 // Compile some chars out...
1121 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1122 //* DEBUG: */ debugOutput($URL);
1124 // Check for the extension filter
1125 if (isExtensionActive('filter')) {
1126 // Use the extension's filter set
1127 return FILTER_VALIDATE_URL($URL, false);
1130 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1131 // https:// in front of the URLs
1132 return isUrlValidSimple($URL);
1135 // Generate a hash for extra-security for all passwords
1136 function generateHash ($plainText, $salt = '', $hash = true) {
1138 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
1140 // Is the required extension 'sql_patches' there and a salt is not given?
1141 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
1142 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
1143 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1144 if ($hash === true) {
1145 // Is plain password
1146 return md5($plainText);
1148 // Is already a hash
1153 // Do we miss an arry element here?
1154 if (!isConfigEntrySet('file_hash')) {
1156 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
1159 // When the salt is empty build a new one, else use the first x configured characters as the salt
1161 // Build server string for more entropy
1162 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
1165 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
1168 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
1170 // Calculate number for generating the code
1171 $a = time() + getConfig('_ADD') - 1;
1173 // Generate SHA1 sum from modula of number and the prime number
1174 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a);
1175 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
1176 $sha1 = scrambleString($sha1);
1177 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
1178 //* DEBUG: */ $sha1b = descrambleString($sha1);
1179 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
1181 // Generate the password salt string
1182 $salt = substr($sha1, 0, getSaltLength());
1183 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
1186 //* DEBUG: */ debugOutput('salt=' . $salt);
1187 $salt = substr($salt, 0, getSaltLength());
1188 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
1190 // Sanity check on salt
1191 if (strlen($salt) != getSaltLength()) {
1193 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
1197 // Generate final hash (for debug output)
1198 $finalHash = $salt . sha1($salt . $plainText);
1201 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
1207 // Scramble a string
1208 function scrambleString ($str) {
1212 // Final check, in case of failture it will return unscrambled string
1213 if (strlen($str) > 40) {
1214 // The string is to long
1216 } elseif (strlen($str) == 40) {
1218 $scrambleNums = explode(':', getPassScramble());
1220 // Generate new numbers
1221 $scrambleNums = explode(':', genScrambleString(strlen($str)));
1224 // Compare both lengths and abort if different
1225 if (strlen($str) != count($scrambleNums)) return $str;
1227 // Scramble string here
1228 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
1229 for ($idx = 0; $idx < strlen($str); $idx++) {
1230 // Get char on scrambled position
1231 $char = substr($str, $scrambleNums[$idx], 1);
1233 // Add it to final output string
1234 $scrambled .= $char;
1237 // Return scrambled string
1238 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
1242 // De-scramble a string scrambled by scrambleString()
1243 function descrambleString ($str) {
1244 // Scramble only 40 chars long strings
1245 if (strlen($str) != 40) return $str;
1247 // Load numbers from config
1248 $scrambleNums = explode(':', getPassScramble());
1251 if (count($scrambleNums) != 40) return $str;
1253 // Begin descrambling
1254 $orig = str_repeat(' ', 40);
1255 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
1256 for ($idx = 0; $idx < 40; $idx++) {
1257 $char = substr($str, $idx, 1);
1258 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1261 // Return scrambled string
1262 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1266 // Generated a "string" for scrambling
1267 function genScrambleString ($len) {
1268 // Prepare array for the numbers
1269 $scrambleNumbers = array();
1271 // First we need to setup randomized numbers from 0 to 31
1272 for ($idx = 0; $idx < $len; $idx++) {
1274 $rand = mt_rand(0, ($len -1));
1276 // Check for it by creating more numbers
1277 while (array_key_exists($rand, $scrambleNumbers)) {
1278 $rand = mt_rand(0, ($len -1));
1282 $scrambleNumbers[$rand] = $rand;
1285 // So let's create the string for storing it in database
1286 $scrambleString = implode(':', $scrambleNumbers);
1287 return $scrambleString;
1290 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1291 function encodeHashForCookie ($passHash) {
1292 // Return vanilla password hash
1295 // Is a secret key and master salt already initialized?
1296 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1297 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1298 // Only calculate when the secret key is generated
1299 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1300 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1301 // Both keys must have same length so return unencrypted
1302 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1306 $newHash = ''; $start = 9;
1307 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1308 for ($idx = 0; $idx < 20; $idx++) {
1309 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1310 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1311 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1312 $mod = dechex($idx);
1313 if ($part1 > $part2) {
1314 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1315 } elseif ($part2 > $part1) {
1316 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1318 $mod = substr($mod, 0, 2);
1319 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1320 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1321 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1326 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1327 $ret = generateHash($newHash, getMasterSalt());
1331 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1335 // Fix "deleted" cookies
1336 function fixDeletedCookies ($cookies) {
1337 // Is this an array with entries?
1338 if ((is_array($cookies)) && (count($cookies) > 0)) {
1339 // Then check all cookies if they are marked as deleted!
1340 foreach ($cookies as $cookieName) {
1341 // Is the cookie set to "deleted"?
1342 if (getSession($cookieName) == 'deleted') {
1343 setSession($cookieName, '');
1349 // Checks if a given apache module is loaded
1350 function isApacheModuleLoaded ($apacheModule) {
1351 // Check it and return result
1352 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1355 // Get current theme name
1356 function getCurrentTheme () {
1357 // The default theme is 'default'... ;-)
1360 // Do we have ext-theme installed and active?
1361 if (isExtensionActive('theme')) {
1362 // Call inner method
1363 $ret = getActualTheme();
1366 // Return theme value
1370 // Generates an error code from given account status
1371 function generateErrorCodeFromUserStatus ($status = '') {
1372 // If no status is provided, use the default, cached
1373 if ((empty($status)) && (isMember())) {
1375 $status = getUserData('status');
1378 // Default error code if unknown account status
1379 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1381 // Generate constant name
1382 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1384 // Is the constant there?
1385 if (isCodeSet($codeName)) {
1387 $errorCode = getCode($codeName);
1390 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1393 // Return error code
1397 // Back-ported from the new ship-simu engine. :-)
1398 function debug_get_printable_backtrace () {
1400 $backtrace = '<ol>';
1402 // Get and prepare backtrace for output
1403 $backtraceArray = debug_backtrace();
1404 foreach ($backtraceArray as $key => $trace) {
1405 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1406 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1407 if (!isset($trace['args'])) $trace['args'] = array();
1408 $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>';
1412 $backtrace .= '</ol>';
1414 // Return the backtrace
1418 // A mail-able backtrace
1419 function debug_get_mailable_backtrace () {
1423 // Get and prepare backtrace for output
1424 $backtraceArray = debug_backtrace();
1425 foreach ($backtraceArray as $key => $trace) {
1426 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1427 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1428 if (!isset($trace['args'])) $trace['args'] = array();
1429 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1432 // Return the backtrace
1436 // Generates a ***weak*** seed
1437 function generateSeed () {
1438 return microtime(true) * 100000;
1441 // Converts a message code to a human-readable message
1442 function getMessageFromErrorCode ($code) {
1446 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1447 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
1448 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1449 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1450 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1451 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1452 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1453 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1454 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1455 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1456 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1457 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1458 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1459 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1460 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1461 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1462 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1463 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1464 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1465 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1466 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1467 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1468 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1469 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1470 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1471 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1472 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1473 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1474 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1476 case getCode('ERROR_MAILID'):
1477 if (isExtensionActive('mailid', true)) {
1478 $message = '{--ERROR_CONFIRMING_MAIL--}';
1480 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', 'mailid');
1484 case getCode('EXTENSION_PROBLEM'):
1485 if (isGetRequestParameterSet('ext')) {
1486 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1488 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1492 case getCode('URL_TLOCK'):
1493 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1494 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1495 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1497 // Load timestamp from last order
1498 list($timestamp) = SQL_FETCHROW($result);
1501 SQL_FREERESULT($result);
1503 // Translate it for templates
1504 $timestamp = generateDateTime($timestamp, 1);
1506 // Calculate hours...
1507 $STD = round(getConfig('url_tlock') / 60 / 60);
1510 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
1513 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
1515 // Finally contruct the message
1516 // @TODO Rewrite this old lost code to a template
1517 $message = '{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ' . $STD . '
1518 {--_HOURS--}, ' . $MIN . ' {--_MINUTES--} {--_AND--} ' . $SEC . ' {--_SECONDS--}<br />
1519 {--MEMBER_LAST_TLOCK--}: ' . $timestamp;
1523 // Missing/invalid code
1524 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1527 logDebugMessage(__FUNCTION__, __LINE__, $message);
1531 // Return the message
1535 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1536 function isUrlValidSimple ($url) {
1538 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1540 // Allows http and https
1541 $http = "(http|https)+(:\/\/)";
1543 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1544 // Test double-domains (e.g. .de.vu)
1545 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1547 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1549 $dir = "((/)+([-_\.[:alnum:]])+)*";
1551 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1552 // ... and the string after and including question character
1553 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1554 // Pattern for URLs like http://url/dir/doc.html?var=value
1555 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1556 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1557 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1558 // Pattern for URLs like http://url/dir/?var=value
1559 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1560 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1561 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1562 // Pattern for URLs like http://url/dir/page.ext
1563 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1564 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1565 $pattern['ipdp'] = $http . $ip . $dir . $page;
1566 // Pattern for URLs like http://url/dir
1567 $pattern['d1d'] = $http . $domain1 . $dir;
1568 $pattern['d2d'] = $http . $domain2 . $dir;
1569 $pattern['ipd'] = $http . $ip . $dir;
1570 // Pattern for URLs like http://url/?var=value
1571 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1572 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1573 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1574 // Pattern for URLs like http://url?var=value
1575 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1576 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1577 $pattern['ipg12'] = $http . $ip . $getstring1;
1579 // Test all patterns
1581 foreach ($pattern as $key => $pat) {
1583 if (isDebugRegularExpressionEnabled()) {
1584 // @TODO Are these convertions still required?
1585 $pat = str_replace('.', '\.', $pat);
1586 $pat = str_replace('@', '\@', $pat);
1587 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1590 // Check if expression matches
1591 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1594 if ($reg === true) break;
1597 // Return true/false
1601 // Wtites data to a config.php-style file
1602 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1603 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1604 // Initialize some variables
1610 // Is the file there and read-/write-able?
1611 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1612 $search = 'CFG: ' . $comment;
1613 $tmp = $FQFN . '.tmp';
1615 // Open the source file
1616 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1618 // Is the resource valid?
1619 if (is_resource($fp)) {
1620 // Open temporary file
1621 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1623 // Is the resource again valid?
1624 if (is_resource($fp_tmp)) {
1625 // Mark temporary file as readable
1626 $GLOBALS['file_readable'][$tmp] = true;
1629 while (!feof($fp)) {
1630 // Read from source file
1631 $line = fgets ($fp, 1024);
1633 if (strpos($line, $search) > -1) {
1639 if ($next === $seek) {
1641 $line = $prefix . $DATA . $suffix . "\n";
1647 // Write to temp file
1648 fwrite($fp_tmp, $line);
1654 // Finished writing tmp file
1658 // Close source file
1661 if (($done === true) && ($found === true)) {
1662 // Copy back tmp file and delete tmp :-)
1663 copyFileVerified($tmp, $FQFN, 0644);
1664 return removeFile($tmp);
1665 } elseif ($found === false) {
1666 outputHtml('<strong>CHANGE:</strong> 404!');
1668 outputHtml('<strong>TMP:</strong> UNDONE!');
1672 // File not found, not readable or writeable
1673 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1676 // An error was detected!
1679 // Send notification to admin
1680 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
1681 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1683 sendAdminsEmails($subject, $templateName, $content, $userid);
1685 // Send out out-dated way
1686 $message = loadEmailTemplate($templateName, $content, $userid);
1687 sendAdminEmails($subject, $message);
1691 // Debug message logger
1692 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1693 // Is debug mode enabled?
1694 if ((isDebugModeEnabled()) || ($force === true)) {
1696 $message = str_replace("\r", '', str_replace("\n", '', $message));
1698 // Log this message away
1699 $fp = fopen(getCachePath() . 'debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write logfile debug.log!');
1700 fwrite($fp, generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
1705 // Handle extra values
1706 function handleExtraValues ($filterFunction, $value, $extraValue) {
1707 // Default is the value itself
1710 // Do we have a special filter function?
1711 if (!empty($filterFunction)) {
1712 // Does the filter function exist?
1713 if (function_exists($filterFunction)) {
1714 // Do we have extra parameters here?
1715 if (!empty($extraValue)) {
1716 // Put both parameters in one new array by default
1717 $args = array($value, $extraValue);
1719 // If we have an array simply use it and pre-extend it with our value
1720 if (is_array($extraValue)) {
1721 // Make the new args array
1722 $args = merge_array(array($value), $extraValue);
1725 // Call the multi-parameter call-back
1726 $ret = call_user_func_array($filterFunction, $args);
1728 // One parameter call
1729 $ret = call_user_func($filterFunction, $value);
1738 // Converts timestamp selections into a timestamp
1739 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1740 // Init test variable
1744 // Get last three chars
1745 $test = substr($id, -3);
1747 // Improved way of checking! :-)
1748 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1749 // Found a multi-selection for timings?
1750 $test = substr($id, 0, -3);
1751 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)) {
1752 // Generate timestamp
1753 $postData[$test] = createTimestampFromSelections($test, $postData);
1754 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1755 $GLOBALS['skip_config'][$test] = true;
1757 // Remove data from array
1758 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1759 unset($postData[$test . '_' . $rem]);
1770 // Reverts the german decimal comma into Computer decimal dot
1771 function convertCommaToDot ($str) {
1772 // Default float is not a float... ;-)
1775 // Which language is selected?
1776 switch (getLanguage()) {
1777 case 'de': // German language
1778 // Remove german thousand dots first
1779 $str = str_replace('.', '', $str);
1781 // Replace german commata with decimal dot and cast it
1782 $float = (float)str_replace(',', '.', $str);
1785 default: // US and so on
1786 // Remove thousand dots first and cast
1787 $float = (float)str_replace(',', '', $str);
1795 // Handle menu-depending failed logins and return the rendered content
1796 function handleLoginFailures ($accessLevel) {
1797 // Default output is empty ;-)
1800 // Is the session data set?
1801 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1802 // Ignore zero values
1803 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1804 // Non-guest has login failures found, get both data and prepare it for template
1805 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1807 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1808 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1812 $OUT = loadTemplate('login_failures', true, $content);
1815 // Reset session data
1816 setSession('mailer_' . $accessLevel . '_failures', '');
1817 setSession('mailer_' . $accessLevel . '_last_failure', '');
1820 // Return rendered content
1825 function rebuildCache ($cache, $inc = '', $force = false) {
1827 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1829 // Shall I remove the cache file?
1830 if (isCacheInstanceValid()) {
1832 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1834 $GLOBALS['cache_instance']->removeCacheFile($force);
1837 // Include file given?
1840 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
1842 // Is the include there?
1843 if (isIncludeReadable($inc)) {
1844 // And rebuild it from scratch
1845 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1848 // Include not found!
1849 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1855 // Determines the real remote address
1856 function determineRealRemoteAddress () {
1857 // Is a proxy in use?
1858 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1860 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1861 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
1862 // Yet, another proxy
1863 $address = $_SERVER['HTTP_CLIENT_IP'];
1865 // The regular address when no proxy was used
1866 $address = $_SERVER['REMOTE_ADDR'];
1869 // This strips out the real address from proxy output
1870 if (strstr($address, ',')) {
1871 $addressArray = explode(',', $address);
1872 $address = $addressArray[0];
1875 // Return the result
1879 // Adds a bonus mail to the queue
1880 // This is a high-level function!
1881 function addNewBonusMail ($data, $mode = '', $output=true) {
1882 // Use mode from data if not set and availble ;-)
1883 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
1885 // Generate receiver list
1886 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1889 if (!empty($receiver)) {
1890 // Add bonus mail to queue
1891 addBonusMailToQueue(
1903 // Mail inserted into bonus pool
1904 if ($output === true) {
1905 loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
1907 } elseif ($output === true) {
1908 // More entered than can be reached!
1909 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
1912 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1916 // Determines referal id and sets it
1917 function determineReferalId () {
1918 // Skip this in non-html-mode and outside ref.php
1919 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
1921 // Check if refid is set
1922 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1924 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1925 // The variable user comes from the click-counter script click.php and we only accept this here
1926 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1927 } elseif (isPostRequestParameterSet('refid')) {
1928 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
1929 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1930 } elseif (isGetRequestParameterSet('refid')) {
1931 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
1932 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1933 } elseif (isGetRequestParameterSet('ref')) {
1934 // Set refid=ref (the referal link uses such variable)
1935 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1936 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1937 // Set session refid als global
1938 $GLOBALS['refid'] = bigintval(getSession('refid'));
1939 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (isRandomReferalIdEnabled())) {
1940 // Select a random user which has confirmed enougth mails
1941 $GLOBALS['refid'] = determineRandomReferalId();
1942 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getConfig('def_refid')))) {
1943 // Set default refid as refid in URL
1944 $GLOBALS['refid'] = getConfig('def_refid');
1946 // No default id when sql_patches is not installed or none set
1947 $GLOBALS['refid'] = '0';
1950 // Set cookie when default refid > 0
1951 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isConfigEntrySet('def_refid')) && (isValidUserId(getConfig('def_refid'))))) {
1952 // Default is not found
1955 // Do we have nickname or userid set?
1956 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1957 // Nickname in URL, so load the id
1958 $found = fetchUserData($GLOBALS['refid'], 'nickname');
1959 } elseif ($GLOBALS['refid'] > 0) {
1960 // Direct userid entered
1961 $found = fetchUserData($GLOBALS['refid']);
1964 // Is the record valid?
1965 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
1966 // No, then reset referal id
1967 $GLOBALS['refid'] = getConfig('def_refid');
1971 setSession('refid', $GLOBALS['refid']);
1974 // Return determined refid
1975 return $GLOBALS['refid'];
1978 // Enables the reset mode and runs it
1979 function doReset () {
1980 // Enable the reset mode
1981 $GLOBALS['reset_enabled'] = true;
1984 runFilterChain('reset');
1987 // Our shutdown-function
1988 function shutdown () {
1989 // Call the filter chain 'shutdown'
1990 runFilterChain('shutdown', null);
1992 // Check if not in installation phase and the link is up
1993 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1995 SQL_CLOSE(__FUNCTION__, __LINE__);
1996 } elseif (!isInstallationPhase()) {
1998 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
2001 // Stop executing here
2006 function initMemberId () {
2007 $GLOBALS['member_id'] = '0';
2010 // Setter for member id
2011 function setMemberId ($memberid) {
2012 // We should not set member id to zero
2013 if ($memberid == '0') debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
2016 $GLOBALS['member_id'] = bigintval($memberid);
2019 // Getter for member id or returns zero
2020 function getMemberId () {
2021 // Default member id
2024 // Is the member id set?
2025 if (isMemberIdSet()) {
2027 $memberid = $GLOBALS['member_id'];
2034 // Checks ether the member id is set
2035 function isMemberIdSet () {
2036 return (isset($GLOBALS['member_id']));
2039 // Setter for extra title
2040 function setExtraTitle ($extraTitle) {
2041 $GLOBALS['extra_title'] = $extraTitle;
2044 // Getter for extra title
2045 function getExtraTitle () {
2046 // Is the extra title set?
2047 if (!isExtraTitleSet()) {
2048 // No, then abort here
2049 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
2053 return $GLOBALS['extra_title'];
2056 // Checks if the extra title is set
2057 function isExtraTitleSet () {
2058 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
2061 // Reads a directory recursively by default and searches for files not matching
2062 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
2063 // a whole directory.
2064 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
2065 // Add default entries we should exclude
2066 $excludeArray[] = '.';
2067 $excludeArray[] = '..';
2068 $excludeArray[] = '.svn';
2069 $excludeArray[] = '.htaccess';
2071 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
2076 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
2079 while ($baseFile = readdir($dirPointer)) {
2080 // Exclude '.', '..' and entries in $excludeArray automatically
2081 if (in_array($baseFile, $excludeArray, true)) {
2083 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
2087 // Construct include filename and FQFN
2088 $fileName = $baseDir . $baseFile;
2089 $FQFN = getPath() . $fileName;
2091 // Remove double slashes
2092 $FQFN = str_replace('//', '/', $FQFN);
2094 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
2095 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
2096 // These Lines are only for debugging!!
2097 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
2098 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
2099 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
2105 // Skip also files with non-matching prefix genericly
2106 if (($recursive === true) && (isDirectory($FQFN))) {
2107 // Is a redirectory so read it as well
2108 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
2110 // And skip further processing
2112 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
2114 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
2116 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
2117 // Skip wrong suffix as well
2118 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
2120 } elseif (!isFileReadable($FQFN)) {
2121 // Not readable so skip it
2122 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
2126 // Is the file a PHP script or other?
2127 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
2128 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
2129 // Is this a valid include file?
2130 if ($extension == '.php') {
2131 // Remove both for extension name
2132 $extName = substr($baseFile, strlen($prefix), -4);
2134 // Is the extension valid and active?
2135 if (isExtensionNameValid($extName)) {
2136 // Then add this file
2137 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
2138 $files[] = $fileName;
2140 // Add non-extension files as well
2141 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
2142 if ($addBaseDir === true) {
2143 $files[] = $fileName;
2145 $files[] = $baseFile;
2149 // We found .php file but should not search for them, why?
2150 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
2152 } elseif (substr($baseFile, -4, 4) == $extension) {
2153 // Other, generic file found
2154 $files[] = $fileName;
2159 closedir($dirPointer);
2164 // Return array with include files
2165 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
2169 // Maps a module name into a database table name
2170 function mapModuleToTable ($moduleName) {
2171 // Map only these, still lame code...
2172 switch ($moduleName) {
2173 // 'index' is the guest's menu
2174 case 'index': $moduleName = 'guest'; break;
2175 // ... and 'login' the member's menu
2176 case 'login': $moduleName = 'member'; break;
2177 // Anything else will not be mapped, silently.
2184 // Add SQL debug data to array for later output
2185 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
2186 // Do we have cache?
2187 if (!isset($GLOBALS['debug_sql_available'])) {
2188 // Check it and cache it in $GLOBALS
2189 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
2192 // Don't execute anything here if we don't need or ext-other is missing
2193 if ($GLOBALS['debug_sql_available'] === false) {
2197 // Already executed?
2198 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
2199 // Then abort here, we don't need to profile a query twice
2203 // Remeber this as profiled (or not, but we don't care here)
2204 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
2208 'num_rows' => SQL_NUMROWS($result),
2209 'affected' => SQL_AFFECTEDROWS(),
2210 'sql_str' => $sqlString,
2211 'timing' => $timing,
2212 'file' => basename($F),
2217 $GLOBALS['debug_sqls'][] = $record;
2220 // Initializes the cache instance
2221 function initCacheInstance () {
2222 // Load include for CacheSystem class
2223 loadIncludeOnce('inc/classes/cachesystem.class.php');
2225 // Initialize cache system only when it's needed
2226 $GLOBALS['cache_instance'] = new CacheSystem();
2227 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
2228 // Failed to initialize cache sustem
2229 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2233 // Getter for message from array or raw message
2234 function getMessageFromIndexedArray ($message, $pos, $array) {
2235 // Check if the requested message was found in array
2236 if (isset($array[$pos])) {
2237 // ... if yes then use it!
2238 $ret = $array[$pos];
2240 // ... else use default message
2248 // Convert ';' to ', ' for e.g. receiver list
2249 function convertReceivers ($old) {
2250 return str_replace(';', ', ', $old);
2253 // Get a module from filename and access level
2254 function getModuleFromFileName ($file, $accessLevel) {
2255 // Default is 'invalid';
2256 $modCheck = 'invalid';
2258 // @TODO This is still very static, rewrite it somehow
2259 switch ($accessLevel) {
2261 $modCheck = 'admin';
2267 $modCheck = getModule();
2270 default: // Unsupported file name / access level
2271 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2279 // Encodes an URL for adding session id, etc.
2280 function encodeUrl ($url, $outputMode = '0') {
2281 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2282 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) return $url;
2284 // Do we have a valid session?
2285 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2287 // Determine right seperator
2288 $seperator = '&';
2289 if (strpos($url, '?') === false) {
2292 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2298 if (session_id() != '') {
2299 $url .= $seperator . session_name() . '=' . session_id();
2304 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2306 $url = '{?URL?}/' . $url;
2313 // Simple check for spider
2314 function isSpider () {
2315 // Get the UA and trim it down
2316 $userAgent = trim(strtolower(detectUserAgent(true)));
2318 // It should not be empty, if so it is better a spider/bot
2319 if (empty($userAgent)) return true;
2322 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2325 // Function to search for the last modified file
2326 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2328 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2329 // Does it match what we are looking for? (We skip a lot files already!)
2330 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2331 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2333 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2334 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2336 // Walk through all entries
2337 foreach ($ds as $d) {
2338 // Generate proper FQFN
2339 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2341 // Is it a file and readable?
2342 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2343 if (isFileReadable($FQFN)) {
2344 // $FQFN is a readable file so extract the requested data from it
2345 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2346 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2348 // Is the file more recent?
2349 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2350 // This file is newer as the file before
2351 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2352 $last_changed['path_name'] = $FQFN;
2353 $last_changed[$lookFor] = $check;
2357 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2362 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2363 function handleFieldWithBraces ($field) {
2364 // Are there braces [] at the end?
2365 if (substr($field, -2, 2) == '[]') {
2366 // Try to find one and replace it. I do it this way to allow easy
2367 // extending of this code.
2368 foreach (array('admin_list_builder_id_value') as $key) {
2369 // Is the cache entry set?
2370 if (isset($GLOBALS[$key])) {
2372 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2384 // Converts a userid so it can be used in SQL queries
2385 function makeDatabaseUserId ($userid) {
2386 // Is it a valid username?
2387 if (isValidUserId($userid)) {
2389 $userid = bigintval($userid);
2391 // Is not valid or zero
2399 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2400 // Note: This function is cached
2401 function capitalizeUnderscoreString ($str) {
2402 // Do we have cache?
2403 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2404 // Init target string
2407 // Explode it with the underscore, but rewrite dashes to underscore before
2408 $strArray = explode('_', str_replace('-', '_', $str));
2410 // "Walk" through all elements and make them lower-case but first upper-case
2411 foreach ($strArray as $part) {
2412 // Capitalize the string part
2413 $capitalized .= ucfirst(strtolower($part));
2416 // Store the converted string in cache array
2417 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2421 return $GLOBALS[__FUNCTION__][$str];
2424 //-----------------------------------------------------------------------------
2425 // Automatically re-created functions, all taken from user comments on www.php.net
2426 //-----------------------------------------------------------------------------
2428 if (!function_exists('html_entity_decode')) {
2429 // Taken from documentation on www.php.net
2430 function html_entity_decode ($string) {
2431 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2432 $trans_tbl = array_flip($trans_tbl);
2433 return strtr($string, $trans_tbl);
2437 if (!function_exists('http_build_query')) {
2438 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
2439 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
2441 foreach ((array)$data as $k => $v) {
2442 if (is_int($k) && $prefix != null) {
2443 $k = urlencode($prefix . $k);
2446 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
2448 if (is_array($v) || is_object($v)) {
2449 array_push($ret, http_build_query($v, '', $sep, $k));
2451 array_push($ret, $k.'='.urlencode($v));
2455 if (empty($sep)) $sep = ini_get('arg_separator.output');
2457 return implode($sep, $ret);