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 = getWebmaster();
124 } elseif ($toEmail == '0') {
126 $toEmail = getWebmaster();
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') {
172 // Problem detected while sending a mail, forward it to admin
173 return sendRawEmail(getWebmaster(), '[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 = getWebmaster();
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(getWebmaster(), getMainTitle());
239 $mail->AddCustomHeader('Errors-To:' . getWebmaster());
240 $mail->AddCustomHeader('X-Loop:' . getWebmaster());
241 $mail->AddCustomHeader('Bounces-To:' . getWebmaster());
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() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
662 $keys = getSiteKey() . getEncryptSeperator() . getDateKey();
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() . getDateKey() . getEncryptSeperator() . $a, getMasterSalt());
695 // Create number from hash
696 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getRandNo() - $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() . getDateKey() . getEncryptSeperator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
701 // Create number from hash
702 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
705 // At least 10 numbers shall be secure enought!
706 $len = getCodeLength();
714 // Cut off requested counts of number
715 $return = substr(str_replace('.', '', $rcode), 0, $len);
717 // Done building code
721 // Does only allow numbers
722 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
723 // Filter all numbers out
724 $ret = preg_replace('/[^0123456789]/', '', $num);
727 if ($castValue === true) {
728 // Cast to biggest numeric type
729 $ret = (double) $ret;
732 // Has the whole value changed?
733 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true) && (!is_null($num))) {
735 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
742 // Creates a Uni* timestamp from given selection data and prefix
743 function createTimestampFromSelections ($prefix, $postData) {
744 // Initial return value
747 // Do we have a leap year?
749 $TEST = getYear() / 4;
752 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
753 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getOneDay();
755 // First add years...
756 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
759 $ret += $postData[$prefix . '_mo'] * 2628000;
762 $ret += $postData[$prefix . '_we'] * 604800;
765 $ret += $postData[$prefix . '_da'] * 86400;
768 $ret += $postData[$prefix . '_ho'] * 3600;
771 $ret += $postData[$prefix . '_mi'] * 60;
773 // And at last seconds...
774 $ret += $postData[$prefix . '_se'];
776 // Return calculated value
780 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
781 function createFancyTime ($stamp) {
782 // Get data array with years/months/weeks/days/...
783 $data = createTimeSelections($stamp, '', '', '', true);
785 foreach ($data as $k => $v) {
787 // Value is greater than 0 "eval" data to return string
788 $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
793 // Do we have something there?
794 if (strlen($ret) > 0) {
795 // Remove leading commata and space
796 $ret = substr($ret, 2);
799 $ret = '0 {--_SECONDS--}';
802 // Return fancy time string
806 // Extract host from script name
807 function extractHostnameFromUrl (&$script) {
808 // Use default SERVER_URL by default... ;) So?
809 $url = getServerUrl();
811 // Is this URL valid?
812 if (substr($script, 0, 7) == 'http://') {
813 // Use the hostname from script URL as new hostname
814 $url = substr($script, 7);
815 $extract = explode('/', $url);
817 // Done extracting the URL :)
821 $host = str_replace('http://', '', $url);
822 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
824 // Generate relative URL
825 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
826 if (substr(strtolower($script), 0, 7) == 'http://') {
827 // But only if http:// is in front!
828 $script = substr($script, (strlen($url) + 7));
829 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
831 $script = substr($script, (strlen($url) + 8));
834 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
835 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
841 // Send a GET request
842 function sendGetRequest ($script, $data = array()) {
843 // Extract host name from script
844 $host = extractHostnameFromUrl($script);
847 $body = http_build_query($data, '', '&');
849 // There should be data, else we don't need to extend $script with $body
851 // Do we have a question-mark in the script?
852 if (strpos($script, '?') === false) {
853 // No, so first char must be question mark
863 // Remove trailed & to make it more conform
864 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
867 // Generate GET request header
868 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
869 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
870 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
871 if (isConfigEntrySet('FULL_VERSION')) {
872 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
874 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
876 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
877 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
878 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
879 $request .= 'Connection: close' . getConfig('HTTP_EOL');
880 $request .= getConfig('HTTP_EOL');
882 // Send the raw request
883 $response = sendRawRequest($host, $request);
885 // Return the result to the caller function
889 // Send a POST request
890 function sendPostRequest ($script, $postData) {
891 // Is postData an array?
892 if (!is_array($postData)) {
894 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
895 return array('', '', '');
898 // Extract host name from script
899 $host = extractHostnameFromUrl($script);
901 // Construct request body
902 $body = http_build_query($postData, '', '&');
904 // Generate POST request header
905 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
906 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
907 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
908 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
909 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
910 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
911 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
912 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
913 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
914 $request .= 'Connection: close' . getConfig('HTTP_EOL');
915 $request .= getConfig('HTTP_EOL');
920 // Send the raw request
921 $response = sendRawRequest($host, $request);
923 // Return the result to the caller function
927 // Sends a raw request to another host
928 function sendRawRequest ($host, $request) {
929 // Init errno and errdesc with 'all fine' values
930 $errno = '0'; $errdesc = '';
933 $response = array('', '', '');
935 // Default is not to use proxy
938 // Are proxy settins set?
945 loadIncludeOnce('inc/classes/resolver.class.php');
947 // Get resolver instance
948 $resolver = new HostnameResolver();
951 //* DEBUG: */ die('SCRIPT=' . $script);
952 if ($useProxy === true) {
953 // Resolve hostname into IP address
954 $ip = $resolver->resolveHostname(compileRawCode(getProxyHost()));
956 // Connect to host through proxy connection
957 $fp = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
959 // Resolve hostname into IP address
960 $ip = $resolver->resolveHostname($host);
962 // Connect to host directly
963 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
967 if (!is_resource($fp)) {
969 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
971 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
972 // Cannot set non-blocking mode or timeout
973 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
978 if ($useProxy === true) {
979 // Setup proxy tunnel
980 $response = setupProxyTunnel($host, $fp);
982 // If the response is invalid, abort
983 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
985 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
991 fwrite($fp, $request);
994 $start = microtime(true);
998 // Get info from stream
999 $info = stream_get_meta_data($fp);
1001 // Is it timed out? 15 seconds is a really patient...
1002 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1004 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1010 // Get line from stream
1011 $line = fgets($fp, 128);
1013 // Ignore empty lines because of non-blocking mode
1015 // uslepp a little to avoid 100% CPU load
1022 // Add it to response
1023 $response[] = trim($line);
1029 // Time request if debug-mode is enabled
1030 if (isDebugModeEnabled()) {
1031 // Add debug message...
1032 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1035 // Skip first empty lines
1037 foreach ($resp as $idx => $line) {
1039 $line = trim($line);
1041 // Is this line empty?
1044 array_shift($response);
1046 // Abort on first non-empty line
1051 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1052 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1054 // Proxy agent found or something went wrong?
1055 if (!isset($response[0])) {
1056 // No response, maybe timeout
1057 $response = array('', '', '');
1058 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1059 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1060 // Proxy header detected, so remove two lines
1061 array_shift($response);
1062 array_shift($response);
1065 // Was the request successfull?
1066 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1067 // Not found / access forbidden
1068 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1069 $response = array('', '', '');
1076 // Sets up a proxy tunnel for given hostname and through resource
1077 function setupProxyTunnel ($host, $resource) {
1079 $response = array('', '', '');
1081 // Generate CONNECT request header
1082 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1083 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1085 // Use login data to proxy? (username at least!)
1086 if (getProxyUsername() != '') {
1088 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
1089 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1092 // Add last new-line
1093 $proxyTunnel .= getConfig('HTTP_EOL');
1094 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1097 fwrite($fp, $proxyTunnel);
1101 // No response received
1105 // Read the first line
1106 $resp = trim(fgets($fp, 10240));
1107 $respArray = explode(' ', $resp);
1108 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1109 // Invalid response!
1117 // Taken from www.php.net isInStringIgnoreCase() user comments
1118 function isEmailValid ($email) {
1119 // Check first part of email address
1120 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1123 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1126 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1128 // Return check result
1129 return preg_match($regex, $email);
1132 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1133 function isUrlValid ($URL, $compile=true) {
1134 // Trim URL a little
1135 $URL = trim(urldecode($URL));
1136 //* DEBUG: */ debugOutput($URL);
1138 // Compile some chars out...
1139 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1140 //* DEBUG: */ debugOutput($URL);
1142 // Check for the extension filter
1143 if (isExtensionActive('filter')) {
1144 // Use the extension's filter set
1145 return FILTER_VALIDATE_URL($URL, false);
1148 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1149 // https:// in front of the URLs
1150 return isUrlValidSimple($URL);
1153 // Generate a hash for extra-security for all passwords
1154 function generateHash ($plainText, $salt = '', $hash = true) {
1156 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
1158 // Is the required extension 'sql_patches' there and a salt is not given?
1159 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
1160 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
1161 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1162 if ($hash === true) {
1163 // Is plain password
1164 return md5($plainText);
1166 // Is already a hash
1171 // Do we miss an arry element here?
1172 if (!isConfigEntrySet('file_hash')) {
1174 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
1177 // When the salt is empty build a new one, else use the first x configured characters as the salt
1179 // Build server string for more entropy
1180 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
1183 $keys = getSiteKey() . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
1186 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
1188 // Calculate number for generating the code
1189 $a = time() + getConfig('_ADD') - 1;
1191 // Generate SHA1 sum from modula of number and the prime number
1192 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a);
1193 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
1194 $sha1 = scrambleString($sha1);
1195 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
1196 //* DEBUG: */ $sha1b = descrambleString($sha1);
1197 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
1199 // Generate the password salt string
1200 $salt = substr($sha1, 0, getSaltLength());
1201 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
1204 //* DEBUG: */ debugOutput('salt=' . $salt);
1205 $salt = substr($salt, 0, getSaltLength());
1206 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
1208 // Sanity check on salt
1209 if (strlen($salt) != getSaltLength()) {
1211 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
1215 // Generate final hash (for debug output)
1216 $finalHash = $salt . sha1($salt . $plainText);
1219 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
1225 // Scramble a string
1226 function scrambleString ($str) {
1230 // Final check, in case of failture it will return unscrambled string
1231 if (strlen($str) > 40) {
1232 // The string is to long
1234 } elseif (strlen($str) == 40) {
1236 $scrambleNums = explode(':', getPassScramble());
1238 // Generate new numbers
1239 $scrambleNums = explode(':', genScrambleString(strlen($str)));
1242 // Compare both lengths and abort if different
1243 if (strlen($str) != count($scrambleNums)) return $str;
1245 // Scramble string here
1246 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
1247 for ($idx = 0; $idx < strlen($str); $idx++) {
1248 // Get char on scrambled position
1249 $char = substr($str, $scrambleNums[$idx], 1);
1251 // Add it to final output string
1252 $scrambled .= $char;
1255 // Return scrambled string
1256 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
1260 // De-scramble a string scrambled by scrambleString()
1261 function descrambleString ($str) {
1262 // Scramble only 40 chars long strings
1263 if (strlen($str) != 40) return $str;
1265 // Load numbers from config
1266 $scrambleNums = explode(':', getPassScramble());
1269 if (count($scrambleNums) != 40) return $str;
1271 // Begin descrambling
1272 $orig = str_repeat(' ', 40);
1273 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
1274 for ($idx = 0; $idx < 40; $idx++) {
1275 $char = substr($str, $idx, 1);
1276 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1279 // Return scrambled string
1280 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1284 // Generated a "string" for scrambling
1285 function genScrambleString ($len) {
1286 // Prepare array for the numbers
1287 $scrambleNumbers = array();
1289 // First we need to setup randomized numbers from 0 to 31
1290 for ($idx = 0; $idx < $len; $idx++) {
1292 $rand = mt_rand(0, ($len - 1));
1294 // Check for it by creating more numbers
1295 while (array_key_exists($rand, $scrambleNumbers)) {
1296 $rand = mt_rand(0, ($len - 1));
1300 $scrambleNumbers[$rand] = $rand;
1303 // So let's create the string for storing it in database
1304 $scrambleString = implode(':', $scrambleNumbers);
1305 return $scrambleString;
1308 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1309 function encodeHashForCookie ($passHash) {
1310 // Return vanilla password hash
1313 // Is a secret key and master salt already initialized?
1314 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1315 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1316 // Only calculate when the secret key is generated
1317 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1318 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1319 // Both keys must have same length so return unencrypted
1320 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1324 $newHash = ''; $start = 9;
1325 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1326 for ($idx = 0; $idx < 20; $idx++) {
1327 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1328 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1329 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1330 $mod = dechex($idx);
1331 if ($part1 > $part2) {
1332 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1333 } elseif ($part2 > $part1) {
1334 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1336 $mod = substr($mod, 0, 2);
1337 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1338 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1339 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1344 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1345 $ret = generateHash($newHash, getMasterSalt());
1349 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1353 // Fix "deleted" cookies
1354 function fixDeletedCookies ($cookies) {
1355 // Is this an array with entries?
1356 if ((is_array($cookies)) && (count($cookies) > 0)) {
1357 // Then check all cookies if they are marked as deleted!
1358 foreach ($cookies as $cookieName) {
1359 // Is the cookie set to "deleted"?
1360 if (getSession($cookieName) == 'deleted') {
1361 setSession($cookieName, '');
1367 // Checks if a given apache module is loaded
1368 function isApacheModuleLoaded ($apacheModule) {
1369 // Check it and return result
1370 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1373 // Get current theme name
1374 function getCurrentTheme () {
1375 // The default theme is 'default'... ;-)
1378 // Do we have ext-theme installed and active?
1379 if (isExtensionActive('theme')) {
1380 // Call inner method
1381 $ret = getActualTheme();
1384 // Return theme value
1388 // Generates an error code from given account status
1389 function generateErrorCodeFromUserStatus ($status = '') {
1390 // If no status is provided, use the default, cached
1391 if ((empty($status)) && (isMember())) {
1393 $status = getUserData('status');
1396 // Default error code if unknown account status
1397 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1399 // Generate constant name
1400 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1402 // Is the constant there?
1403 if (isCodeSet($codeName)) {
1405 $errorCode = getCode($codeName);
1408 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1411 // Return error code
1415 // Back-ported from the new ship-simu engine. :-)
1416 function debug_get_printable_backtrace () {
1418 $backtrace = '<ol>';
1420 // Get and prepare backtrace for output
1421 $backtraceArray = debug_backtrace();
1422 foreach ($backtraceArray as $key => $trace) {
1423 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1424 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1425 if (!isset($trace['args'])) $trace['args'] = array();
1426 $backtrace .= '<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>';
1430 $backtrace .= '</ol>';
1432 // Return the backtrace
1436 // A mail-able backtrace
1437 function debug_get_mailable_backtrace () {
1441 // Get and prepare backtrace for output
1442 $backtraceArray = debug_backtrace();
1443 foreach ($backtraceArray as $key => $trace) {
1444 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1445 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1446 if (!isset($trace['args'])) $trace['args'] = array();
1447 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1450 // Return the backtrace
1454 // Generates a ***weak*** seed
1455 function generateSeed () {
1456 return microtime(true) * 100000;
1459 // Converts a message code to a human-readable message
1460 function getMessageFromErrorCode ($code) {
1464 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1465 case getCode('LOGOUT_FAILED') : $message = '<span class="notice">{--LOGOUT_FAILED--}</span>'; break;
1466 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1467 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1468 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1469 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1470 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1471 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1472 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1473 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1474 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1475 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1476 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1477 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1478 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1479 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1480 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1481 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1482 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1483 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1484 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1485 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1486 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1487 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1488 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1489 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1490 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1491 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1492 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1493 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1495 case getCode('ERROR_MAILID'):
1496 if (isExtensionActive('mailid', true)) {
1497 $message = '{--ERROR_CONFIRMING_MAIL--}';
1499 $message = generateExtensionInactiveNotInstalledMessage('mailid');
1503 case getCode('EXTENSION_PROBLEM'):
1504 if (isGetRequestParameterSet('ext')) {
1505 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1507 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1511 case getCode('URL_TIME_LOCK'):
1512 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1513 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1514 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1516 // Load timestamp from last order
1517 $content = SQL_FETCHARRAY($result);
1520 SQL_FREERESULT($result);
1522 // Translate it for templates
1523 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1525 // Calculate hours...
1526 $content['hours'] = round(getConfig('url_tlock') / 60 / 60);
1529 $content['minutes'] = round((getConfig('url_tlock') - $content['hours'] * 60 * 60) / 60);
1532 $content['seconds'] = round(getConfig('url_tlock') - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1534 // Finally contruct the message
1535 $message = loadTemplate('tlock_message', true, $content);
1539 // Missing/invalid code
1540 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1543 logDebugMessage(__FUNCTION__, __LINE__, $message);
1547 // Return the message
1551 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1552 function isUrlValidSimple ($url) {
1554 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1556 // Allows http and https
1557 $http = "(http|https)+(:\/\/)";
1559 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1560 // Test double-domains (e.g. .de.vu)
1561 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1563 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1565 $dir = "((/)+([-_\.[:alnum:]])+)*";
1567 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1568 // ... and the string after and including question character
1569 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1570 // Pattern for URLs like http://url/dir/doc.html?var=value
1571 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1572 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1573 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1574 // Pattern for URLs like http://url/dir/?var=value
1575 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1576 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1577 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1578 // Pattern for URLs like http://url/dir/page.ext
1579 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1580 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1581 $pattern['ipdp'] = $http . $ip . $dir . $page;
1582 // Pattern for URLs like http://url/dir
1583 $pattern['d1d'] = $http . $domain1 . $dir;
1584 $pattern['d2d'] = $http . $domain2 . $dir;
1585 $pattern['ipd'] = $http . $ip . $dir;
1586 // Pattern for URLs like http://url/?var=value
1587 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1588 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1589 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1590 // Pattern for URLs like http://url?var=value
1591 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1592 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1593 $pattern['ipg12'] = $http . $ip . $getstring1;
1595 // Test all patterns
1597 foreach ($pattern as $key => $pat) {
1599 if (isDebugRegularExpressionEnabled()) {
1600 // @TODO Are these convertions still required?
1601 $pat = str_replace('.', '\.', $pat);
1602 $pat = str_replace('@', '\@', $pat);
1603 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1606 // Check if expression matches
1607 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1610 if ($reg === true) break;
1613 // Return true/false
1617 // Wtites data to a config.php-style file
1618 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1619 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1620 // Initialize some variables
1626 // Is the file there and read-/write-able?
1627 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1628 $search = 'CFG: ' . $comment;
1629 $tmp = $FQFN . '.tmp';
1631 // Open the source file
1632 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1634 // Is the resource valid?
1635 if (is_resource($fp)) {
1636 // Open temporary file
1637 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1639 // Is the resource again valid?
1640 if (is_resource($fp_tmp)) {
1641 // Mark temporary file as readable
1642 $GLOBALS['file_readable'][$tmp] = true;
1645 while (!feof($fp)) {
1646 // Read from source file
1647 $line = fgets ($fp, 1024);
1649 if (strpos($line, $search) > -1) {
1655 if ($next === $seek) {
1657 $line = $prefix . $DATA . $suffix . "\n";
1663 // Write to temp file
1664 fwrite($fp_tmp, $line);
1670 // Finished writing tmp file
1674 // Close source file
1677 if (($done === true) && ($found === true)) {
1678 // Copy back tmp file and delete tmp :-)
1679 copyFileVerified($tmp, $FQFN, 0644);
1680 return removeFile($tmp);
1681 } elseif ($found === false) {
1682 outputHtml('<strong>CHANGE:</strong> 404!');
1684 outputHtml('<strong>TMP:</strong> UNDONE!');
1688 // File not found, not readable or writeable
1689 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1692 // An error was detected!
1696 // Send notification to admin
1697 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = '0') {
1698 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1700 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName);
1701 sendAdminsEmails($subject, $templateName, $content, $userid);
1703 // Send out-dated way
1704 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName);
1705 $message = loadEmailTemplate($templateName, $content, $userid);
1706 sendAdminEmails($subject, $message);
1710 // Debug message logger
1711 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1712 // Is debug mode enabled?
1713 if ((isDebugModeEnabled()) || ($force === true)) {
1715 $message = str_replace("\r", '', str_replace("\n", '', $message));
1717 // Log this message away
1718 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1722 // Handle extra values
1723 function handleExtraValues ($filterFunction, $value, $extraValue) {
1724 // Default is the value itself
1727 // Do we have a special filter function?
1728 if (!empty($filterFunction)) {
1729 // Does the filter function exist?
1730 if (function_exists($filterFunction)) {
1731 // Do we have extra parameters here?
1732 if (!empty($extraValue)) {
1733 // Put both parameters in one new array by default
1734 $args = array($value, $extraValue);
1736 // If we have an array simply use it and pre-extend it with our value
1737 if (is_array($extraValue)) {
1738 // Make the new args array
1739 $args = merge_array(array($value), $extraValue);
1742 // Call the multi-parameter call-back
1743 $ret = call_user_func_array($filterFunction, $args);
1745 // One parameter call
1746 $ret = call_user_func($filterFunction, $value);
1755 // Converts timestamp selections into a timestamp
1756 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1757 // Init test variable
1761 // Get last three chars
1762 $test = substr($id, -3);
1764 // Improved way of checking! :-)
1765 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1766 // Found a multi-selection for timings?
1767 $test = substr($id, 0, -3);
1768 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)) {
1769 // Generate timestamp
1770 $postData[$test] = createTimestampFromSelections($test, $postData);
1771 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1772 $GLOBALS['skip_config'][$test] = true;
1774 // Remove data from array
1775 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1776 unset($postData[$test . '_' . $rem]);
1787 // Reverts the german decimal comma into Computer decimal dot
1788 function convertCommaToDot ($str) {
1789 // Default float is not a float... ;-)
1792 // Which language is selected?
1793 switch (getLanguage()) {
1794 case 'de': // German language
1795 // Remove german thousand dots first
1796 $str = str_replace('.', '', $str);
1798 // Replace german commata with decimal dot and cast it
1799 $float = (float)str_replace(',', '.', $str);
1802 default: // US and so on
1803 // Remove thousand dots first and cast
1804 $float = (float)str_replace(',', '', $str);
1812 // Handle menu-depending failed logins and return the rendered content
1813 function handleLoginFailures ($accessLevel) {
1814 // Default output is empty ;-)
1817 // Is the session data set?
1818 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1819 // Ignore zero values
1820 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1821 // Non-guest has login failures found, get both data and prepare it for template
1822 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1824 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1825 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1829 $OUT = loadTemplate('login_failures', true, $content);
1832 // Reset session data
1833 setSession('mailer_' . $accessLevel . '_failures', '');
1834 setSession('mailer_' . $accessLevel . '_last_failure', '');
1837 // Return rendered content
1842 function rebuildCache ($cache, $inc = '', $force = false) {
1844 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1846 // Shall I remove the cache file?
1847 if (isCacheInstanceValid()) {
1849 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1851 $GLOBALS['cache_instance']->removeCacheFile($force);
1854 // Include file given?
1857 $inc = sprintf("inc/loader/load-%s.php", $inc);
1859 // Is the include there?
1860 if (isIncludeReadable($inc)) {
1861 // And rebuild it from scratch
1862 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1865 // Include not found
1866 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1872 // Determines the real remote address
1873 function determineRealRemoteAddress ($remoteAddr = false) {
1874 // Is a proxy in use?
1875 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1877 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1878 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1879 // Yet, another proxy
1880 $address = $_SERVER['HTTP_CLIENT_IP'];
1882 // The regular address when no proxy was used
1883 $address = $_SERVER['REMOTE_ADDR'];
1886 // This strips out the real address from proxy output
1887 if (strstr($address, ',')) {
1888 $addressArray = explode(',', $address);
1889 $address = $addressArray[0];
1892 // Return the result
1896 // Adds a bonus mail to the queue
1897 // This is a high-level function!
1898 function addNewBonusMail ($data, $mode = '', $output = true) {
1899 // Use mode from data if not set and availble ;-)
1900 if ((empty($mode)) && (isset($data['mode']))) {
1901 $mode = $data['mode'];
1904 // Generate receiver list
1905 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1908 if (!empty($receiver)) {
1909 // Add bonus mail to queue
1910 addBonusMailToQueue(
1922 // Mail inserted into bonus pool
1923 if ($output === true) {
1924 loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
1926 } elseif ($output === true) {
1927 // More entered than can be reached!
1928 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
1931 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1935 // Determines referal id and sets it
1936 function determineReferalId () {
1937 // Skip this in non-html-mode and outside ref.php
1938 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) {
1942 // Check if refid is set
1943 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1945 } elseif (isPostRequestParameterSet('refid')) {
1946 // Get referal id from POST element refid
1947 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1948 } elseif (isGetRequestParameterSet('refid')) {
1949 // Get referal id from GET parameter refid
1950 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1951 } elseif (isGetRequestParameterSet('ref')) {
1952 // Set refid=ref (the referal link uses such variable)
1953 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1954 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1955 // The variable user comes from click.php
1956 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1957 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1958 // Set session refid als global
1959 $GLOBALS['refid'] = bigintval(getSession('refid'));
1960 } elseif (isRandomReferalIdEnabled()) {
1961 // Select a random user which has confirmed enougth mails
1962 $GLOBALS['refid'] = determineRandomReferalId();
1963 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
1964 // Set default refid as refid in URL
1965 $GLOBALS['refid'] = getDefRefid();
1967 // No default id when sql_patches is not installed or none set
1968 $GLOBALS['refid'] = null;
1971 // Set cookie when default refid > 0
1972 if (!isSessionVariableSet('refid') || (isValidUserId($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
1973 // Default is not found
1976 // Do we have nickname or userid set?
1977 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1978 // Nickname in URL, so load the id
1979 $found = fetchUserData($GLOBALS['refid'], 'nickname');
1980 } elseif (isValidUserId($GLOBALS['refid'])) {
1981 // Direct userid entered
1982 $found = fetchUserData($GLOBALS['refid']);
1985 // Is the record valid?
1986 if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
1987 // No, then reset referal id
1988 $GLOBALS['refid'] = getDefRefid();
1992 setSession('refid', $GLOBALS['refid']);
1995 // Return determined refid
1996 return $GLOBALS['refid'];
1999 // Enables the reset mode and runs it
2000 function doReset () {
2001 // Enable the reset mode
2002 $GLOBALS['reset_enabled'] = true;
2005 runFilterChain('reset');
2008 // Enables the reset mode (hourly, weekly and monthly) and runs it
2009 function doHourly () {
2010 // Enable the hourly reset mode
2011 $GLOBALS['hourly_enabled'] = true;
2013 // Run filters (one always!)
2014 runFilterChain('hourly');
2017 // Our shutdown-function
2018 function shutdown () {
2019 // Call the filter chain 'shutdown'
2020 runFilterChain('shutdown', null);
2022 // Check if not in installation phase and the link is up
2023 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
2025 SQL_CLOSE(__FUNCTION__, __LINE__);
2026 } elseif (!isInstallationPhase()) {
2028 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
2031 // Stop executing here
2036 function initMemberId () {
2037 $GLOBALS['member_id'] = '0';
2040 // Setter for member id
2041 function setMemberId ($memberid) {
2042 // We should not set member id to zero
2043 if ($memberid == '0') {
2044 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
2048 $GLOBALS['member_id'] = bigintval($memberid);
2051 // Getter for member id or returns zero
2052 function getMemberId () {
2053 // Default member id
2056 // Is the member id set?
2057 if (isMemberIdSet()) {
2059 $memberid = $GLOBALS['member_id'];
2066 // Checks ether the member id is set
2067 function isMemberIdSet () {
2068 return (isset($GLOBALS['member_id']));
2071 // Setter for extra title
2072 function setExtraTitle ($extraTitle) {
2073 $GLOBALS['extra_title'] = $extraTitle;
2076 // Getter for extra title
2077 function getExtraTitle () {
2078 // Is the extra title set?
2079 if (!isExtraTitleSet()) {
2080 // No, then abort here
2081 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
2085 return $GLOBALS['extra_title'];
2088 // Checks if the extra title is set
2089 function isExtraTitleSet () {
2090 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
2093 // Reads a directory recursively by default and searches for files not matching
2094 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
2095 // a whole directory.
2096 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
2097 // Add default entries we should exclude
2098 $excludeArray[] = '.';
2099 $excludeArray[] = '..';
2100 $excludeArray[] = '.svn';
2101 $excludeArray[] = '.htaccess';
2103 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
2108 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
2111 while ($baseFile = readdir($dirPointer)) {
2112 // Exclude '.', '..' and entries in $excludeArray automatically
2113 if (in_array($baseFile, $excludeArray, true)) {
2115 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
2119 // Construct include filename and FQFN
2120 $fileName = $baseDir . $baseFile;
2121 $FQFN = getPath() . $fileName;
2123 // Remove double slashes
2124 $FQFN = str_replace('//', '/', $FQFN);
2126 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
2127 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
2128 // These Lines are only for debugging!!
2129 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
2130 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
2131 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
2137 // Skip also files with non-matching prefix genericly
2138 if (($recursive === true) && (isDirectory($FQFN))) {
2139 // Is a redirectory so read it as well
2140 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
2142 // And skip further processing
2144 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
2146 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
2148 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
2149 // Skip wrong suffix as well
2150 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
2152 } elseif (!isFileReadable($FQFN)) {
2153 // Not readable so skip it
2154 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
2158 // Get file' extension (last 4 chars)
2159 $fileExtension = substr($baseFile, -4, 4);
2161 // Is the file a PHP script or other?
2162 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
2163 if (($fileExtension == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
2164 // Is this a valid include file?
2165 if ($extension == '.php') {
2166 // Remove both for extension name
2167 $extName = substr($baseFile, strlen($prefix), -4);
2169 // Add file with or without base path
2170 if ($addBaseDir === true) {
2172 $files[] = $fileName;
2175 $files[] = $baseFile;
2178 // We found .php file but should not search for them, why?
2179 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
2181 } elseif ($fileExtension == $extension) {
2182 // Other, generic file found
2183 $files[] = $fileName;
2188 closedir($dirPointer);
2193 // Return array with include files
2194 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
2198 // Checks wether $prefix is found in $fileName
2199 function isFilePrefixFound ($fileName, $prefix) {
2200 // @TODO Find a way to cache this
2201 return (substr($fileName, 0, strlen($prefix)) == $prefix);
2204 // Maps a module name into a database table name
2205 function mapModuleToTable ($moduleName) {
2206 // Map only these, still lame code...
2207 switch ($moduleName) {
2208 // 'index' is the guest's menu
2209 case 'index': $moduleName = 'guest'; break;
2210 // ... and 'login' the member's menu
2211 case 'login': $moduleName = 'member'; break;
2212 // Anything else will not be mapped, silently.
2219 // Add SQL debug data to array for later output
2220 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
2221 // Do we have cache?
2222 if (!isset($GLOBALS['debug_sql_available'])) {
2223 // Check it and cache it in $GLOBALS
2224 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
2227 // Don't execute anything here if we don't need or ext-other is missing
2228 if ($GLOBALS['debug_sql_available'] === false) {
2232 // Already executed?
2233 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
2234 // Then abort here, we don't need to profile a query twice
2238 // Remeber this as profiled (or not, but we don't care here)
2239 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
2243 'num_rows' => SQL_NUMROWS($result),
2244 'affected' => SQL_AFFECTEDROWS(),
2245 'sql_str' => $sqlString,
2246 'timing' => $timing,
2247 'file' => basename($F),
2252 $GLOBALS['debug_sqls'][] = $record;
2255 // Initializes the cache instance
2256 function initCacheInstance () {
2257 // Check for double-initialization
2258 if (isset($GLOBALS['cache_instance'])) {
2259 // This should not happen and must be fixed
2260 debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
2263 // Load include for CacheSystem class
2264 loadIncludeOnce('inc/classes/cachesystem.class.php');
2266 // Initialize cache system only when it's needed
2267 $GLOBALS['cache_instance'] = new CacheSystem();
2270 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
2271 // Failed to initialize cache sustem
2272 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2276 // Getter for message from array or raw message
2277 function getMessageFromIndexedArray ($message, $pos, $array) {
2278 // Check if the requested message was found in array
2279 if (isset($array[$pos])) {
2280 // ... if yes then use it!
2281 $ret = $array[$pos];
2283 // ... else use default message
2291 // Convert ';' to ', ' for e.g. receiver list
2292 function convertReceivers ($old) {
2293 return str_replace(';', ', ', $old);
2296 // Get a module from filename and access level
2297 function getModuleFromFileName ($file, $accessLevel) {
2298 // Default is 'invalid';
2299 $modCheck = 'invalid';
2301 // @TODO This is still very static, rewrite it somehow
2302 switch ($accessLevel) {
2304 $modCheck = 'admin';
2310 $modCheck = getModule();
2313 default: // Unsupported file name / access level
2314 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2322 // Encodes an URL for adding session id, etc.
2323 function encodeUrl ($url, $outputMode = '0') {
2324 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2325 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) {
2326 // Raw output mode detected or session_name() found in URL
2330 // Do we have a valid session?
2331 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2333 // Determine right seperator
2334 $seperator = '&';
2335 if (strpos($url, '?') === false) {
2338 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2339 // Non-HTML mode (or forced non-HTML mode
2344 if (session_id() != '') {
2345 $url .= $seperator . session_name() . '=' . session_id();
2350 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2352 $url = '{?URL?}/' . $url;
2359 // Simple check for spider
2360 function isSpider () {
2361 // Get the UA and trim it down
2362 $userAgent = trim(strtolower(detectUserAgent(true)));
2364 // It should not be empty, if so it is better a spider/bot
2365 if (empty($userAgent)) {
2366 // It is a spider/bot
2371 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2374 // Function to search for the last modified file
2375 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2377 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2378 // Does it match what we are looking for? (We skip a lot files already!)
2379 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2380 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2382 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2383 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2385 // Walk through all entries
2386 foreach ($ds as $d) {
2387 // Generate proper FQFN
2388 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2390 // Is it a file and readable?
2391 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2392 if (isFileReadable($FQFN)) {
2393 // $FQFN is a readable file so extract the requested data from it
2394 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2395 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2397 // Is the file more recent?
2398 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2399 // This file is newer as the file before
2400 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2401 $last_changed['path_name'] = $FQFN;
2402 $last_changed[$lookFor] = $check;
2406 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2411 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2412 function handleFieldWithBraces ($field) {
2413 // Are there braces [] at the end?
2414 if (substr($field, -2, 2) == '[]') {
2415 // Try to find one and replace it. I do it this way to allow easy
2416 // extending of this code.
2417 foreach (array('admin_list_builder_id_value') as $key) {
2418 // Is the cache entry set?
2419 if (isset($GLOBALS[$key])) {
2421 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2433 // Converts a userid so it can be used in SQL queries
2434 function makeDatabaseUserId ($userid) {
2435 // Is it a valid username?
2436 if (isValidUserId($userid)) {
2438 $userid = bigintval($userid);
2440 // Is not valid or zero
2448 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2449 // Note: This function is cached
2450 function capitalizeUnderscoreString ($str) {
2451 // Do we have cache?
2452 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2453 // Init target string
2456 // Explode it with the underscore, but rewrite dashes to underscore before
2457 $strArray = explode('_', str_replace('-', '_', $str));
2459 // "Walk" through all elements and make them lower-case but first upper-case
2460 foreach ($strArray as $part) {
2461 // Capitalize the string part
2462 $capitalized .= firstCharUpperCase($part);
2465 // Store the converted string in cache array
2466 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2470 return $GLOBALS[__FUNCTION__][$str];
2473 // Generate admin links for mail order
2474 // mailType can be: 'mid' or 'bid'
2475 function generateAdminMailLinks ($mailType, $mailId) {
2480 // Default column for mail status is 'data_type'
2481 // @TODO Rename column data_type to e.g. mail_status
2482 $statusColumn = 'data_type';
2484 // Which mail do we have?
2485 switch ($mailType) {
2486 case 'bid': // Bonus mail
2490 case 'mid': // Member mail
2494 default: // Handle unsupported types
2495 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2496 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2500 // Is the mail type supported?
2501 if (!empty($table)) {
2502 // Query for the mail
2503 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2504 array($statusColumn, $table, bigintval($mailId)), __FILE__, __LINE__);
2506 // Do we have one entry there?
2507 if (SQL_NUMROWS($result) == 1) {
2509 $content = SQL_FETCHARRAY($result);
2510 die('<pre>'.print_r($content, true).'</pre>');
2514 SQL_FREERESULT($result);
2517 // Return generated HTML code
2521 //-----------------------------------------------------------------------------
2522 // Automatically re-created functions, all taken from user comments on www.php.net
2523 //-----------------------------------------------------------------------------
2525 if (!function_exists('html_entity_decode')) {
2526 // Taken from documentation on www.php.net
2527 function html_entity_decode ($string) {
2528 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2529 $trans_tbl = array_flip($trans_tbl);
2530 return strtr($string, $trans_tbl);
2534 if (!function_exists('http_build_query')) {
2535 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
2536 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
2538 foreach ((array) $data as $k => $v) {
2539 if (is_int($k) && $prefix != null) {
2540 $k = urlencode($prefix . $k);
2543 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
2545 if (is_array($v) || is_object($v)) {
2546 array_push($ret, http_build_query($v, '', $sep, $k));
2548 array_push($ret, $k.'='.urlencode($v));
2552 if (empty($sep)) $sep = ini_get('arg_separator.output');
2554 return implode($sep, $ret);