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 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009, 2010 by Mailer Developer Team *
20 * For more information visit: http://www.mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Sends out all headers required for HTTP/1.1 reply
44 function sendHttpHeaders () {
46 $now = gmdate('D, d M Y H:i:s') . ' GMT';
49 sendHeader('HTTP/1.1 ' . getHttpStatus());
51 // General headers for no caching
52 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
53 sendHeader('Last-Modified: ' . $now);
54 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
55 sendHeader('Pragma: no-cache'); // HTTP/1.0
56 sendHeader('Connection: Close');
57 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
58 sendHeader('Content-Language: ' . getLanguage());
61 // Init fatal message array
62 function initFatalMessages () {
63 $GLOBALS['fatal_messages'] = array();
66 // Getter for whole fatal error messages
67 function getFatalArray () {
68 return $GLOBALS['fatal_messages'];
71 // Add a fatal error message to the queue array
72 function addFatalMessage ($F, $L, $message, $extra = '') {
73 if (is_array($extra)) {
74 // Multiple extras for a message with masks
75 $message = call_user_func_array('sprintf', $extra);
76 } elseif (!empty($extra)) {
77 // $message is text with a mask plus extras to insert into the text
78 $message = sprintf($message, $extra);
81 // Add message to $GLOBALS['fatal_messages']
82 $GLOBALS['fatal_messages'][] = $message;
84 // Log fatal messages away
85 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
88 // Getter for total fatal message count
89 function getTotalFatalErrors () {
93 // Do we have at least the first entry?
94 if (!empty($GLOBALS['fatal_messages'][0])) {
96 $count = count($GLOBALS['fatal_messages']);
103 // Send mail out to an email address
104 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
105 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'toEmail=' . $toEmail . ',subject=' . $subject . ',isHtml=' . $isHtml);
108 if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
109 // Value detected, is the message extension installed?
110 // @TODO Extension 'msg' does not exist
111 if (isExtensionActive('msg')) {
112 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
115 // Does the user exist?
116 if (fetchUserData($toEmail)) {
118 $toEmail = getUserData('email');
121 $toEmail = getConfig('WEBMASTER');
124 } elseif ($toEmail == '0') {
126 $toEmail = getConfig('WEBMASTER');
128 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
130 // Check for PHPMailer or debug-mode
131 if ((!checkPhpMailerUsage()) || (isDebugModeEnabled())) {
132 // Prefix is '' for text mails
136 if ($isHtml == 'Y') {
141 // Not in PHPMailer-Mode
142 if (empty($mailHeader)) {
143 // Load email header template
144 $mailHeader = loadEmailTemplate($prefix . 'header');
147 $mailHeader .= loadEmailTemplate($prefix . 'header');
151 // Fix HTML parameter (default is no!)
152 if (empty($isHtml)) {
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 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 // Default is 'menu_unknown'
456 $content['visible_css'] = $prefix . 'menu_unknown';
458 // Translate 'visible' and keep an eye on the prefix
459 switch ($content['visible']) {
461 case 'Y': $content['visible_css'] = $prefix . 'menu_visible' ; break;
462 case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break;
464 // Please report this
465 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, true) . '</pre>');
469 // Translate 'locked' and keep an eye on the prefix
470 switch ($content['locked']) {
472 case 'Y': $content['locked_css'] = $prefix . 'menu_locked' ; break;
473 case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break;
475 // Please report this
476 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, true) . '</pre>');
480 // Return the resulting array
484 // Generates an URL for the dereferer
485 function generateDerefererUrl ($URL) {
486 // Don't de-refer our own links!
487 if (substr($URL, 0, strlen(getUrl())) != getUrl()) {
488 // De-refer this link
489 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
496 // Generates an URL for the frametester
497 function generateFrametesterUrl ($URL) {
498 // Prepare frametester URL
499 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
500 encodeString(compileUriCode($URL))
503 // Return the new URL
504 return $frametesterUrl;
507 // Count entries from e.g. a selection box
508 function countSelection ($array) {
510 if (!is_array($array)) {
512 debug_report_bug(__FUNCTION__, __LINE__, 'No array provided.');
519 foreach ($array as $key => $selected) {
521 if (!empty($selected)) $ret++;
524 // Return counted selections
528 // Generates a timestamp (some wrapper for mktime())
529 function makeTime ($hours, $minutes, $seconds, $stamp) {
530 // Extract day, month and year from given timestamp
531 $days = getDay($stamp);
532 $months = getMonth($stamp);
533 $years = getYear($stamp);
535 // Create timestamp for wished time which depends on extracted date
546 // Redirects to an URL and if neccessarry extends it with own base URL
547 function redirectToUrl ($URL, $allowSpider = true) {
549 if (substr($URL, 0, 6) == '{%url=') $URL = substr($URL, 6, -2);
552 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
554 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
555 $rel = ' rel="external"';
557 // Do we have internal or external URL?
558 if (substr($URL, 0, strlen(getUrl())) == getUrl()) {
559 // Own (=internal) URL
563 // Three different ways to debug...
564 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'URL=' . $URL);
565 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
566 //* DEBUG: */ die($URL);
568 // Simple probe for bots/spiders from search engines
569 if ((isSpider()) && ($allowSpider === true)) {
571 setHttpStatus('200 OK');
573 // Set content-type here to fix a missing array element
574 setContentType('text/html');
576 // Output new location link as anchor
577 outputHtml('<a href="' . $URL . '"' . $rel . '>' . secureString($URL) . '</a>');
578 } elseif (!headers_sent()) {
579 // Clear output buffer
582 // Clear own output buffer
583 $GLOBALS['output'] = '';
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 (still has one reference in this function)
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')) {
661 $keys .= getEncryptSeperator().getSecretKey();
663 if (isConfigEntrySet('file_hash')) {
664 $keys .= getEncryptSeperator().getFileHash();
666 $keys .= getEncryptSeperator() . getDateFromPatchTime();
667 if (isConfigEntrySet('master_salt')) {
668 $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')) {
676 $data .= getEncryptSeperator() . getSession('u_hash');
679 // Add referal id, language, theme and userid
680 $data .= getEncryptSeperator() . determineReferalId();
681 $data .= getEncryptSeperator() . getLanguage();
682 $data .= getEncryptSeperator() . getCurrentTheme();
683 $data .= getEncryptSeperator() . getMemberId();
685 // Calculate number for generating the code
686 $a = $code + getConfig('_ADD') - 1;
688 if (isConfigEntrySet('master_salt')) {
689 // Generate hash with master salt from modula of number with the prime number and other data
690 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, getMasterSalt());
692 // Create number from hash
693 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
695 // Generate hash with "hash of site key" from modula of number with the prime number and other data
696 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, substr(sha1(getConfig('SITE_KEY')), 0, getSaltLength()));
698 // Create number from hash
699 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
702 // At least 10 numbers shall be secure enought!
703 $len = getCodeLength();
704 if ($len == '0') $len = $length;
705 if ($len == '0') $len = 10;
707 // Cut off requested counts of number
708 $return = substr(str_replace('.', '', $rcode), 0, $len);
710 // Done building code
714 // Does only allow numbers
715 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
716 // Filter all numbers out
717 $ret = preg_replace('/[^0123456789]/', '', $num);
720 if ($castValue === true) {
721 // Cast to biggest numeric type
722 $ret = (double) $ret;
725 // Has the whole value changed?
726 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true) && (!is_null($num))) {
728 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
735 // Creates a Uni* timestamp from given selection data and prefix
736 function createTimestampFromSelections ($prefix, $postData) {
737 // Initial return value
740 // Do we have a leap year?
742 $TEST = getYear() / 4;
745 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
746 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getOneDay();
748 // First add years...
749 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
752 $ret += $postData[$prefix . '_mo'] * 2628000;
755 $ret += $postData[$prefix . '_we'] * 604800;
758 $ret += $postData[$prefix . '_da'] * 86400;
761 $ret += $postData[$prefix . '_ho'] * 3600;
764 $ret += $postData[$prefix . '_mi'] * 60;
766 // And at last seconds...
767 $ret += $postData[$prefix . '_se'];
769 // Return calculated value
773 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
774 function createFancyTime ($stamp) {
775 // Get data array with years/months/weeks/days/...
776 $data = createTimeSelections($stamp, '', '', '', true);
778 foreach($data as $k => $v) {
780 // Value is greater than 0 "eval" data to return string
781 $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
786 // Do we have something there?
787 if (strlen($ret) > 0) {
788 // Remove leading commata and space
789 $ret = substr($ret, 2);
792 $ret = '0 {--_SECONDS--}';
795 // Return fancy time string
799 // Extract host from script name
800 function extractHostnameFromUrl (&$script) {
801 // Use default SERVER_URL by default... ;) So?
802 $url = getServerUrl();
804 // Is this URL valid?
805 if (substr($script, 0, 7) == 'http://') {
806 // Use the hostname from script URL as new hostname
807 $url = substr($script, 7);
808 $extract = explode('/', $url);
810 // Done extracting the URL :)
814 $host = str_replace('http://', '', $url);
815 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
817 // Generate relative URL
818 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
819 if (substr(strtolower($script), 0, 7) == 'http://') {
820 // But only if http:// is in front!
821 $script = substr($script, (strlen($url) + 7));
822 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
824 $script = substr($script, (strlen($url) + 8));
827 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
828 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
834 // Send a GET request
835 function sendGetRequest ($script, $data = array()) {
836 // Extract host name from script
837 $host = extractHostnameFromUrl($script);
840 $body = http_build_query($data, '', '&');
842 // There should be data, else we don't need to extend $script with $body
844 // Do we have a question-mark in the script?
845 if (strpos($script, '?') === false) {
846 // No, so first char must be question mark
856 // Remove trailed & to make it more conform
857 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
860 // Generate GET request header
861 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
862 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
863 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
864 if (isConfigEntrySet('FULL_VERSION')) {
865 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
867 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
869 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
870 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
871 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
872 $request .= 'Connection: close' . getConfig('HTTP_EOL');
873 $request .= getConfig('HTTP_EOL');
875 // Send the raw request
876 $response = sendRawRequest($host, $request);
878 // Return the result to the caller function
882 // Send a POST request
883 function sendPostRequest ($script, $postData) {
884 // Is postData an array?
885 if (!is_array($postData)) {
887 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
888 return array('', '', '');
891 // Extract host name from script
892 $host = extractHostnameFromUrl($script);
894 // Construct request body
895 $body = http_build_query($postData, '', '&');
897 // Generate POST request header
898 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
899 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
900 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
901 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
902 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
903 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
904 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
905 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
906 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
907 $request .= 'Connection: close' . getConfig('HTTP_EOL');
908 $request .= getConfig('HTTP_EOL');
913 // Send the raw request
914 $response = sendRawRequest($host, $request);
916 // Return the result to the caller function
920 // Sends a raw request to another host
921 function sendRawRequest ($host, $request) {
922 // Init errno and errdesc with 'all fine' values
923 $errno = '0'; $errdesc = '';
926 $response = array('', '', '');
928 // Default is not to use proxy
931 // Are proxy settins set?
938 loadIncludeOnce('inc/classes/resolver.class.php');
940 // Get resolver instance
941 $resolver = new HostnameResolver();
944 //* DEBUG: */ die('SCRIPT=' . $script);
945 if ($useProxy === true) {
946 // Resolve hostname into IP address
947 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
949 // Connect to host through proxy connection
950 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
952 // Resolve hostname into IP address
953 $ip = $resolver->resolveHostname($host);
955 // Connect to host directly
956 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
960 if (!is_resource($fp)) {
962 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
964 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
965 // Cannot set non-blocking mode or timeout
966 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
971 if ($useProxy === true) {
972 // Setup proxy tunnel
973 $response = setupProxyTunnel($host, $fp);
975 // If the response is invalid, abort
976 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
978 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
984 fwrite($fp, $request);
987 $start = microtime(true);
991 // Get info from stream
992 $info = stream_get_meta_data($fp);
994 // Is it timed out? 15 seconds is a really patient...
995 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
997 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1003 // Get line from stream
1004 $line = fgets($fp, 128);
1006 // Ignore empty lines because of non-blocking mode
1008 // uslepp a little to avoid 100% CPU load
1015 // Add it to response
1016 $response[] = trim($line);
1022 // Time request if debug-mode is enabled
1023 if (isDebugModeEnabled()) {
1024 // Add debug message...
1025 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1028 // Skip first empty lines
1030 foreach ($resp as $idx => $line) {
1032 $line = trim($line);
1034 // Is this line empty?
1037 array_shift($response);
1039 // Abort on first non-empty line
1044 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1045 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1047 // Proxy agent found or something went wrong?
1048 if (!isset($response[0])) {
1049 // No response, maybe timeout
1050 $response = array('', '', '');
1051 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1052 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1053 // Proxy header detected, so remove two lines
1054 array_shift($response);
1055 array_shift($response);
1058 // Was the request successfull?
1059 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1060 // Not found / access forbidden
1061 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1062 $response = array('', '', '');
1069 // Sets up a proxy tunnel for given hostname and through resource
1070 function setupProxyTunnel ($host, $resource) {
1072 $response = array('', '', '');
1074 // Generate CONNECT request header
1075 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1076 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1078 // Use login data to proxy? (username at least!)
1079 if (getConfig('proxy_username') != '') {
1081 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1082 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1085 // Add last new-line
1086 $proxyTunnel .= getConfig('HTTP_EOL');
1087 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1090 fwrite($fp, $proxyTunnel);
1094 // No response received
1098 // Read the first line
1099 $resp = trim(fgets($fp, 10240));
1100 $respArray = explode(' ', $resp);
1101 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1102 // Invalid response!
1110 // Taken from www.php.net isInStringIgnoreCase() user comments
1111 function isEmailValid ($email) {
1112 // Check first part of email address
1113 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1116 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1119 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1121 // Return check result
1122 return preg_match($regex, $email);
1125 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1126 function isUrlValid ($URL, $compile=true) {
1127 // Trim URL a little
1128 $URL = trim(urldecode($URL));
1129 //* DEBUG: */ debugOutput($URL);
1131 // Compile some chars out...
1132 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1133 //* DEBUG: */ debugOutput($URL);
1135 // Check for the extension filter
1136 if (isExtensionActive('filter')) {
1137 // Use the extension's filter set
1138 return FILTER_VALIDATE_URL($URL, false);
1141 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1142 // https:// in front of the URLs
1143 return isUrlValidSimple($URL);
1146 // Generate a hash for extra-security for all passwords
1147 function generateHash ($plainText, $salt = '', $hash = true) {
1149 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
1151 // Is the required extension 'sql_patches' there and a salt is not given?
1152 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
1153 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
1154 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1155 if ($hash === true) {
1156 // Is plain password
1157 return md5($plainText);
1159 // Is already a hash
1164 // Do we miss an arry element here?
1165 if (!isConfigEntrySet('file_hash')) {
1167 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
1170 // When the salt is empty build a new one, else use the first x configured characters as the salt
1172 // Build server string for more entropy
1173 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
1176 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
1179 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
1181 // Calculate number for generating the code
1182 $a = time() + getConfig('_ADD') - 1;
1184 // Generate SHA1 sum from modula of number and the prime number
1185 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a);
1186 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
1187 $sha1 = scrambleString($sha1);
1188 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
1189 //* DEBUG: */ $sha1b = descrambleString($sha1);
1190 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
1192 // Generate the password salt string
1193 $salt = substr($sha1, 0, getSaltLength());
1194 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
1197 //* DEBUG: */ debugOutput('salt=' . $salt);
1198 $salt = substr($salt, 0, getSaltLength());
1199 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
1201 // Sanity check on salt
1202 if (strlen($salt) != getSaltLength()) {
1204 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
1208 // Generate final hash (for debug output)
1209 $finalHash = $salt . sha1($salt . $plainText);
1212 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
1218 // Scramble a string
1219 function scrambleString ($str) {
1223 // Final check, in case of failture it will return unscrambled string
1224 if (strlen($str) > 40) {
1225 // The string is to long
1227 } elseif (strlen($str) == 40) {
1229 $scrambleNums = explode(':', getPassScramble());
1231 // Generate new numbers
1232 $scrambleNums = explode(':', genScrambleString(strlen($str)));
1235 // Compare both lengths and abort if different
1236 if (strlen($str) != count($scrambleNums)) return $str;
1238 // Scramble string here
1239 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
1240 for ($idx = 0; $idx < strlen($str); $idx++) {
1241 // Get char on scrambled position
1242 $char = substr($str, $scrambleNums[$idx], 1);
1244 // Add it to final output string
1245 $scrambled .= $char;
1248 // Return scrambled string
1249 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
1253 // De-scramble a string scrambled by scrambleString()
1254 function descrambleString ($str) {
1255 // Scramble only 40 chars long strings
1256 if (strlen($str) != 40) return $str;
1258 // Load numbers from config
1259 $scrambleNums = explode(':', getPassScramble());
1262 if (count($scrambleNums) != 40) return $str;
1264 // Begin descrambling
1265 $orig = str_repeat(' ', 40);
1266 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
1267 for ($idx = 0; $idx < 40; $idx++) {
1268 $char = substr($str, $idx, 1);
1269 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1272 // Return scrambled string
1273 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1277 // Generated a "string" for scrambling
1278 function genScrambleString ($len) {
1279 // Prepare array for the numbers
1280 $scrambleNumbers = array();
1282 // First we need to setup randomized numbers from 0 to 31
1283 for ($idx = 0; $idx < $len; $idx++) {
1285 $rand = mt_rand(0, ($len - 1));
1287 // Check for it by creating more numbers
1288 while (array_key_exists($rand, $scrambleNumbers)) {
1289 $rand = mt_rand(0, ($len - 1));
1293 $scrambleNumbers[$rand] = $rand;
1296 // So let's create the string for storing it in database
1297 $scrambleString = implode(':', $scrambleNumbers);
1298 return $scrambleString;
1301 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1302 function encodeHashForCookie ($passHash) {
1303 // Return vanilla password hash
1306 // Is a secret key and master salt already initialized?
1307 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1308 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1309 // Only calculate when the secret key is generated
1310 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1311 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1312 // Both keys must have same length so return unencrypted
1313 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1317 $newHash = ''; $start = 9;
1318 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1319 for ($idx = 0; $idx < 20; $idx++) {
1320 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1321 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1322 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1323 $mod = dechex($idx);
1324 if ($part1 > $part2) {
1325 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1326 } elseif ($part2 > $part1) {
1327 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1329 $mod = substr($mod, 0, 2);
1330 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1331 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1332 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1337 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1338 $ret = generateHash($newHash, getMasterSalt());
1342 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1346 // Fix "deleted" cookies
1347 function fixDeletedCookies ($cookies) {
1348 // Is this an array with entries?
1349 if ((is_array($cookies)) && (count($cookies) > 0)) {
1350 // Then check all cookies if they are marked as deleted!
1351 foreach ($cookies as $cookieName) {
1352 // Is the cookie set to "deleted"?
1353 if (getSession($cookieName) == 'deleted') {
1354 setSession($cookieName, '');
1360 // Checks if a given apache module is loaded
1361 function isApacheModuleLoaded ($apacheModule) {
1362 // Check it and return result
1363 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1366 // Get current theme name
1367 function getCurrentTheme () {
1368 // The default theme is 'default'... ;-)
1371 // Do we have ext-theme installed and active?
1372 if (isExtensionActive('theme')) {
1373 // Call inner method
1374 $ret = getActualTheme();
1377 // Return theme value
1381 // Generates an error code from given account status
1382 function generateErrorCodeFromUserStatus ($status = '') {
1383 // If no status is provided, use the default, cached
1384 if ((empty($status)) && (isMember())) {
1386 $status = getUserData('status');
1389 // Default error code if unknown account status
1390 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1392 // Generate constant name
1393 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1395 // Is the constant there?
1396 if (isCodeSet($codeName)) {
1398 $errorCode = getCode($codeName);
1401 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1404 // Return error code
1408 // Back-ported from the new ship-simu engine. :-)
1409 function debug_get_printable_backtrace () {
1411 $backtrace = '<ol>';
1413 // Get and prepare backtrace for output
1414 $backtraceArray = debug_backtrace();
1415 foreach ($backtraceArray as $key => $trace) {
1416 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1417 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1418 if (!isset($trace['args'])) $trace['args'] = array();
1419 $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>';
1423 $backtrace .= '</ol>';
1425 // Return the backtrace
1429 // A mail-able backtrace
1430 function debug_get_mailable_backtrace () {
1434 // Get and prepare backtrace for output
1435 $backtraceArray = debug_backtrace();
1436 foreach ($backtraceArray as $key => $trace) {
1437 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1438 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1439 if (!isset($trace['args'])) $trace['args'] = array();
1440 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1443 // Return the backtrace
1447 // Generates a ***weak*** seed
1448 function generateSeed () {
1449 return microtime(true) * 100000;
1452 // Converts a message code to a human-readable message
1453 function getMessageFromErrorCode ($code) {
1457 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1458 case getCode('LOGOUT_FAILED') : $message = '<span class="notice">{--LOGOUT_FAILED--}</span>'; break;
1459 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1460 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1461 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1462 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1463 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1464 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1465 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1466 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1467 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1468 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1469 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1470 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1471 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1472 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1473 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1474 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1475 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1476 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1477 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1478 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1479 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1480 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1481 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1482 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1483 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1484 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1485 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1486 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1488 case getCode('ERROR_MAILID'):
1489 if (isExtensionActive('mailid', true)) {
1490 $message = '{--ERROR_CONFIRMING_MAIL--}';
1492 $message = generateExtensionInactiveNotInstalledMessage('mailid');
1496 case getCode('EXTENSION_PROBLEM'):
1497 if (isGetRequestParameterSet('ext')) {
1498 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1500 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1504 case getCode('URL_TIME_LOCK'):
1505 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1506 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1507 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1509 // Load timestamp from last order
1510 $content = SQL_FETCHARRAY($result);
1513 SQL_FREERESULT($result);
1515 // Translate it for templates
1516 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1518 // Calculate hours...
1519 $content['hours'] = round(getConfig('url_tlock') / 60 / 60);
1522 $content['minutes'] = round((getConfig('url_tlock') - $content['hours'] * 60 * 60) / 60);
1525 $content['seconds'] = round(getConfig('url_tlock') - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1527 // Finally contruct the message
1528 $message = loadTemplate('tlock_message', true, $content);
1532 // Missing/invalid code
1533 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1536 logDebugMessage(__FUNCTION__, __LINE__, $message);
1540 // Return the message
1544 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1545 function isUrlValidSimple ($url) {
1547 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1549 // Allows http and https
1550 $http = "(http|https)+(:\/\/)";
1552 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1553 // Test double-domains (e.g. .de.vu)
1554 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1556 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1558 $dir = "((/)+([-_\.[:alnum:]])+)*";
1560 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1561 // ... and the string after and including question character
1562 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1563 // Pattern for URLs like http://url/dir/doc.html?var=value
1564 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1565 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1566 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1567 // Pattern for URLs like http://url/dir/?var=value
1568 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1569 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1570 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1571 // Pattern for URLs like http://url/dir/page.ext
1572 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1573 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1574 $pattern['ipdp'] = $http . $ip . $dir . $page;
1575 // Pattern for URLs like http://url/dir
1576 $pattern['d1d'] = $http . $domain1 . $dir;
1577 $pattern['d2d'] = $http . $domain2 . $dir;
1578 $pattern['ipd'] = $http . $ip . $dir;
1579 // Pattern for URLs like http://url/?var=value
1580 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1581 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1582 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1583 // Pattern for URLs like http://url?var=value
1584 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1585 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1586 $pattern['ipg12'] = $http . $ip . $getstring1;
1588 // Test all patterns
1590 foreach ($pattern as $key => $pat) {
1592 if (isDebugRegularExpressionEnabled()) {
1593 // @TODO Are these convertions still required?
1594 $pat = str_replace('.', '\.', $pat);
1595 $pat = str_replace('@', '\@', $pat);
1596 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1599 // Check if expression matches
1600 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1603 if ($reg === true) break;
1606 // Return true/false
1610 // Wtites data to a config.php-style file
1611 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1612 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1613 // Initialize some variables
1619 // Is the file there and read-/write-able?
1620 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1621 $search = 'CFG: ' . $comment;
1622 $tmp = $FQFN . '.tmp';
1624 // Open the source file
1625 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1627 // Is the resource valid?
1628 if (is_resource($fp)) {
1629 // Open temporary file
1630 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1632 // Is the resource again valid?
1633 if (is_resource($fp_tmp)) {
1634 // Mark temporary file as readable
1635 $GLOBALS['file_readable'][$tmp] = true;
1638 while (!feof($fp)) {
1639 // Read from source file
1640 $line = fgets ($fp, 1024);
1642 if (strpos($line, $search) > -1) {
1648 if ($next === $seek) {
1650 $line = $prefix . $DATA . $suffix . "\n";
1656 // Write to temp file
1657 fwrite($fp_tmp, $line);
1663 // Finished writing tmp file
1667 // Close source file
1670 if (($done === true) && ($found === true)) {
1671 // Copy back tmp file and delete tmp :-)
1672 copyFileVerified($tmp, $FQFN, 0644);
1673 return removeFile($tmp);
1674 } elseif ($found === false) {
1675 outputHtml('<strong>CHANGE:</strong> 404!');
1677 outputHtml('<strong>TMP:</strong> UNDONE!');
1681 // File not found, not readable or writeable
1682 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1685 // An error was detected!
1688 // Send notification to admin
1689 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
1690 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1692 sendAdminsEmails($subject, $templateName, $content, $userid);
1694 // Send out out-dated way
1695 $message = loadEmailTemplate($templateName, $content, $userid);
1696 sendAdminEmails($subject, $message);
1700 // Debug message logger
1701 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1702 // Is debug mode enabled?
1703 if ((isDebugModeEnabled()) || ($force === true)) {
1705 $message = str_replace("\r", '', str_replace("\n", '', $message));
1707 // Log this message away
1708 $fp = fopen(getCachePath() . 'debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write logfile debug.log!');
1709 fwrite($fp, generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
1714 // Handle extra values
1715 function handleExtraValues ($filterFunction, $value, $extraValue) {
1716 // Default is the value itself
1719 // Do we have a special filter function?
1720 if (!empty($filterFunction)) {
1721 // Does the filter function exist?
1722 if (function_exists($filterFunction)) {
1723 // Do we have extra parameters here?
1724 if (!empty($extraValue)) {
1725 // Put both parameters in one new array by default
1726 $args = array($value, $extraValue);
1728 // If we have an array simply use it and pre-extend it with our value
1729 if (is_array($extraValue)) {
1730 // Make the new args array
1731 $args = merge_array(array($value), $extraValue);
1734 // Call the multi-parameter call-back
1735 $ret = call_user_func_array($filterFunction, $args);
1737 // One parameter call
1738 $ret = call_user_func($filterFunction, $value);
1747 // Converts timestamp selections into a timestamp
1748 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1749 // Init test variable
1753 // Get last three chars
1754 $test = substr($id, -3);
1756 // Improved way of checking! :-)
1757 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1758 // Found a multi-selection for timings?
1759 $test = substr($id, 0, -3);
1760 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)) {
1761 // Generate timestamp
1762 $postData[$test] = createTimestampFromSelections($test, $postData);
1763 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1764 $GLOBALS['skip_config'][$test] = true;
1766 // Remove data from array
1767 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1768 unset($postData[$test . '_' . $rem]);
1779 // Reverts the german decimal comma into Computer decimal dot
1780 function convertCommaToDot ($str) {
1781 // Default float is not a float... ;-)
1784 // Which language is selected?
1785 switch (getLanguage()) {
1786 case 'de': // German language
1787 // Remove german thousand dots first
1788 $str = str_replace('.', '', $str);
1790 // Replace german commata with decimal dot and cast it
1791 $float = (float)str_replace(',', '.', $str);
1794 default: // US and so on
1795 // Remove thousand dots first and cast
1796 $float = (float)str_replace(',', '', $str);
1804 // Handle menu-depending failed logins and return the rendered content
1805 function handleLoginFailures ($accessLevel) {
1806 // Default output is empty ;-)
1809 // Is the session data set?
1810 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1811 // Ignore zero values
1812 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1813 // Non-guest has login failures found, get both data and prepare it for template
1814 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1816 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1817 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1821 $OUT = loadTemplate('login_failures', true, $content);
1824 // Reset session data
1825 setSession('mailer_' . $accessLevel . '_failures', '');
1826 setSession('mailer_' . $accessLevel . '_last_failure', '');
1829 // Return rendered content
1834 function rebuildCache ($cache, $inc = '', $force = false) {
1836 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1838 // Shall I remove the cache file?
1839 if (isCacheInstanceValid()) {
1841 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1843 $GLOBALS['cache_instance']->removeCacheFile($force);
1846 // Include file given?
1849 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
1851 // Is the include there?
1852 if (isIncludeReadable($inc)) {
1853 // And rebuild it from scratch
1854 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1857 // Include not found!
1858 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1864 // Determines the real remote address
1865 function determineRealRemoteAddress () {
1866 // Is a proxy in use?
1867 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1869 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1870 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
1871 // Yet, another proxy
1872 $address = $_SERVER['HTTP_CLIENT_IP'];
1874 // The regular address when no proxy was used
1875 $address = $_SERVER['REMOTE_ADDR'];
1878 // This strips out the real address from proxy output
1879 if (strstr($address, ',')) {
1880 $addressArray = explode(',', $address);
1881 $address = $addressArray[0];
1884 // Return the result
1888 // Adds a bonus mail to the queue
1889 // This is a high-level function!
1890 function addNewBonusMail ($data, $mode = '', $output=true) {
1891 // Use mode from data if not set and availble ;-)
1892 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
1894 // Generate receiver list
1895 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1898 if (!empty($receiver)) {
1899 // Add bonus mail to queue
1900 addBonusMailToQueue(
1912 // Mail inserted into bonus pool
1913 if ($output === true) {
1914 loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
1916 } elseif ($output === true) {
1917 // More entered than can be reached!
1918 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
1921 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1925 // Determines referal id and sets it
1926 function determineReferalId () {
1927 // Skip this in non-html-mode and outside ref.php
1928 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
1930 // Check if refid is set
1931 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1933 } elseif (isPostRequestParameterSet('refid')) {
1934 // Get referal id from POST element refid
1935 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1936 } elseif (isGetRequestParameterSet('refid')) {
1937 // Get referal id from GET parameter refid
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 ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1943 // The variable user comes from click.php
1944 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1945 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1946 // Set session refid als global
1947 $GLOBALS['refid'] = bigintval(getSession('refid'));
1948 } elseif (isRandomReferalIdEnabled()) {
1949 // Select a random user which has confirmed enougth mails
1950 $GLOBALS['refid'] = determineRandomReferalId();
1951 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
1952 // Set default refid as refid in URL
1953 $GLOBALS['refid'] = getDefRefid();
1955 // No default id when sql_patches is not installed or none set
1956 $GLOBALS['refid'] = null;
1959 // Set cookie when default refid > 0
1960 if (!isSessionVariableSet('refid') || (isValidUserId($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
1961 // Default is not found
1964 // Do we have nickname or userid set?
1965 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1966 // Nickname in URL, so load the id
1967 $found = fetchUserData($GLOBALS['refid'], 'nickname');
1968 } elseif (isValidUserId($GLOBALS['refid'])) {
1969 // Direct userid entered
1970 $found = fetchUserData($GLOBALS['refid']);
1973 // Is the record valid?
1974 if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
1975 // No, then reset referal id
1976 $GLOBALS['refid'] = getDefRefid();
1980 setSession('refid', $GLOBALS['refid']);
1983 // Return determined refid
1984 return $GLOBALS['refid'];
1987 // Enables the reset mode and runs it
1988 function doReset () {
1989 // Enable the reset mode
1990 $GLOBALS['reset_enabled'] = true;
1993 runFilterChain('reset');
1996 // Our shutdown-function
1997 function shutdown () {
1998 // Call the filter chain 'shutdown'
1999 runFilterChain('shutdown', null);
2001 // Check if not in installation phase and the link is up
2002 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
2004 SQL_CLOSE(__FUNCTION__, __LINE__);
2005 } elseif (!isInstallationPhase()) {
2007 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
2010 // Stop executing here
2015 function initMemberId () {
2016 $GLOBALS['member_id'] = '0';
2019 // Setter for member id
2020 function setMemberId ($memberid) {
2021 // We should not set member id to zero
2022 if ($memberid == '0') {
2023 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
2027 $GLOBALS['member_id'] = bigintval($memberid);
2030 // Getter for member id or returns zero
2031 function getMemberId () {
2032 // Default member id
2035 // Is the member id set?
2036 if (isMemberIdSet()) {
2038 $memberid = $GLOBALS['member_id'];
2045 // Checks ether the member id is set
2046 function isMemberIdSet () {
2047 return (isset($GLOBALS['member_id']));
2050 // Setter for extra title
2051 function setExtraTitle ($extraTitle) {
2052 $GLOBALS['extra_title'] = $extraTitle;
2055 // Getter for extra title
2056 function getExtraTitle () {
2057 // Is the extra title set?
2058 if (!isExtraTitleSet()) {
2059 // No, then abort here
2060 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
2064 return $GLOBALS['extra_title'];
2067 // Checks if the extra title is set
2068 function isExtraTitleSet () {
2069 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
2072 // Reads a directory recursively by default and searches for files not matching
2073 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
2074 // a whole directory.
2075 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
2076 // Add default entries we should exclude
2077 $excludeArray[] = '.';
2078 $excludeArray[] = '..';
2079 $excludeArray[] = '.svn';
2080 $excludeArray[] = '.htaccess';
2082 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
2087 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
2090 while ($baseFile = readdir($dirPointer)) {
2091 // Exclude '.', '..' and entries in $excludeArray automatically
2092 if (in_array($baseFile, $excludeArray, true)) {
2094 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
2098 // Construct include filename and FQFN
2099 $fileName = $baseDir . $baseFile;
2100 $FQFN = getPath() . $fileName;
2102 // Remove double slashes
2103 $FQFN = str_replace('//', '/', $FQFN);
2105 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
2106 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
2107 // These Lines are only for debugging!!
2108 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
2109 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
2110 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
2116 // Skip also files with non-matching prefix genericly
2117 if (($recursive === true) && (isDirectory($FQFN))) {
2118 // Is a redirectory so read it as well
2119 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
2121 // And skip further processing
2123 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
2125 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
2127 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
2128 // Skip wrong suffix as well
2129 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
2131 } elseif (!isFileReadable($FQFN)) {
2132 // Not readable so skip it
2133 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
2137 // Is the file a PHP script or other?
2138 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
2139 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
2140 // Is this a valid include file?
2141 if ($extension == '.php') {
2142 // Remove both for extension name
2143 $extName = substr($baseFile, strlen($prefix), -4);
2145 // Is the extension valid and active?
2146 if (isExtensionNameValid($extName)) {
2147 // Then add this file
2148 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
2149 $files[] = $fileName;
2151 // Add non-extension files as well
2152 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
2153 if ($addBaseDir === true) {
2154 $files[] = $fileName;
2156 $files[] = $baseFile;
2160 // We found .php file but should not search for them, why?
2161 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
2163 } elseif (substr($baseFile, -4, 4) == $extension) {
2164 // Other, generic file found
2165 $files[] = $fileName;
2170 closedir($dirPointer);
2175 // Return array with include files
2176 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
2180 // Maps a module name into a database table name
2181 function mapModuleToTable ($moduleName) {
2182 // Map only these, still lame code...
2183 switch ($moduleName) {
2184 // 'index' is the guest's menu
2185 case 'index': $moduleName = 'guest'; break;
2186 // ... and 'login' the member's menu
2187 case 'login': $moduleName = 'member'; break;
2188 // Anything else will not be mapped, silently.
2195 // Add SQL debug data to array for later output
2196 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
2197 // Do we have cache?
2198 if (!isset($GLOBALS['debug_sql_available'])) {
2199 // Check it and cache it in $GLOBALS
2200 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
2203 // Don't execute anything here if we don't need or ext-other is missing
2204 if ($GLOBALS['debug_sql_available'] === false) {
2208 // Already executed?
2209 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
2210 // Then abort here, we don't need to profile a query twice
2214 // Remeber this as profiled (or not, but we don't care here)
2215 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
2219 'num_rows' => SQL_NUMROWS($result),
2220 'affected' => SQL_AFFECTEDROWS(),
2221 'sql_str' => $sqlString,
2222 'timing' => $timing,
2223 'file' => basename($F),
2228 $GLOBALS['debug_sqls'][] = $record;
2231 // Initializes the cache instance
2232 function initCacheInstance () {
2233 // Check for double-initialization
2234 if (isset($GLOBALS['cache_instance'])) {
2235 // This should not happen and must be fixed
2236 debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
2239 // Load include for CacheSystem class
2240 loadIncludeOnce('inc/classes/cachesystem.class.php');
2242 // Initialize cache system only when it's needed
2243 $GLOBALS['cache_instance'] = new CacheSystem();
2246 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
2247 // Failed to initialize cache sustem
2248 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2252 // Getter for message from array or raw message
2253 function getMessageFromIndexedArray ($message, $pos, $array) {
2254 // Check if the requested message was found in array
2255 if (isset($array[$pos])) {
2256 // ... if yes then use it!
2257 $ret = $array[$pos];
2259 // ... else use default message
2267 // Convert ';' to ', ' for e.g. receiver list
2268 function convertReceivers ($old) {
2269 return str_replace(';', ', ', $old);
2272 // Get a module from filename and access level
2273 function getModuleFromFileName ($file, $accessLevel) {
2274 // Default is 'invalid';
2275 $modCheck = 'invalid';
2277 // @TODO This is still very static, rewrite it somehow
2278 switch ($accessLevel) {
2280 $modCheck = 'admin';
2286 $modCheck = getModule();
2289 default: // Unsupported file name / access level
2290 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2298 // Encodes an URL for adding session id, etc.
2299 function encodeUrl ($url, $outputMode = '0') {
2300 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2301 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) return $url;
2303 // Do we have a valid session?
2304 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2306 // Determine right seperator
2307 $seperator = '&';
2308 if (strpos($url, '?') === false) {
2311 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2317 if (session_id() != '') {
2318 $url .= $seperator . session_name() . '=' . session_id();
2323 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2325 $url = '{?URL?}/' . $url;
2332 // Simple check for spider
2333 function isSpider () {
2334 // Get the UA and trim it down
2335 $userAgent = trim(strtolower(detectUserAgent(true)));
2337 // It should not be empty, if so it is better a spider/bot
2338 if (empty($userAgent)) return true;
2341 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2344 // Function to search for the last modified file
2345 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2347 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2348 // Does it match what we are looking for? (We skip a lot files already!)
2349 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2350 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2352 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2353 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2355 // Walk through all entries
2356 foreach ($ds as $d) {
2357 // Generate proper FQFN
2358 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2360 // Is it a file and readable?
2361 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2362 if (isFileReadable($FQFN)) {
2363 // $FQFN is a readable file so extract the requested data from it
2364 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2365 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2367 // Is the file more recent?
2368 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2369 // This file is newer as the file before
2370 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2371 $last_changed['path_name'] = $FQFN;
2372 $last_changed[$lookFor] = $check;
2376 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2381 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2382 function handleFieldWithBraces ($field) {
2383 // Are there braces [] at the end?
2384 if (substr($field, -2, 2) == '[]') {
2385 // Try to find one and replace it. I do it this way to allow easy
2386 // extending of this code.
2387 foreach (array('admin_list_builder_id_value') as $key) {
2388 // Is the cache entry set?
2389 if (isset($GLOBALS[$key])) {
2391 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2403 // Converts a userid so it can be used in SQL queries
2404 function makeDatabaseUserId ($userid) {
2405 // Is it a valid username?
2406 if (isValidUserId($userid)) {
2408 $userid = bigintval($userid);
2410 // Is not valid or zero
2418 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2419 // Note: This function is cached
2420 function capitalizeUnderscoreString ($str) {
2421 // Do we have cache?
2422 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2423 // Init target string
2426 // Explode it with the underscore, but rewrite dashes to underscore before
2427 $strArray = explode('_', str_replace('-', '_', $str));
2429 // "Walk" through all elements and make them lower-case but first upper-case
2430 foreach ($strArray as $part) {
2431 // Capitalize the string part
2432 $capitalized .= ucfirst(strtolower($part));
2435 // Store the converted string in cache array
2436 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2440 return $GLOBALS[__FUNCTION__][$str];
2443 //-----------------------------------------------------------------------------
2444 // Automatically re-created functions, all taken from user comments on www.php.net
2445 //-----------------------------------------------------------------------------
2447 if (!function_exists('html_entity_decode')) {
2448 // Taken from documentation on www.php.net
2449 function html_entity_decode ($string) {
2450 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2451 $trans_tbl = array_flip($trans_tbl);
2452 return strtr($string, $trans_tbl);
2456 if (!function_exists('http_build_query')) {
2457 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
2458 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
2460 foreach ((array) $data as $k => $v) {
2461 if (is_int($k) && $prefix != null) {
2462 $k = urlencode($prefix . $k);
2465 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
2467 if (is_array($v) || is_object($v)) {
2468 array_push($ret, http_build_query($v, '', $sep, $k));
2470 array_push($ret, $k.'='.urlencode($v));
2474 if (empty($sep)) $sep = ini_get('arg_separator.output');
2476 return implode($sep, $ret);