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-database functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-Datenbank-Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 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 = getPassLen();
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 // Default status is unknown if something goes through
431 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
433 // Generate message depending on status
438 $ret = sprintf("{--ACCOUNT_STATUS_%s--}", $status);
443 $ret = '{--ACCOUNT_STATUS_DELETED--}';
447 // Please report all unknown status
448 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
456 // "Translates" 'visible' and 'locked' to a CSS class
457 function translateMenuVisibleLocked ($content, $prefix = '') {
458 // Default is 'menu_unknown'
459 $content['visible_css'] = $prefix . 'menu_unknown';
461 // Translate 'visible' and keep an eye on the prefix
462 switch ($content['visible']) {
464 case 'Y': $content['visible_css'] = $prefix . 'menu_visible' ; break;
465 case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break;
467 // Please report this
468 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, true) . '</pre>');
472 // Translate 'locked' and keep an eye on the prefix
473 switch ($content['locked']) {
475 case 'Y': $content['locked_css'] = $prefix . 'menu_locked' ; break;
476 case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break;
478 // Please report this
479 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, true) . '</pre>');
483 // Return the resulting array
487 // Generates an URL for the dereferer
488 function generateDerefererUrl ($URL) {
489 // Don't de-refer our own links!
490 if (substr($URL, 0, strlen(getUrl())) != getUrl()) {
491 // De-refer this link
492 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
499 // Generates an URL for the frametester
500 function generateFrametesterUrl ($URL) {
501 // Prepare frametester URL
502 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
503 encodeString(compileUriCode($URL))
506 // Return the new URL
507 return $frametesterUrl;
510 // Count entries from e.g. a selection box
511 function countSelection ($array) {
513 if (!is_array($array)) {
515 debug_report_bug(__FUNCTION__, __LINE__, 'No array provided.');
522 foreach ($array as $key => $selected) {
524 if (!empty($selected)) $ret++;
527 // Return counted selections
531 // Generates a timestamp (some wrapper for mktime())
532 function makeTime ($hours, $minutes, $seconds, $stamp) {
533 // Extract day, month and year from given timestamp
534 $days = getDay($stamp);
535 $months = getMonth($stamp);
536 $years = getYear($stamp);
538 // Create timestamp for wished time which depends on extracted date
549 // Redirects to an URL and if neccessarry extends it with own base URL
550 function redirectToUrl ($URL, $allowSpider = true) {
552 if (substr($URL, 0, 6) == '{%url=') $URL = substr($URL, 6, -2);
555 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
557 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
558 $rel = ' rel="external"';
560 // Do we have internal or external URL?
561 if (substr($URL, 0, strlen(getUrl())) == getUrl()) {
562 // Own (=internal) URL
566 // Three different ways to debug...
567 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'URL=' . $URL);
568 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
569 //* DEBUG: */ die($URL);
571 // Simple probe for bots/spiders from search engines
572 if ((isSpider()) && ($allowSpider === true)) {
574 setHttpStatus('200 OK');
576 // Set content-type here to fix a missing array element
577 setContentType('text/html');
579 // Output new location link as anchor
580 outputHtml('<a href="' . $URL . '"' . $rel . '>' . secureString($URL) . '</a>');
581 } elseif (!headers_sent()) {
582 // Clear output buffer
585 // Clear own output buffer
586 $GLOBALS['output'] = '';
588 // Load URL when headers are not sent
589 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $URL), false));
591 // Output error message
592 loadInclude('inc/header.php');
593 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
594 loadInclude('inc/footer.php');
597 // Shut the mailer down here
601 /************************************************************************
603 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
604 * $a_sort sortiert: *
606 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
607 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
608 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
609 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
610 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
612 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
613 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
614 * Sie, dass es doch nicht so schwer ist! :-) *
616 ************************************************************************/
617 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
619 while ($primary_key < count($a_sort)) {
620 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
621 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
623 if ($nums === false) {
624 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
625 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
626 } elseif ($key != $key2) {
627 // Sort numbers (E.g.: 9 < 10)
628 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
629 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
633 // We have found two different values, so let's sort whole array
634 foreach ($dummy as $sort_key => $sort_val) {
635 $t = $dummy[$sort_key][$key];
636 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
637 $dummy[$sort_key][$key2] = $t;
648 // Write back sorted array
654 // Deprecated : $length (still has one reference in this function)
657 function generateRandomCode ($length, $code, $userid, $DATA = '') {
658 // Build server string
659 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
662 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY');
663 if (isConfigEntrySet('secret_key')) {
664 $keys .= getEncryptSeperator().getSecretKey();
666 if (isConfigEntrySet('file_hash')) {
667 $keys .= getEncryptSeperator().getFileHash();
669 $keys .= getEncryptSeperator() . getDateFromPatchTime();
670 if (isConfigEntrySet('master_salt')) {
671 $keys .= getEncryptSeperator().getMasterSalt();
674 // Build string from misc data
675 $data = $code . getEncryptSeperator() . $userid . getEncryptSeperator() . $DATA;
677 // Add more additional data
678 if (isSessionVariableSet('u_hash')) {
679 $data .= getEncryptSeperator() . getSession('u_hash');
682 // Add referal id, language, theme and userid
683 $data .= getEncryptSeperator() . determineReferalId();
684 $data .= getEncryptSeperator() . getLanguage();
685 $data .= getEncryptSeperator() . getCurrentTheme();
686 $data .= getEncryptSeperator() . getMemberId();
688 // Calculate number for generating the code
689 $a = $code + getConfig('_ADD') - 1;
691 if (isConfigEntrySet('master_salt')) {
692 // Generate hash with master salt from modula of number with the prime number and other data
693 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, getMasterSalt());
695 // Create number from hash
696 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
698 // Generate hash with "hash of site key" from modula of number with the prime number and other data
699 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a, substr(sha1(getConfig('SITE_KEY')), 0, getSaltLength()));
701 // Create number from hash
702 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
705 // At least 10 numbers shall be secure enought!
706 $len = getCodeLength();
707 if ($len == '0') $len = $length;
708 if ($len == '0') $len = 10;
710 // Cut off requested counts of number
711 $return = substr(str_replace('.', '', $rcode), 0, $len);
713 // Done building code
717 // Does only allow numbers
718 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
719 // Filter all numbers out
720 $ret = preg_replace('/[^0123456789]/', '', $num);
723 if ($castValue === true) {
724 // Cast to biggest numeric type
725 $ret = (double) $ret;
728 // Has the whole value changed?
729 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true) && (!is_null($num))) {
731 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
738 // Creates a Uni* timestamp from given selection data and prefix
739 function createTimestampFromSelections ($prefix, $postData) {
740 // Initial return value
743 // Do we have a leap year?
745 $TEST = getYear() / 4;
748 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
749 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getOneDay();
751 // First add years...
752 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
755 $ret += $postData[$prefix . '_mo'] * 2628000;
758 $ret += $postData[$prefix . '_we'] * 604800;
761 $ret += $postData[$prefix . '_da'] * 86400;
764 $ret += $postData[$prefix . '_ho'] * 3600;
767 $ret += $postData[$prefix . '_mi'] * 60;
769 // And at last seconds...
770 $ret += $postData[$prefix . '_se'];
772 // Return calculated value
776 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
777 function createFancyTime ($stamp) {
778 // Get data array with years/months/weeks/days/...
779 $data = createTimeSelections($stamp, '', '', '', true);
781 foreach ($data as $k => $v) {
783 // Value is greater than 0 "eval" data to return string
784 $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
789 // Do we have something there?
790 if (strlen($ret) > 0) {
791 // Remove leading commata and space
792 $ret = substr($ret, 2);
795 $ret = '0 {--_SECONDS--}';
798 // Return fancy time string
802 // Extract host from script name
803 function extractHostnameFromUrl (&$script) {
804 // Use default SERVER_URL by default... ;) So?
805 $url = getServerUrl();
807 // Is this URL valid?
808 if (substr($script, 0, 7) == 'http://') {
809 // Use the hostname from script URL as new hostname
810 $url = substr($script, 7);
811 $extract = explode('/', $url);
813 // Done extracting the URL :)
817 $host = str_replace('http://', '', $url);
818 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
820 // Generate relative URL
821 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
822 if (substr(strtolower($script), 0, 7) == 'http://') {
823 // But only if http:// is in front!
824 $script = substr($script, (strlen($url) + 7));
825 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
827 $script = substr($script, (strlen($url) + 8));
830 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
831 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
837 // Send a GET request
838 function sendGetRequest ($script, $data = array()) {
839 // Extract host name from script
840 $host = extractHostnameFromUrl($script);
843 $body = http_build_query($data, '', '&');
845 // There should be data, else we don't need to extend $script with $body
847 // Do we have a question-mark in the script?
848 if (strpos($script, '?') === false) {
849 // No, so first char must be question mark
859 // Remove trailed & to make it more conform
860 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
863 // Generate GET request header
864 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
865 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
866 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
867 if (isConfigEntrySet('FULL_VERSION')) {
868 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
870 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
872 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
873 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
874 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
875 $request .= 'Connection: close' . getConfig('HTTP_EOL');
876 $request .= getConfig('HTTP_EOL');
878 // Send the raw request
879 $response = sendRawRequest($host, $request);
881 // Return the result to the caller function
885 // Send a POST request
886 function sendPostRequest ($script, $postData) {
887 // Is postData an array?
888 if (!is_array($postData)) {
890 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
891 return array('', '', '');
894 // Extract host name from script
895 $host = extractHostnameFromUrl($script);
897 // Construct request body
898 $body = http_build_query($postData, '', '&');
900 // Generate POST request header
901 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
902 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
903 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
904 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
905 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
906 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
907 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
908 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
909 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
910 $request .= 'Connection: close' . getConfig('HTTP_EOL');
911 $request .= getConfig('HTTP_EOL');
916 // Send the raw request
917 $response = sendRawRequest($host, $request);
919 // Return the result to the caller function
923 // Sends a raw request to another host
924 function sendRawRequest ($host, $request) {
925 // Init errno and errdesc with 'all fine' values
926 $errno = '0'; $errdesc = '';
929 $response = array('', '', '');
931 // Default is not to use proxy
934 // Are proxy settins set?
941 loadIncludeOnce('inc/classes/resolver.class.php');
943 // Get resolver instance
944 $resolver = new HostnameResolver();
947 //* DEBUG: */ die('SCRIPT=' . $script);
948 if ($useProxy === true) {
949 // Resolve hostname into IP address
950 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
952 // Connect to host through proxy connection
953 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
955 // Resolve hostname into IP address
956 $ip = $resolver->resolveHostname($host);
958 // Connect to host directly
959 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
963 if (!is_resource($fp)) {
965 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
967 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
968 // Cannot set non-blocking mode or timeout
969 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
974 if ($useProxy === true) {
975 // Setup proxy tunnel
976 $response = setupProxyTunnel($host, $fp);
978 // If the response is invalid, abort
979 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
981 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
987 fwrite($fp, $request);
990 $start = microtime(true);
994 // Get info from stream
995 $info = stream_get_meta_data($fp);
997 // Is it timed out? 15 seconds is a really patient...
998 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1000 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1006 // Get line from stream
1007 $line = fgets($fp, 128);
1009 // Ignore empty lines because of non-blocking mode
1011 // uslepp a little to avoid 100% CPU load
1018 // Add it to response
1019 $response[] = trim($line);
1025 // Time request if debug-mode is enabled
1026 if (isDebugModeEnabled()) {
1027 // Add debug message...
1028 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1031 // Skip first empty lines
1033 foreach ($resp as $idx => $line) {
1035 $line = trim($line);
1037 // Is this line empty?
1040 array_shift($response);
1042 // Abort on first non-empty line
1047 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1048 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1050 // Proxy agent found or something went wrong?
1051 if (!isset($response[0])) {
1052 // No response, maybe timeout
1053 $response = array('', '', '');
1054 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1055 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1056 // Proxy header detected, so remove two lines
1057 array_shift($response);
1058 array_shift($response);
1061 // Was the request successfull?
1062 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1063 // Not found / access forbidden
1064 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1065 $response = array('', '', '');
1072 // Sets up a proxy tunnel for given hostname and through resource
1073 function setupProxyTunnel ($host, $resource) {
1075 $response = array('', '', '');
1077 // Generate CONNECT request header
1078 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1079 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1081 // Use login data to proxy? (username at least!)
1082 if (getConfig('proxy_username') != '') {
1084 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1085 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1088 // Add last new-line
1089 $proxyTunnel .= getConfig('HTTP_EOL');
1090 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1093 fwrite($fp, $proxyTunnel);
1097 // No response received
1101 // Read the first line
1102 $resp = trim(fgets($fp, 10240));
1103 $respArray = explode(' ', $resp);
1104 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1105 // Invalid response!
1113 // Taken from www.php.net isInStringIgnoreCase() user comments
1114 function isEmailValid ($email) {
1115 // Check first part of email address
1116 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1119 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1122 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1124 // Return check result
1125 return preg_match($regex, $email);
1128 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1129 function isUrlValid ($URL, $compile=true) {
1130 // Trim URL a little
1131 $URL = trim(urldecode($URL));
1132 //* DEBUG: */ debugOutput($URL);
1134 // Compile some chars out...
1135 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1136 //* DEBUG: */ debugOutput($URL);
1138 // Check for the extension filter
1139 if (isExtensionActive('filter')) {
1140 // Use the extension's filter set
1141 return FILTER_VALIDATE_URL($URL, false);
1144 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1145 // https:// in front of the URLs
1146 return isUrlValidSimple($URL);
1149 // Generate a hash for extra-security for all passwords
1150 function generateHash ($plainText, $salt = '', $hash = true) {
1152 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
1154 // Is the required extension 'sql_patches' there and a salt is not given?
1155 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
1156 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
1157 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1158 if ($hash === true) {
1159 // Is plain password
1160 return md5($plainText);
1162 // Is already a hash
1167 // Do we miss an arry element here?
1168 if (!isConfigEntrySet('file_hash')) {
1170 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
1173 // When the salt is empty build a new one, else use the first x configured characters as the salt
1175 // Build server string for more entropy
1176 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRemoteAddr();
1179 $keys = getConfig('SITE_KEY') . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
1182 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
1184 // Calculate number for generating the code
1185 $a = time() + getConfig('_ADD') - 1;
1187 // Generate SHA1 sum from modula of number and the prime number
1188 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getConfig('DATE_KEY') . getEncryptSeperator() . $a);
1189 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
1190 $sha1 = scrambleString($sha1);
1191 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
1192 //* DEBUG: */ $sha1b = descrambleString($sha1);
1193 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
1195 // Generate the password salt string
1196 $salt = substr($sha1, 0, getSaltLength());
1197 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
1200 //* DEBUG: */ debugOutput('salt=' . $salt);
1201 $salt = substr($salt, 0, getSaltLength());
1202 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
1204 // Sanity check on salt
1205 if (strlen($salt) != getSaltLength()) {
1207 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
1211 // Generate final hash (for debug output)
1212 $finalHash = $salt . sha1($salt . $plainText);
1215 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
1221 // Scramble a string
1222 function scrambleString ($str) {
1226 // Final check, in case of failture it will return unscrambled string
1227 if (strlen($str) > 40) {
1228 // The string is to long
1230 } elseif (strlen($str) == 40) {
1232 $scrambleNums = explode(':', getPassScramble());
1234 // Generate new numbers
1235 $scrambleNums = explode(':', genScrambleString(strlen($str)));
1238 // Compare both lengths and abort if different
1239 if (strlen($str) != count($scrambleNums)) return $str;
1241 // Scramble string here
1242 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
1243 for ($idx = 0; $idx < strlen($str); $idx++) {
1244 // Get char on scrambled position
1245 $char = substr($str, $scrambleNums[$idx], 1);
1247 // Add it to final output string
1248 $scrambled .= $char;
1251 // Return scrambled string
1252 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
1256 // De-scramble a string scrambled by scrambleString()
1257 function descrambleString ($str) {
1258 // Scramble only 40 chars long strings
1259 if (strlen($str) != 40) return $str;
1261 // Load numbers from config
1262 $scrambleNums = explode(':', getPassScramble());
1265 if (count($scrambleNums) != 40) return $str;
1267 // Begin descrambling
1268 $orig = str_repeat(' ', 40);
1269 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
1270 for ($idx = 0; $idx < 40; $idx++) {
1271 $char = substr($str, $idx, 1);
1272 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1275 // Return scrambled string
1276 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1280 // Generated a "string" for scrambling
1281 function genScrambleString ($len) {
1282 // Prepare array for the numbers
1283 $scrambleNumbers = array();
1285 // First we need to setup randomized numbers from 0 to 31
1286 for ($idx = 0; $idx < $len; $idx++) {
1288 $rand = mt_rand(0, ($len - 1));
1290 // Check for it by creating more numbers
1291 while (array_key_exists($rand, $scrambleNumbers)) {
1292 $rand = mt_rand(0, ($len - 1));
1296 $scrambleNumbers[$rand] = $rand;
1299 // So let's create the string for storing it in database
1300 $scrambleString = implode(':', $scrambleNumbers);
1301 return $scrambleString;
1304 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1305 function encodeHashForCookie ($passHash) {
1306 // Return vanilla password hash
1309 // Is a secret key and master salt already initialized?
1310 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1311 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1312 // Only calculate when the secret key is generated
1313 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1314 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1315 // Both keys must have same length so return unencrypted
1316 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1320 $newHash = ''; $start = 9;
1321 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1322 for ($idx = 0; $idx < 20; $idx++) {
1323 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1324 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1325 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1326 $mod = dechex($idx);
1327 if ($part1 > $part2) {
1328 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1329 } elseif ($part2 > $part1) {
1330 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1332 $mod = substr($mod, 0, 2);
1333 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1334 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1335 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1340 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1341 $ret = generateHash($newHash, getMasterSalt());
1345 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1349 // Fix "deleted" cookies
1350 function fixDeletedCookies ($cookies) {
1351 // Is this an array with entries?
1352 if ((is_array($cookies)) && (count($cookies) > 0)) {
1353 // Then check all cookies if they are marked as deleted!
1354 foreach ($cookies as $cookieName) {
1355 // Is the cookie set to "deleted"?
1356 if (getSession($cookieName) == 'deleted') {
1357 setSession($cookieName, '');
1363 // Checks if a given apache module is loaded
1364 function isApacheModuleLoaded ($apacheModule) {
1365 // Check it and return result
1366 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1369 // Get current theme name
1370 function getCurrentTheme () {
1371 // The default theme is 'default'... ;-)
1374 // Do we have ext-theme installed and active?
1375 if (isExtensionActive('theme')) {
1376 // Call inner method
1377 $ret = getActualTheme();
1380 // Return theme value
1384 // Generates an error code from given account status
1385 function generateErrorCodeFromUserStatus ($status = '') {
1386 // If no status is provided, use the default, cached
1387 if ((empty($status)) && (isMember())) {
1389 $status = getUserData('status');
1392 // Default error code if unknown account status
1393 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1395 // Generate constant name
1396 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1398 // Is the constant there?
1399 if (isCodeSet($codeName)) {
1401 $errorCode = getCode($codeName);
1404 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1407 // Return error code
1411 // Back-ported from the new ship-simu engine. :-)
1412 function debug_get_printable_backtrace () {
1414 $backtrace = '<ol>';
1416 // Get and prepare backtrace for output
1417 $backtraceArray = debug_backtrace();
1418 foreach ($backtraceArray as $key => $trace) {
1419 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1420 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1421 if (!isset($trace['args'])) $trace['args'] = array();
1422 $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>';
1426 $backtrace .= '</ol>';
1428 // Return the backtrace
1432 // A mail-able backtrace
1433 function debug_get_mailable_backtrace () {
1437 // Get and prepare backtrace for output
1438 $backtraceArray = debug_backtrace();
1439 foreach ($backtraceArray as $key => $trace) {
1440 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1441 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1442 if (!isset($trace['args'])) $trace['args'] = array();
1443 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1446 // Return the backtrace
1450 // Generates a ***weak*** seed
1451 function generateSeed () {
1452 return microtime(true) * 100000;
1455 // Converts a message code to a human-readable message
1456 function getMessageFromErrorCode ($code) {
1460 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1461 case getCode('LOGOUT_FAILED') : $message = '<span class="notice">{--LOGOUT_FAILED--}</span>'; break;
1462 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1463 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1464 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1465 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1466 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1467 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1468 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1469 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1470 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1471 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1472 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1473 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1474 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1475 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1476 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1477 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1478 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1479 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1480 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1481 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1482 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1483 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1484 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1485 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1486 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1487 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1488 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1489 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1491 case getCode('ERROR_MAILID'):
1492 if (isExtensionActive('mailid', true)) {
1493 $message = '{--ERROR_CONFIRMING_MAIL--}';
1495 $message = generateExtensionInactiveNotInstalledMessage('mailid');
1499 case getCode('EXTENSION_PROBLEM'):
1500 if (isGetRequestParameterSet('ext')) {
1501 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1503 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1507 case getCode('URL_TIME_LOCK'):
1508 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1509 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1510 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1512 // Load timestamp from last order
1513 $content = SQL_FETCHARRAY($result);
1516 SQL_FREERESULT($result);
1518 // Translate it for templates
1519 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1521 // Calculate hours...
1522 $content['hours'] = round(getConfig('url_tlock') / 60 / 60);
1525 $content['minutes'] = round((getConfig('url_tlock') - $content['hours'] * 60 * 60) / 60);
1528 $content['seconds'] = round(getConfig('url_tlock') - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1530 // Finally contruct the message
1531 $message = loadTemplate('tlock_message', true, $content);
1535 // Missing/invalid code
1536 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1539 logDebugMessage(__FUNCTION__, __LINE__, $message);
1543 // Return the message
1547 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1548 function isUrlValidSimple ($url) {
1550 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1552 // Allows http and https
1553 $http = "(http|https)+(:\/\/)";
1555 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1556 // Test double-domains (e.g. .de.vu)
1557 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1559 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1561 $dir = "((/)+([-_\.[:alnum:]])+)*";
1563 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1564 // ... and the string after and including question character
1565 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1566 // Pattern for URLs like http://url/dir/doc.html?var=value
1567 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1568 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1569 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1570 // Pattern for URLs like http://url/dir/?var=value
1571 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1572 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1573 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1574 // Pattern for URLs like http://url/dir/page.ext
1575 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1576 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1577 $pattern['ipdp'] = $http . $ip . $dir . $page;
1578 // Pattern for URLs like http://url/dir
1579 $pattern['d1d'] = $http . $domain1 . $dir;
1580 $pattern['d2d'] = $http . $domain2 . $dir;
1581 $pattern['ipd'] = $http . $ip . $dir;
1582 // Pattern for URLs like http://url/?var=value
1583 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1584 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1585 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1586 // Pattern for URLs like http://url?var=value
1587 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1588 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1589 $pattern['ipg12'] = $http . $ip . $getstring1;
1591 // Test all patterns
1593 foreach ($pattern as $key => $pat) {
1595 if (isDebugRegularExpressionEnabled()) {
1596 // @TODO Are these convertions still required?
1597 $pat = str_replace('.', '\.', $pat);
1598 $pat = str_replace('@', '\@', $pat);
1599 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1602 // Check if expression matches
1603 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1606 if ($reg === true) break;
1609 // Return true/false
1613 // Wtites data to a config.php-style file
1614 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1615 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1616 // Initialize some variables
1622 // Is the file there and read-/write-able?
1623 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1624 $search = 'CFG: ' . $comment;
1625 $tmp = $FQFN . '.tmp';
1627 // Open the source file
1628 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1630 // Is the resource valid?
1631 if (is_resource($fp)) {
1632 // Open temporary file
1633 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1635 // Is the resource again valid?
1636 if (is_resource($fp_tmp)) {
1637 // Mark temporary file as readable
1638 $GLOBALS['file_readable'][$tmp] = true;
1641 while (!feof($fp)) {
1642 // Read from source file
1643 $line = fgets ($fp, 1024);
1645 if (strpos($line, $search) > -1) {
1651 if ($next === $seek) {
1653 $line = $prefix . $DATA . $suffix . "\n";
1659 // Write to temp file
1660 fwrite($fp_tmp, $line);
1666 // Finished writing tmp file
1670 // Close source file
1673 if (($done === true) && ($found === true)) {
1674 // Copy back tmp file and delete tmp :-)
1675 copyFileVerified($tmp, $FQFN, 0644);
1676 return removeFile($tmp);
1677 } elseif ($found === false) {
1678 outputHtml('<strong>CHANGE:</strong> 404!');
1680 outputHtml('<strong>TMP:</strong> UNDONE!');
1684 // File not found, not readable or writeable
1685 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1688 // An error was detected!
1692 // Send notification to admin
1693 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = '0') {
1694 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1696 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName);
1697 sendAdminsEmails($subject, $templateName, $content, $userid);
1699 // Send out-dated way
1700 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName);
1701 $message = loadEmailTemplate($templateName, $content, $userid);
1702 sendAdminEmails($subject, $message);
1706 // Debug message logger
1707 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1708 // Is debug mode enabled?
1709 if ((isDebugModeEnabled()) || ($force === true)) {
1711 $message = str_replace("\r", '', str_replace("\n", '', $message));
1713 // Log this message away
1714 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1718 // Handle extra values
1719 function handleExtraValues ($filterFunction, $value, $extraValue) {
1720 // Default is the value itself
1723 // Do we have a special filter function?
1724 if (!empty($filterFunction)) {
1725 // Does the filter function exist?
1726 if (function_exists($filterFunction)) {
1727 // Do we have extra parameters here?
1728 if (!empty($extraValue)) {
1729 // Put both parameters in one new array by default
1730 $args = array($value, $extraValue);
1732 // If we have an array simply use it and pre-extend it with our value
1733 if (is_array($extraValue)) {
1734 // Make the new args array
1735 $args = merge_array(array($value), $extraValue);
1738 // Call the multi-parameter call-back
1739 $ret = call_user_func_array($filterFunction, $args);
1741 // One parameter call
1742 $ret = call_user_func($filterFunction, $value);
1751 // Converts timestamp selections into a timestamp
1752 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1753 // Init test variable
1757 // Get last three chars
1758 $test = substr($id, -3);
1760 // Improved way of checking! :-)
1761 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1762 // Found a multi-selection for timings?
1763 $test = substr($id, 0, -3);
1764 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)) {
1765 // Generate timestamp
1766 $postData[$test] = createTimestampFromSelections($test, $postData);
1767 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1768 $GLOBALS['skip_config'][$test] = true;
1770 // Remove data from array
1771 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1772 unset($postData[$test . '_' . $rem]);
1783 // Reverts the german decimal comma into Computer decimal dot
1784 function convertCommaToDot ($str) {
1785 // Default float is not a float... ;-)
1788 // Which language is selected?
1789 switch (getLanguage()) {
1790 case 'de': // German language
1791 // Remove german thousand dots first
1792 $str = str_replace('.', '', $str);
1794 // Replace german commata with decimal dot and cast it
1795 $float = (float)str_replace(',', '.', $str);
1798 default: // US and so on
1799 // Remove thousand dots first and cast
1800 $float = (float)str_replace(',', '', $str);
1808 // Handle menu-depending failed logins and return the rendered content
1809 function handleLoginFailures ($accessLevel) {
1810 // Default output is empty ;-)
1813 // Is the session data set?
1814 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1815 // Ignore zero values
1816 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1817 // Non-guest has login failures found, get both data and prepare it for template
1818 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1820 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1821 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1825 $OUT = loadTemplate('login_failures', true, $content);
1828 // Reset session data
1829 setSession('mailer_' . $accessLevel . '_failures', '');
1830 setSession('mailer_' . $accessLevel . '_last_failure', '');
1833 // Return rendered content
1838 function rebuildCache ($cache, $inc = '', $force = false) {
1840 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1842 // Shall I remove the cache file?
1843 if (isCacheInstanceValid()) {
1845 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1847 $GLOBALS['cache_instance']->removeCacheFile($force);
1850 // Include file given?
1853 $inc = sprintf("inc/loader/load-%s.php", $inc);
1855 // Is the include there?
1856 if (isIncludeReadable($inc)) {
1857 // And rebuild it from scratch
1858 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1861 // Include not found!
1862 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1868 // Determines the real remote address
1869 function determineRealRemoteAddress () {
1870 // Is a proxy in use?
1871 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1873 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1874 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
1875 // Yet, another proxy
1876 $address = $_SERVER['HTTP_CLIENT_IP'];
1878 // The regular address when no proxy was used
1879 $address = $_SERVER['REMOTE_ADDR'];
1882 // This strips out the real address from proxy output
1883 if (strstr($address, ',')) {
1884 $addressArray = explode(',', $address);
1885 $address = $addressArray[0];
1888 // Return the result
1892 // Adds a bonus mail to the queue
1893 // This is a high-level function!
1894 function addNewBonusMail ($data, $mode = '', $output=true) {
1895 // Use mode from data if not set and availble ;-)
1896 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
1898 // Generate receiver list
1899 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1902 if (!empty($receiver)) {
1903 // Add bonus mail to queue
1904 addBonusMailToQueue(
1916 // Mail inserted into bonus pool
1917 if ($output === true) {
1918 loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
1920 } elseif ($output === true) {
1921 // More entered than can be reached!
1922 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
1925 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1929 // Determines referal id and sets it
1930 function determineReferalId () {
1931 // Skip this in non-html-mode and outside ref.php
1932 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
1934 // Check if refid is set
1935 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1937 } elseif (isPostRequestParameterSet('refid')) {
1938 // Get referal id from POST element refid
1939 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1940 } elseif (isGetRequestParameterSet('refid')) {
1941 // Get referal id from GET parameter refid
1942 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1943 } elseif (isGetRequestParameterSet('ref')) {
1944 // Set refid=ref (the referal link uses such variable)
1945 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1946 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1947 // The variable user comes from click.php
1948 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1949 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1950 // Set session refid als global
1951 $GLOBALS['refid'] = bigintval(getSession('refid'));
1952 } elseif (isRandomReferalIdEnabled()) {
1953 // Select a random user which has confirmed enougth mails
1954 $GLOBALS['refid'] = determineRandomReferalId();
1955 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
1956 // Set default refid as refid in URL
1957 $GLOBALS['refid'] = getDefRefid();
1959 // No default id when sql_patches is not installed or none set
1960 $GLOBALS['refid'] = null;
1963 // Set cookie when default refid > 0
1964 if (!isSessionVariableSet('refid') || (isValidUserId($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
1965 // Default is not found
1968 // Do we have nickname or userid set?
1969 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1970 // Nickname in URL, so load the id
1971 $found = fetchUserData($GLOBALS['refid'], 'nickname');
1972 } elseif (isValidUserId($GLOBALS['refid'])) {
1973 // Direct userid entered
1974 $found = fetchUserData($GLOBALS['refid']);
1977 // Is the record valid?
1978 if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
1979 // No, then reset referal id
1980 $GLOBALS['refid'] = getDefRefid();
1984 setSession('refid', $GLOBALS['refid']);
1987 // Return determined refid
1988 return $GLOBALS['refid'];
1991 // Enables the reset mode and runs it
1992 function doReset () {
1993 // Enable the reset mode
1994 $GLOBALS['reset_enabled'] = true;
1997 runFilterChain('reset');
2000 // Our shutdown-function
2001 function shutdown () {
2002 // Call the filter chain 'shutdown'
2003 runFilterChain('shutdown', null);
2005 // Check if not in installation phase and the link is up
2006 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
2008 SQL_CLOSE(__FUNCTION__, __LINE__);
2009 } elseif (!isInstallationPhase()) {
2011 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
2014 // Stop executing here
2019 function initMemberId () {
2020 $GLOBALS['member_id'] = '0';
2023 // Setter for member id
2024 function setMemberId ($memberid) {
2025 // We should not set member id to zero
2026 if ($memberid == '0') {
2027 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
2031 $GLOBALS['member_id'] = bigintval($memberid);
2034 // Getter for member id or returns zero
2035 function getMemberId () {
2036 // Default member id
2039 // Is the member id set?
2040 if (isMemberIdSet()) {
2042 $memberid = $GLOBALS['member_id'];
2049 // Checks ether the member id is set
2050 function isMemberIdSet () {
2051 return (isset($GLOBALS['member_id']));
2054 // Setter for extra title
2055 function setExtraTitle ($extraTitle) {
2056 $GLOBALS['extra_title'] = $extraTitle;
2059 // Getter for extra title
2060 function getExtraTitle () {
2061 // Is the extra title set?
2062 if (!isExtraTitleSet()) {
2063 // No, then abort here
2064 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
2068 return $GLOBALS['extra_title'];
2071 // Checks if the extra title is set
2072 function isExtraTitleSet () {
2073 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
2076 // Reads a directory recursively by default and searches for files not matching
2077 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
2078 // a whole directory.
2079 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
2080 // Add default entries we should exclude
2081 $excludeArray[] = '.';
2082 $excludeArray[] = '..';
2083 $excludeArray[] = '.svn';
2084 $excludeArray[] = '.htaccess';
2086 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
2091 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
2094 while ($baseFile = readdir($dirPointer)) {
2095 // Exclude '.', '..' and entries in $excludeArray automatically
2096 if (in_array($baseFile, $excludeArray, true)) {
2098 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
2102 // Construct include filename and FQFN
2103 $fileName = $baseDir . $baseFile;
2104 $FQFN = getPath() . $fileName;
2106 // Remove double slashes
2107 $FQFN = str_replace('//', '/', $FQFN);
2109 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
2110 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
2111 // These Lines are only for debugging!!
2112 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
2113 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
2114 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
2120 // Skip also files with non-matching prefix genericly
2121 if (($recursive === true) && (isDirectory($FQFN))) {
2122 // Is a redirectory so read it as well
2123 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
2125 // And skip further processing
2127 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
2129 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
2131 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
2132 // Skip wrong suffix as well
2133 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
2135 } elseif (!isFileReadable($FQFN)) {
2136 // Not readable so skip it
2137 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
2141 // Is the file a PHP script or other?
2142 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
2143 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
2144 // Is this a valid include file?
2145 if ($extension == '.php') {
2146 // Remove both for extension name
2147 $extName = substr($baseFile, strlen($prefix), -4);
2149 // Add file with or without base path
2150 if ($addBaseDir === true) {
2152 $files[] = $fileName;
2155 $files[] = $baseFile;
2158 // We found .php file but should not search for them, why?
2159 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
2161 } elseif (substr($baseFile, -4, 4) == $extension) {
2162 // Other, generic file found
2163 $files[] = $fileName;
2168 closedir($dirPointer);
2173 // Return array with include files
2174 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
2178 // Maps a module name into a database table name
2179 function mapModuleToTable ($moduleName) {
2180 // Map only these, still lame code...
2181 switch ($moduleName) {
2182 // 'index' is the guest's menu
2183 case 'index': $moduleName = 'guest'; break;
2184 // ... and 'login' the member's menu
2185 case 'login': $moduleName = 'member'; break;
2186 // Anything else will not be mapped, silently.
2193 // Add SQL debug data to array for later output
2194 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
2195 // Do we have cache?
2196 if (!isset($GLOBALS['debug_sql_available'])) {
2197 // Check it and cache it in $GLOBALS
2198 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
2201 // Don't execute anything here if we don't need or ext-other is missing
2202 if ($GLOBALS['debug_sql_available'] === false) {
2206 // Already executed?
2207 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
2208 // Then abort here, we don't need to profile a query twice
2212 // Remeber this as profiled (or not, but we don't care here)
2213 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
2217 'num_rows' => SQL_NUMROWS($result),
2218 'affected' => SQL_AFFECTEDROWS(),
2219 'sql_str' => $sqlString,
2220 'timing' => $timing,
2221 'file' => basename($F),
2226 $GLOBALS['debug_sqls'][] = $record;
2229 // Initializes the cache instance
2230 function initCacheInstance () {
2231 // Check for double-initialization
2232 if (isset($GLOBALS['cache_instance'])) {
2233 // This should not happen and must be fixed
2234 debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
2237 // Load include for CacheSystem class
2238 loadIncludeOnce('inc/classes/cachesystem.class.php');
2240 // Initialize cache system only when it's needed
2241 $GLOBALS['cache_instance'] = new CacheSystem();
2244 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
2245 // Failed to initialize cache sustem
2246 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2250 // Getter for message from array or raw message
2251 function getMessageFromIndexedArray ($message, $pos, $array) {
2252 // Check if the requested message was found in array
2253 if (isset($array[$pos])) {
2254 // ... if yes then use it!
2255 $ret = $array[$pos];
2257 // ... else use default message
2265 // Convert ';' to ', ' for e.g. receiver list
2266 function convertReceivers ($old) {
2267 return str_replace(';', ', ', $old);
2270 // Get a module from filename and access level
2271 function getModuleFromFileName ($file, $accessLevel) {
2272 // Default is 'invalid';
2273 $modCheck = 'invalid';
2275 // @TODO This is still very static, rewrite it somehow
2276 switch ($accessLevel) {
2278 $modCheck = 'admin';
2284 $modCheck = getModule();
2287 default: // Unsupported file name / access level
2288 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2296 // Encodes an URL for adding session id, etc.
2297 function encodeUrl ($url, $outputMode = '0') {
2298 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2299 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) return $url;
2301 // Do we have a valid session?
2302 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2304 // Determine right seperator
2305 $seperator = '&';
2306 if (strpos($url, '?') === false) {
2309 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2315 if (session_id() != '') {
2316 $url .= $seperator . session_name() . '=' . session_id();
2321 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2323 $url = '{?URL?}/' . $url;
2330 // Simple check for spider
2331 function isSpider () {
2332 // Get the UA and trim it down
2333 $userAgent = trim(strtolower(detectUserAgent(true)));
2335 // It should not be empty, if so it is better a spider/bot
2336 if (empty($userAgent)) {
2337 // It is a spider/bot
2342 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2345 // Function to search for the last modified file
2346 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2348 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2349 // Does it match what we are looking for? (We skip a lot files already!)
2350 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2351 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2353 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2354 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2356 // Walk through all entries
2357 foreach ($ds as $d) {
2358 // Generate proper FQFN
2359 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2361 // Is it a file and readable?
2362 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2363 if (isFileReadable($FQFN)) {
2364 // $FQFN is a readable file so extract the requested data from it
2365 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2366 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2368 // Is the file more recent?
2369 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2370 // This file is newer as the file before
2371 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2372 $last_changed['path_name'] = $FQFN;
2373 $last_changed[$lookFor] = $check;
2377 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2382 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2383 function handleFieldWithBraces ($field) {
2384 // Are there braces [] at the end?
2385 if (substr($field, -2, 2) == '[]') {
2386 // Try to find one and replace it. I do it this way to allow easy
2387 // extending of this code.
2388 foreach (array('admin_list_builder_id_value') as $key) {
2389 // Is the cache entry set?
2390 if (isset($GLOBALS[$key])) {
2392 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2404 // Converts a userid so it can be used in SQL queries
2405 function makeDatabaseUserId ($userid) {
2406 // Is it a valid username?
2407 if (isValidUserId($userid)) {
2409 $userid = bigintval($userid);
2411 // Is not valid or zero
2419 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2420 // Note: This function is cached
2421 function capitalizeUnderscoreString ($str) {
2422 // Do we have cache?
2423 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2424 // Init target string
2427 // Explode it with the underscore, but rewrite dashes to underscore before
2428 $strArray = explode('_', str_replace('-', '_', $str));
2430 // "Walk" through all elements and make them lower-case but first upper-case
2431 foreach ($strArray as $part) {
2432 // Capitalize the string part
2433 $capitalized .= firstCharUpperCase($part);
2436 // Store the converted string in cache array
2437 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2441 return $GLOBALS[__FUNCTION__][$str];
2444 // Generate admin links for mail order
2445 // mailType can be: 'mid' or 'bid'
2446 function generateAdminMailLinks ($mailType, $mailId) {
2451 // Default column for mail status is 'data_type'
2452 // @TODO Rename column data_type to e.g. mail_status
2453 $statusColumn = 'data_type';
2455 // Which mail do we have?
2456 switch ($mailType) {
2457 case 'bid': // Bonus mail
2461 case 'mid': // Member mail
2465 default: // Handle unsupported types
2466 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2467 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2471 // Is the mail type supported?
2472 if (!empty($table)) {
2473 // Query for the mail
2474 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2475 array($statusColumn, $table, bigintval($mailId)), __FILE__, __LINE__);
2477 // Do we have one entry there?
2478 if (SQL_NUMROWS($result) == 1) {
2480 $content = SQL_FETCHARRAY($result);
2481 die('<pre>'.print_r($content, true).'</pre>');
2485 SQL_FREERESULT($result);
2488 // Return generated HTML code
2492 //-----------------------------------------------------------------------------
2493 // Automatically re-created functions, all taken from user comments on www.php.net
2494 //-----------------------------------------------------------------------------
2496 if (!function_exists('html_entity_decode')) {
2497 // Taken from documentation on www.php.net
2498 function html_entity_decode ($string) {
2499 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2500 $trans_tbl = array_flip($trans_tbl);
2501 return strtr($string, $trans_tbl);
2505 if (!function_exists('http_build_query')) {
2506 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
2507 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
2509 foreach ((array) $data as $k => $v) {
2510 if (is_int($k) && $prefix != null) {
2511 $k = urlencode($prefix . $k);
2514 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
2516 if (is_array($v) || is_object($v)) {
2517 array_push($ret, http_build_query($v, '', $sep, $k));
2519 array_push($ret, $k.'='.urlencode($v));
2523 if (empty($sep)) $sep = ini_get('arg_separator.output');
2525 return implode($sep, $ret);