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 // Init fatal message array
44 function initFatalMessages () {
45 $GLOBALS['fatal_messages'] = array();
48 // Getter for whole fatal error messages
49 function getFatalArray () {
50 return $GLOBALS['fatal_messages'];
53 // Add a fatal error message to the queue array
54 function addFatalMessage ($F, $L, $message, $extra = '') {
55 if (is_array($extra)) {
56 // Multiple extras for a message with masks
57 $message = call_user_func_array('sprintf', $extra);
58 } elseif (!empty($extra)) {
59 // $message is text with a mask plus extras to insert into the text
60 $message = sprintf($message, $extra);
63 // Add message to $GLOBALS['fatal_messages']
64 $GLOBALS['fatal_messages'][] = $message;
66 // Log fatal messages away
67 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
70 // Getter for total fatal message count
71 function getTotalFatalErrors () {
75 // Do we have at least the first entry?
76 if (!empty($GLOBALS['fatal_messages'][0])) {
78 $count = count($GLOBALS['fatal_messages']);
85 // Send mail out to an email address
86 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
87 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'toEmail=' . $toEmail . ',subject=' . $subject . ',isHtml=' . $isHtml);
90 if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
91 // Value detected, is the message extension installed?
92 // @TODO Extension 'msg' does not exist
93 if (isExtensionActive('msg')) {
94 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
97 // Does the user exist?
98 if (fetchUserData($toEmail)) {
100 $toEmail = getUserData('email');
103 $toEmail = getWebmaster();
106 } elseif ($toEmail == '0') {
108 $toEmail = getWebmaster();
110 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
112 // Check for PHPMailer or debug-mode
113 if ((!checkPhpMailerUsage()) || (isDebugModeEnabled())) {
114 // Prefix is '' for text mails
118 if ($isHtml == 'Y') {
123 // Not in PHPMailer-Mode
124 if (empty($mailHeader)) {
125 // Load email header template
126 $mailHeader = loadEmailTemplate($prefix . 'header');
129 $mailHeader .= loadEmailTemplate($prefix . 'header');
133 // Fix HTML parameter (default is no!)
134 if (empty($isHtml)) {
138 // Debug mode enabled?
139 if (isDebugModeEnabled()) {
140 // In debug mode we want to display the mail instead of sending it away so we can debug this part
142 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
143 To : ' . htmlentities(utf8_decode($toEmail)) . '
144 Subject : ' . htmlentities(utf8_decode($subject)) . '
145 Message : ' . htmlentities(utf8_decode($message)) . '
148 // This is always fine
150 } elseif (!empty($toEmail)) {
152 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
153 } elseif ($isHtml != 'Y') {
154 // Problem detected while sending a mail, forward it to admin
155 return sendRawEmail(getWebmaster(), '[PROBLEM:]' . $subject, $message, $mailHeader);
158 // Why did we end up here? This should not happen
159 debug_report_bug(__FUNCTION__, __LINE__, 'Ending up: template=' . $template);
162 // Check to use wether legacy mail() command or PHPMailer class
163 // @TODO Rewrite this to an extension 'smtp'
165 function checkPhpMailerUsage() {
166 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
169 // Send out a raw email with PHPMailer class or legacy mail() command
170 function sendRawEmail ($toEmail, $subject, $message, $headers) {
171 // Just compile all to put out all configs, etc.
172 $eval = '$toEmail = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($toEmail), false)) . '"); ';
173 $eval .= '$subject = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($subject), false)) . '"); ';
174 $eval .= '$headers = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($headers), false)) . '"); ';
176 // Do not decode entities in the message because we also send HTML mails through this function
177 $eval .= '$message = "' . escapeQuotes(doFinalCompilation(compileRawCode($message), false)) . '";';
179 // Run the final eval() command
182 // Shall we use PHPMailer class or legacy mode?
183 if (checkPhpMailerUsage()) {
184 // Use PHPMailer class with SMTP enabled
185 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
186 loadIncludeOnce('inc/phpmailer/class.smtp.php');
189 $mail = new PHPMailer();
191 // Set charset to UTF-8
192 $mail->CharSet = 'UTF-8';
194 // Path for PHPMailer
195 $mail->PluginDir = sprintf("%sinc/phpmailer/", getPath());
198 $mail->SMTPAuth = true;
199 $mail->Host = getConfig('SMTP_HOSTNAME');
201 $mail->Username = getConfig('SMTP_USER');
202 $mail->Password = getConfig('SMTP_PASSWORD');
203 if (empty($headers)) {
204 $mail->From = getWebmaster();
206 $mail->From = $headers;
208 $mail->FromName = getMainTitle();
209 $mail->Subject = $subject;
210 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
211 $mail->Body = $message;
212 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
213 $mail->WordWrap = 70;
216 $mail->Body = decodeEntities($message);
219 $mail->AddAddress($toEmail, '');
220 $mail->AddReplyTo(getWebmaster(), getMainTitle());
221 $mail->AddCustomHeader('Errors-To:' . getWebmaster());
222 $mail->AddCustomHeader('X-Loop:' . getWebmaster());
223 $mail->AddCustomHeader('Bounces-To:' . getWebmaster());
226 // Has an error occured?
227 if (!empty($mail->ErrorInfo)) {
229 logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
238 // Use legacy mail() command
239 return mail($toEmail, $subject, decodeEntities($message), $headers);
243 // Generate a password in a specified length or use default password length
244 function generatePassword ($length = '0', $exclude = array()) {
245 // Auto-fix invalid length of zero
246 if ($length == '0') {
247 $length = getPassLen();
250 // Initialize array with all allowed chars
251 $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,-,+,_,/,.');
253 // Exclude some entries
254 $ABC = array_diff($ABC, $exclude);
256 // Start creating password
258 for ($i = '0'; $i < $length; $i++) {
259 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
262 // When the size is below 40 we can also add additional security by scrambling
263 // it. Otherwise we may corrupt hashes
264 if (strlen($PASS) <= 40) {
265 // Also scramble the password
266 $PASS = scrambleString($PASS);
269 // Return the password
273 // Generates a human-readable timestamp from the Uni* stamp
274 function generateDateTime ($time, $mode = '0') {
275 // If the stamp is zero it mostly didn't "happen"
278 return '{--NEVER_HAPPENED--}';
281 // Filter out numbers
282 $time = bigintval($time);
285 if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
287 return $GLOBALS[__FUNCTION__][$time][$mode];
291 switch (getLanguage()) {
292 case 'de': // German date / time format
294 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
295 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
296 case '2': $ret = date('d.m.Y|H:i', $time); break;
297 case '3': $ret = date('d.m.Y', $time); break;
298 case '4': $ret = date('d.m.Y|H:i:s', $time); break;
299 case '5': $ret = date('d-m-Y (l-F-T)', $time); break;
300 case '6': $ret = date('Ymd', $time); break;
301 case '7': $ret = date('Y-m-d H:i:s', $time); break; // Compatible with MySQL TIMESTAMP
303 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
308 default: // Default is the US date / time format!
310 case '0': $ret = date('r', $time); break;
311 case '1': $ret = strtolower(date('Y-m-d - g:i A', $time)); break;
312 case '2': $ret = date('y-m-d|H:i', $time); break;
313 case '3': $ret = date('y-m-d', $time); break;
314 case '4': $ret = date('d.m.Y|H:i:s', $time); break;
315 case '5': $ret = date('d-m-Y (l-F-T)', $time); break;
316 case '6': $ret = date('Ymd', $time); break;
317 case '7': $ret = date('Y-m-d H:i:s', $time); break; // Compatible with MySQL TIMESTAMP
319 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
325 $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
331 // Translates Y/N to yes/no
332 function translateYesNo ($yn) {
334 if (!isset($GLOBALS[__FUNCTION__][$yn])) {
336 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
338 case 'Y': $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; break;
339 case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break;
342 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
348 return $GLOBALS[__FUNCTION__][$yn];
351 // Translates the american decimal dot into a german comma
352 function translateComma ($dotted, $cut = true, $max = '0') {
353 // First, cast all to double, due to PHP changes
354 $dotted = (double) $dotted;
356 // Default is 3 you can change this in admin area "Settings -> Misc Options"
357 if (!isConfigEntrySet('max_comma')) {
358 setConfigEntry('max_comma', 3);
361 // Use from config is default
362 $maxComma = getConfig('max_comma');
364 // Use from parameter?
370 if (($cut === true) && ($max == '0')) {
371 // Test for commata if in cut-mode
372 $com = explode('.', $dotted);
373 if (count($com) < 2) {
374 // Don't display commatas even if there are none... ;-)
382 $translated = $dotted;
383 switch (getLanguage()) {
384 case 'de': // German language
385 $translated = number_format($dotted, $maxComma, ',', '.');
388 default: // All others
389 $translated = number_format($dotted, $maxComma, '.', ',');
393 // Return translated value
394 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
398 // Translate Uni*-like gender to human-readable
399 function translateGender ($gender) {
401 $ret = '!' . $gender . '!';
403 // Male/female or company?
408 $ret = sprintf("{--GENDER_%s--}", $gender);
412 // Please report bugs on unknown genders
413 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
417 // Return translated gender
421 // "Translates" the user status
422 function translateUserStatus ($status) {
423 // Default status is unknown if something goes through
424 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
426 // Generate message depending on status
431 $ret = sprintf("{--ACCOUNT_STATUS_%s--}", $status);
436 $ret = '{--ACCOUNT_STATUS_DELETED--}';
440 // Please report all unknown status
441 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
449 // "Translates" 'visible' and 'locked' to a CSS class
450 function translateMenuVisibleLocked ($content, $prefix = '') {
451 // Default is 'menu_unknown'
452 $content['visible_css'] = $prefix . 'menu_unknown';
454 // Translate 'visible' and keep an eye on the prefix
455 switch ($content['visible']) {
457 case 'Y': $content['visible_css'] = $prefix . 'menu_visible' ; break;
458 case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break;
460 // Please report this
461 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, true) . '</pre>');
465 // Translate 'locked' and keep an eye on the prefix
466 switch ($content['locked']) {
468 case 'Y': $content['locked_css'] = $prefix . 'menu_locked' ; break;
469 case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break;
471 // Please report this
472 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, true) . '</pre>');
476 // Return the resulting array
480 // Generates an URL for the dereferer
481 function generateDerefererUrl ($url) {
482 // Don't de-refer our own links!
483 if (substr($url, 0, strlen(getUrl())) != getUrl()) {
484 // De-refer this link
485 $url = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($url)) . '%}';
492 // Generates an URL for the frametester
493 function generateFrametesterUrl ($url) {
494 // Prepare frametester URL
495 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
496 encodeString(compileUriCode($url))
499 // Return the new URL
500 return $frametesterUrl;
503 // Count entries from e.g. a selection box
504 function countSelection ($array) {
506 if (!is_array($array)) {
508 debug_report_bug(__FUNCTION__, __LINE__, 'No array provided.');
515 foreach ($array as $key => $selected) {
517 if (!empty($selected)) $ret++;
520 // Return counted selections
524 // Generates a timestamp (some wrapper for mktime())
525 function makeTime ($hours, $minutes, $seconds, $stamp) {
526 // Extract day, month and year from given timestamp
527 $days = getDay($stamp);
528 $months = getMonth($stamp);
529 $years = getYear($stamp);
531 // Create timestamp for wished time which depends on extracted date
542 // Redirects to an URL and if neccessarry extends it with own base URL
543 function redirectToUrl ($url, $allowSpider = true) {
545 if (substr($url, 0, 6) == '{%url=') {
546 $url = substr($url, 6, -2);
550 eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
552 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
553 $rel = ' rel="external"';
555 // Do we have internal or external URL?
556 if (substr($url, 0, strlen(getUrl())) == getUrl()) {
557 // Own (=internal) URL
561 // Three different ways to debug...
562 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'URL=' . $url);
563 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
564 //* DEBUG: */ die($url);
566 // We should not sent a redirect if headers are already sent
567 if (!headers_sent()) {
568 // Clear output buffer
571 // Clear own output buffer
572 $GLOBALS['output'] = '';
574 // Load URL when headers are not sent
575 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), false));
577 // Output error message
578 loadInclude('inc/header.php');
579 loadTemplate('redirect_url', false, str_replace('&', '&', $url));
580 loadInclude('inc/footer.php');
583 // Shut the mailer down here
587 /************************************************************************
589 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
590 * $a_sort sortiert: *
592 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
593 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
594 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
595 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
596 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
598 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
599 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
600 * Sie, dass es doch nicht so schwer ist! :-) *
602 ************************************************************************/
603 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
605 while ($primary_key < count($a_sort)) {
606 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
607 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
609 if ($nums === false) {
610 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
611 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
612 } elseif ($key != $key2) {
613 // Sort numbers (E.g.: 9 < 10)
614 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
615 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
619 // We have found two different values, so let's sort whole array
620 foreach ($dummy as $sort_key => $sort_val) {
621 $t = $dummy[$sort_key][$key];
622 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
623 $dummy[$sort_key][$key2] = $t;
634 // Write back sorted array
640 // Deprecated : $length (still has one reference in this function)
641 // Optional : $extraData
643 function generateRandomCode ($length, $code, $userid, $extraData = '') {
644 // Build server string
645 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
648 $keys = getSiteKey() . getEncryptSeperator() . getDateKey();
649 if (isConfigEntrySet('secret_key')) {
650 $keys .= getEncryptSeperator().getSecretKey();
652 if (isConfigEntrySet('file_hash')) {
653 $keys .= getEncryptSeperator().getFileHash();
655 $keys .= getEncryptSeperator() . getDateFromPatchTime();
656 if (isConfigEntrySet('master_salt')) {
657 $keys .= getEncryptSeperator().getMasterSalt();
660 // Build string from misc data
661 $data = $code . getEncryptSeperator() . $userid . getEncryptSeperator() . $extraData;
663 // Add more additional data
664 if (isSessionVariableSet('u_hash')) {
665 $data .= getEncryptSeperator() . getSession('u_hash');
668 // Add referal id, language, theme and userid
669 $data .= getEncryptSeperator() . determineReferalId();
670 $data .= getEncryptSeperator() . getLanguage();
671 $data .= getEncryptSeperator() . getCurrentTheme();
672 $data .= getEncryptSeperator() . getMemberId();
674 // Calculate number for generating the code
675 $a = $code + getConfig('_ADD') - 1;
677 if (isConfigEntrySet('master_salt')) {
678 // Generate hash with master salt from modula of number with the prime number and other data
679 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a, getMasterSalt());
681 // Create number from hash
682 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
684 // Generate hash with "hash of site key" from modula of number with the prime number and other data
685 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
687 // Create number from hash
688 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
691 // At least 10 numbers shall be secure enought!
692 $len = getCodeLength();
700 // Cut off requested counts of number
701 $return = substr(str_replace('.', '', $rcode), 0, $len);
703 // Done building code
707 // Does only allow numbers
708 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
709 // Filter all numbers out
710 $ret = preg_replace('/[^0123456789]/', '', $num);
713 if ($castValue === true) {
714 // Cast to biggest numeric type
715 $ret = (double) $ret;
718 // Has the whole value changed?
719 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true) && (!is_null($num))) {
721 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
728 // Creates a Uni* timestamp from given selection data and prefix
729 function createEpocheTimeFromSelections ($prefix, $postData) {
730 // Initial return value
733 // Do we have a leap year?
735 $TEST = getYear() / 4;
738 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
739 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) {
740 $SWITCH = getOneDay();
743 // First add years...
744 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
747 $ret += $postData[$prefix . '_mo'] * 2628000;
750 $ret += $postData[$prefix . '_we'] * 604800;
753 $ret += $postData[$prefix . '_da'] * 86400;
756 $ret += $postData[$prefix . '_ho'] * 3600;
759 $ret += $postData[$prefix . '_mi'] * 60;
761 // And at last seconds...
762 $ret += $postData[$prefix . '_se'];
764 // Return calculated value
768 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
769 function createFancyTime ($stamp) {
770 // Get data array with years/months/weeks/days/...
771 $data = createTimeSelections($stamp, '', '', '', true);
773 foreach ($data as $k => $v) {
775 // Value is greater than 0 "eval" data to return string
776 $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
781 // Do we have something there?
782 if (strlen($ret) > 0) {
783 // Remove leading commata and space
784 $ret = substr($ret, 2);
787 $ret = '0 {--_SECONDS--}';
790 // Return fancy time string
794 // Extract host from script name
795 function extractHostnameFromUrl (&$script) {
796 // Use default SERVER_URL by default... ;) So?
797 $url = getServerUrl();
799 // Is this URL valid?
800 if (substr($script, 0, 7) == 'http://') {
801 // Use the hostname from script URL as new hostname
802 $url = substr($script, 7);
803 $extract = explode('/', $url);
805 // Done extracting the URL :)
809 $host = str_replace('http://', '', $url);
810 if (isInString('/', $host)) {
811 $host = substr($host, 0, strpos($host, '/'));
814 // Generate relative URL
815 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
816 if (substr(strtolower($script), 0, 7) == 'http://') {
817 // But only if http:// is in front!
818 $script = substr($script, (strlen($url) + 7));
819 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
821 $script = substr($script, (strlen($url) + 8));
824 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
825 if (substr($script, 0, 1) == '/') {
826 $script = substr($script, 1);
833 // Taken from www.php.net isInStringIgnoreCase() user comments
834 function isEmailValid ($email) {
835 // Check first part of email address
836 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
839 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
842 $regex = '@^' . $first . '\@' . $domain . '$@iU';
844 // Return check result
845 return preg_match($regex, $email);
848 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
849 function isUrlValid ($url, $compile=true) {
851 $url = trim(urldecode($url));
852 //* DEBUG: */ debugOutput($url);
854 // Compile some chars out...
855 if ($compile === true) {
856 $url = compileUriCode($url, false, false, false);
858 //* DEBUG: */ debugOutput($url);
860 // Check for the extension filter
861 if (isExtensionActive('filter')) {
862 // Use the extension's filter set
863 return FILTER_VALIDATE_URL($url, false);
866 // If not installed, perform a simple test. Just make it sure there is always a http:// or
867 // https:// in front of the URLs
868 return isUrlValidSimple($url);
871 // Generate a hash for extra-security for all passwords
872 function generateHash ($plainText, $salt = '', $hash = true) {
874 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
876 // Is the required extension 'sql_patches' there and a salt is not given?
877 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
878 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
879 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
880 if ($hash === true) {
882 return md5($plainText);
889 // Do we miss an arry element here?
890 if (!isConfigEntrySet('file_hash')) {
892 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
895 // When the salt is empty build a new one, else use the first x configured characters as the salt
897 // Build server string for more entropy
898 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
901 $keys = getSiteKey() . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
904 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
906 // Calculate number for generating the code
907 $a = time() + getConfig('_ADD') - 1;
909 // Generate SHA1 sum from modula of number and the prime number
910 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a);
911 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
912 $sha1 = scrambleString($sha1);
913 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
914 //* DEBUG: */ $sha1b = descrambleString($sha1);
915 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
917 // Generate the password salt string
918 $salt = substr($sha1, 0, getSaltLength());
919 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
922 //* DEBUG: */ debugOutput('salt=' . $salt);
923 $salt = substr($salt, 0, getSaltLength());
924 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
926 // Sanity check on salt
927 if (strlen($salt) != getSaltLength()) {
929 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
933 // Generate final hash (for debug output)
934 $finalHash = $salt . sha1($salt . $plainText);
937 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
944 function scrambleString ($str) {
948 // Final check, in case of failure it will return unscrambled string
949 if (strlen($str) > 40) {
950 // The string is to long
952 } elseif (strlen($str) == 40) {
954 $scrambleNums = explode(':', getPassScramble());
956 // Generate new numbers
957 $scrambleNums = explode(':', genScrambleString(strlen($str)));
960 // Compare both lengths and abort if different
961 if (strlen($str) != count($scrambleNums)) return $str;
963 // Scramble string here
964 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
965 for ($idx = 0; $idx < strlen($str); $idx++) {
966 // Get char on scrambled position
967 $char = substr($str, $scrambleNums[$idx], 1);
969 // Add it to final output string
973 // Return scrambled string
974 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
978 // De-scramble a string scrambled by scrambleString()
979 function descrambleString ($str) {
980 // Scramble only 40 chars long strings
981 if (strlen($str) != 40) return $str;
983 // Load numbers from config
984 $scrambleNums = explode(':', getPassScramble());
987 if (count($scrambleNums) != 40) return $str;
989 // Begin descrambling
990 $orig = str_repeat(' ', 40);
991 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
992 for ($idx = 0; $idx < 40; $idx++) {
993 $char = substr($str, $idx, 1);
994 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
997 // Return scrambled string
998 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
1002 // Generated a "string" for scrambling
1003 function genScrambleString ($len) {
1004 // Prepare array for the numbers
1005 $scrambleNumbers = array();
1007 // First we need to setup randomized numbers from 0 to 31
1008 for ($idx = 0; $idx < $len; $idx++) {
1010 $rand = mt_rand(0, ($len - 1));
1012 // Check for it by creating more numbers
1013 while (array_key_exists($rand, $scrambleNumbers)) {
1014 $rand = mt_rand(0, ($len - 1));
1018 $scrambleNumbers[$rand] = $rand;
1021 // So let's create the string for storing it in database
1022 $scrambleString = implode(':', $scrambleNumbers);
1023 return $scrambleString;
1026 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1027 function encodeHashForCookie ($passHash) {
1028 // Return vanilla password hash
1031 // Is a secret key and master salt already initialized?
1032 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1033 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1034 // Only calculate when the secret key is generated
1035 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1036 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1037 // Both keys must have same length so return unencrypted
1038 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1042 $newHash = ''; $start = 9;
1043 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1044 for ($idx = 0; $idx < 20; $idx++) {
1045 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1046 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1047 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1048 $mod = dechex($idx);
1049 if ($part1 > $part2) {
1050 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1051 } elseif ($part2 > $part1) {
1052 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1054 $mod = substr($mod, 0, 2);
1055 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1056 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1057 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1062 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1063 $ret = generateHash($newHash, getMasterSalt());
1067 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1071 // Fix "deleted" cookies
1072 function fixDeletedCookies ($cookies) {
1073 // Is this an array with entries?
1074 if ((is_array($cookies)) && (count($cookies) > 0)) {
1075 // Then check all cookies if they are marked as deleted!
1076 foreach ($cookies as $cookieName) {
1077 // Is the cookie set to "deleted"?
1078 if (getSession($cookieName) == 'deleted') {
1079 setSession($cookieName, '');
1085 // Checks if a given apache module is loaded
1086 function isApacheModuleLoaded ($apacheModule) {
1087 // Check it and return result
1088 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1091 // Get current theme name
1092 function getCurrentTheme () {
1093 // The default theme is 'default'... ;-)
1096 // Do we have ext-theme installed and active?
1097 if (isExtensionActive('theme')) {
1098 // Call inner method
1099 $ret = getActualTheme();
1102 // Return theme value
1106 // Generates an error code from given account status
1107 function generateErrorCodeFromUserStatus ($status = '') {
1108 // If no status is provided, use the default, cached
1109 if ((empty($status)) && (isMember())) {
1111 $status = getUserData('status');
1114 // Default error code if unknown account status
1115 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1117 // Generate constant name
1118 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1120 // Is the constant there?
1121 if (isCodeSet($codeName)) {
1123 $errorCode = getCode($codeName);
1126 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1129 // Return error code
1133 // Back-ported from the new ship-simu engine. :-)
1134 function debug_get_printable_backtrace () {
1136 $backtrace = '<ol>';
1138 // Get and prepare backtrace for output
1139 $backtraceArray = debug_backtrace();
1140 foreach ($backtraceArray as $key => $trace) {
1141 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1142 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1143 if (!isset($trace['args'])) $trace['args'] = array();
1144 $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>';
1148 $backtrace .= '</ol>';
1150 // Return the backtrace
1154 // A mail-able backtrace
1155 function debug_get_mailable_backtrace () {
1159 // Get and prepare backtrace for output
1160 $backtraceArray = debug_backtrace();
1161 foreach ($backtraceArray as $key => $trace) {
1162 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1163 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1164 if (!isset($trace['args'])) $trace['args'] = array();
1165 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1168 // Return the backtrace
1172 // Generates a ***weak*** seed
1173 function generateSeed () {
1174 return microtime(true) * 100000;
1177 // Converts a message code to a human-readable message
1178 function getMessageFromErrorCode ($code) {
1182 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1183 case getCode('LOGOUT_FAILED') : $message = '<span class="notice">{--LOGOUT_FAILED--}</span>'; break;
1184 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1185 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1186 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1187 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1188 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1189 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1190 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1191 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1192 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1193 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1194 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1195 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1196 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1197 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1198 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1199 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1200 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1201 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1202 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1203 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1204 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1205 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1206 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1207 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1208 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1209 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1210 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1211 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1213 case getCode('ERROR_MAILID'):
1214 if (isExtensionActive('mailid', true)) {
1215 $message = '{--ERROR_CONFIRMING_MAIL--}';
1217 $message = generateExtensionInactiveNotInstalledMessage('mailid');
1221 case getCode('EXTENSION_PROBLEM'):
1222 if (isGetRequestParameterSet('ext')) {
1223 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1225 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1229 case getCode('URL_TIME_LOCK'):
1230 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1231 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1232 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1234 // Load timestamp from last order
1235 $content = SQL_FETCHARRAY($result);
1238 SQL_FREERESULT($result);
1240 // Translate it for templates
1241 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1243 // Calculate hours...
1244 $content['hours'] = round(getUrlTlock() / 60 / 60);
1247 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1250 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1252 // Finally contruct the message
1253 $message = loadTemplate('tlock_message', true, $content);
1257 // Missing/invalid code
1258 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1261 logDebugMessage(__FUNCTION__, __LINE__, $message);
1265 // Return the message
1269 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1270 function isUrlValidSimple ($url) {
1272 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1274 // Allows http and https
1275 $http = "(http|https)+(:\/\/)";
1277 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1278 // Test double-domains (e.g. .de.vu)
1279 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1281 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1283 $dir = "((/)+([-_\.[:alnum:]])+)*";
1285 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1286 // ... and the string after and including question character
1287 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1288 // Pattern for URLs like http://url/dir/doc.html?var=value
1289 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1290 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1291 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1292 // Pattern for URLs like http://url/dir/?var=value
1293 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1294 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1295 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1296 // Pattern for URLs like http://url/dir/page.ext
1297 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1298 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1299 $pattern['ipdp'] = $http . $ip . $dir . $page;
1300 // Pattern for URLs like http://url/dir
1301 $pattern['d1d'] = $http . $domain1 . $dir;
1302 $pattern['d2d'] = $http . $domain2 . $dir;
1303 $pattern['ipd'] = $http . $ip . $dir;
1304 // Pattern for URLs like http://url/?var=value
1305 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1306 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1307 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1308 // Pattern for URLs like http://url?var=value
1309 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1310 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1311 $pattern['ipg12'] = $http . $ip . $getstring1;
1313 // Test all patterns
1315 foreach ($pattern as $key => $pat) {
1317 if (isDebugRegularExpressionEnabled()) {
1318 // @TODO Are these convertions still required?
1319 $pat = str_replace('.', '\.', $pat);
1320 $pat = str_replace('@', '\@', $pat);
1321 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1324 // Check if expression matches
1325 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1328 if ($reg === true) break;
1331 // Return true/false
1335 // Wtites data to a config.php-style file
1336 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1337 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1338 // Initialize some variables
1344 // Is the file there and read-/write-able?
1345 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1346 $search = 'CFG: ' . $comment;
1347 $tmp = $FQFN . '.tmp';
1349 // Open the source file
1350 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1352 // Is the resource valid?
1353 if (is_resource($fp)) {
1354 // Open temporary file
1355 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1357 // Is the resource again valid?
1358 if (is_resource($fp_tmp)) {
1359 // Mark temporary file as readable
1360 $GLOBALS['file_readable'][$tmp] = true;
1363 while (!feof($fp)) {
1364 // Read from source file
1365 $line = fgets ($fp, 1024);
1367 if (strpos($line, $search) > -1) {
1373 if ($next === $seek) {
1375 $line = $prefix . $DATA . $suffix . "\n";
1381 // Write to temp file
1382 fwrite($fp_tmp, $line);
1388 // Finished writing tmp file
1392 // Close source file
1395 if (($done === true) && ($found === true)) {
1396 // Copy back tmp file and delete tmp :-)
1397 copyFileVerified($tmp, $FQFN, 0644);
1398 return removeFile($tmp);
1399 } elseif ($found === false) {
1400 outputHtml('<strong>CHANGE:</strong> 404!');
1402 outputHtml('<strong>TMP:</strong> UNDONE!');
1406 // File not found, not readable or writeable
1407 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1410 // An error was detected!
1414 // Send notification to admin
1415 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = '0') {
1416 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1418 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName);
1419 sendAdminsEmails($subject, $templateName, $content, $userid);
1421 // Send out-dated way
1422 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName);
1423 $message = loadEmailTemplate($templateName, $content, $userid);
1424 sendAdminEmails($subject, $message);
1428 // Debug message logger
1429 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1430 // Is debug mode enabled?
1431 if ((isDebugModeEnabled()) || ($force === true)) {
1433 $message = str_replace("\r", '', str_replace("\n", '', $message));
1435 // Log this message away
1436 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1440 // Handle extra values
1441 function handleExtraValues ($filterFunction, $value, $extraValue) {
1442 // Default is the value itself
1445 // Do we have a special filter function?
1446 if (!empty($filterFunction)) {
1447 // Does the filter function exist?
1448 if (function_exists($filterFunction)) {
1449 // Do we have extra parameters here?
1450 if (!empty($extraValue)) {
1451 // Put both parameters in one new array by default
1452 $args = array($value, $extraValue);
1454 // If we have an array simply use it and pre-extend it with our value
1455 if (is_array($extraValue)) {
1456 // Make the new args array
1457 $args = merge_array(array($value), $extraValue);
1460 // Call the multi-parameter call-back
1461 $ret = call_user_func_array($filterFunction, $args);
1463 // One parameter call
1464 $ret = call_user_func($filterFunction, $value);
1473 // Converts timestamp selections into a timestamp
1474 function convertSelectionsToEpocheTime (array &$postData, array &$DATA, &$id, &$skip) {
1475 // Init test variable
1479 // Get last three chars
1480 $test = substr($id, -3);
1482 // Improved way of checking! :-)
1483 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1484 // Found a multi-selection for timings?
1485 $test = substr($id, 0, -3);
1486 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)) {
1487 // Generate timestamp
1488 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1489 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1490 $GLOBALS['skip_config'][$test] = true;
1492 // Remove data from array
1493 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1494 unset($postData[$test . '_' . $rem]);
1505 // Reverts the german decimal comma into Computer decimal dot
1506 function convertCommaToDot ($str) {
1507 // Default float is not a float... ;-)
1510 // Which language is selected?
1511 switch (getLanguage()) {
1512 case 'de': // German language
1513 // Remove german thousand dots first
1514 $str = str_replace('.', '', $str);
1516 // Replace german commata with decimal dot and cast it
1517 $float = (float)str_replace(',', '.', $str);
1520 default: // US and so on
1521 // Remove thousand dots first and cast
1522 $float = (float)str_replace(',', '', $str);
1530 // Handle menu-depending failed logins and return the rendered content
1531 function handleLoginFailures ($accessLevel) {
1532 // Default output is empty ;-)
1535 // Is the session data set?
1536 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1537 // Ignore zero values
1538 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1539 // Non-guest has login failures found, get both data and prepare it for template
1540 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1542 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1543 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1547 $OUT = loadTemplate('login_failures', true, $content);
1550 // Reset session data
1551 setSession('mailer_' . $accessLevel . '_failures', '');
1552 setSession('mailer_' . $accessLevel . '_last_failure', '');
1555 // Return rendered content
1560 function rebuildCache ($cache, $inc = '', $force = false) {
1562 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1564 // Shall I remove the cache file?
1565 if (isCacheInstanceValid()) {
1567 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1569 $GLOBALS['cache_instance']->removeCacheFile($force);
1572 // Include file given?
1575 $inc = sprintf("inc/loader/load-%s.php", $inc);
1577 // Is the include there?
1578 if (isIncludeReadable($inc)) {
1579 // And rebuild it from scratch
1580 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1583 // Include not found
1584 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1590 // Determines the real remote address
1591 function determineRealRemoteAddress ($remoteAddr = false) {
1592 // Is a proxy in use?
1593 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1595 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1596 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1597 // Yet, another proxy
1598 $address = $_SERVER['HTTP_CLIENT_IP'];
1600 // The regular address when no proxy was used
1601 $address = $_SERVER['REMOTE_ADDR'];
1604 // This strips out the real address from proxy output
1605 if (strstr($address, ',')) {
1606 $addressArray = explode(',', $address);
1607 $address = $addressArray[0];
1610 // Return the result
1614 // Adds a bonus mail to the queue
1615 // This is a high-level function!
1616 function addNewBonusMail ($data, $mode = '', $output = true) {
1617 // Use mode from data if not set and availble ;-)
1618 if ((empty($mode)) && (isset($data['mode']))) {
1619 $mode = $data['mode'];
1622 // Generate receiver list
1623 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1626 if (!empty($receiver)) {
1627 // Add bonus mail to queue
1628 addBonusMailToQueue(
1640 // Mail inserted into bonus pool
1641 if ($output === true) {
1642 displayMessage('{--ADMIN_BONUS_SEND--}');
1644 } elseif ($output === true) {
1645 // More entered than can be reached!
1646 displayMessage('{--ADMIN_MORE_SELECTED--}');
1649 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1653 // Determines referal id and sets it
1654 function determineReferalId () {
1655 // Skip this in non-html-mode and outside ref.php
1656 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) {
1660 // Check if refid is set
1661 if (isReferalIdValid()) {
1663 } elseif (isPostRequestParameterSet('refid')) {
1664 // Get referal id from POST element refid
1665 setReferalId(secureString(postRequestParameter('refid')));
1666 } elseif (isGetRequestParameterSet('refid')) {
1667 // Get referal id from GET parameter refid
1668 setReferalId(secureString(getRequestParameter('refid')));
1669 } elseif (isGetRequestParameterSet('ref')) {
1670 // Set refid=ref (the referal link uses such variable)
1671 setReferalId(secureString(getRequestParameter('ref')));
1672 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1673 // The variable user comes from click.php
1674 setReferalId(bigintval(getRequestParameter('user')));
1675 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1676 // Set session refid als global
1677 setReferalId(bigintval(getSession('refid')));
1678 } elseif (isRandomReferalIdEnabled()) {
1679 // Select a random user which has confirmed enougth mails
1680 setReferalId(determineRandomReferalId());
1681 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
1682 // Set default refid as refid in URL
1683 setReferalId(getDefRefid());
1685 // No default id when sql_patches is not installed or none set
1689 // Set cookie when default refid > 0
1690 if (!isSessionVariableSet('refid') || (!isValidUserId(getReferalId())) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
1691 // Default is not found
1694 // Do we have nickname or userid set?
1695 if ((isExtensionActive('nickname')) && (isNicknameUsed(getReferalId()))) {
1696 // Nickname in URL, so load the id
1697 $found = fetchUserData(getReferalId(), 'nickname');
1699 // If we found it, use the userid as referal id
1700 if ($found === true) {
1701 // Set the userid as 'refid'
1702 setReferalId(getUserData('userid'));
1704 } elseif (isValidUserId(getReferalId())) {
1705 // Direct userid entered
1706 $found = fetchUserData(getReferalId());
1709 // Is the record valid?
1710 if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
1711 // No, then reset referal id
1712 setReferalId(getDefRefid());
1716 setSession('refid', getReferalId());
1717 } elseif (!isReferalIdValid()) {
1719 setSession('refid', 0);
1722 // Return determined refid
1723 return getReferalId();
1726 // Enables the reset mode and runs it
1727 function doReset () {
1728 // Enable the reset mode
1729 $GLOBALS['reset_enabled'] = true;
1732 runFilterChain('reset');
1735 // Enables the reset mode (hourly, weekly and monthly) and runs it
1736 function doHourly () {
1737 // Enable the hourly reset mode
1738 $GLOBALS['hourly_enabled'] = true;
1740 // Run filters (one always!)
1741 runFilterChain('hourly');
1744 // Our shutdown-function
1745 function shutdown () {
1746 // Call the filter chain 'shutdown'
1747 runFilterChain('shutdown', null);
1749 // Check if not in installation phase and the link is up
1750 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1752 SQL_CLOSE(__FUNCTION__, __LINE__);
1753 } elseif (!isInstallationPhase()) {
1755 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
1758 // Stop executing here
1763 function initMemberId () {
1764 $GLOBALS['member_id'] = '0';
1767 // Setter for member id
1768 function setMemberId ($memberid) {
1769 // We should not set member id to zero
1770 if ($memberid == '0') {
1771 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1775 $GLOBALS['member_id'] = bigintval($memberid);
1778 // Getter for member id or returns zero
1779 function getMemberId () {
1780 // Default member id
1783 // Is the member id set?
1784 if (isMemberIdSet()) {
1786 $memberid = $GLOBALS['member_id'];
1793 // Checks ether the member id is set
1794 function isMemberIdSet () {
1795 return (isset($GLOBALS['member_id']));
1798 // Setter for extra title
1799 function setExtraTitle ($extraTitle) {
1800 $GLOBALS['extra_title'] = $extraTitle;
1803 // Getter for extra title
1804 function getExtraTitle () {
1805 // Is the extra title set?
1806 if (!isExtraTitleSet()) {
1807 // No, then abort here
1808 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1812 return $GLOBALS['extra_title'];
1815 // Checks if the extra title is set
1816 function isExtraTitleSet () {
1817 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1820 // Reads a directory recursively by default and searches for files not matching
1821 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
1822 // a whole directory.
1823 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
1824 // Add default entries we should exclude
1825 $excludeArray[] = '.';
1826 $excludeArray[] = '..';
1827 $excludeArray[] = '.svn';
1828 $excludeArray[] = '.htaccess';
1830 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1835 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1838 while ($baseFile = readdir($dirPointer)) {
1839 // Exclude '.', '..' and entries in $excludeArray automatically
1840 if (in_array($baseFile, $excludeArray, true)) {
1842 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1846 // Construct include filename and FQFN
1847 $fileName = $baseDir . $baseFile;
1848 $FQFN = getPath() . $fileName;
1850 // Remove double slashes
1851 $FQFN = str_replace('//', '/', $FQFN);
1853 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1854 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1855 // These Lines are only for debugging!!
1856 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
1857 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
1858 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
1864 // Skip also files with non-matching prefix genericly
1865 if (($recursive === true) && (isDirectory($FQFN))) {
1866 // Is a redirectory so read it as well
1867 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1869 // And skip further processing
1871 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1873 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1875 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1876 // Skip wrong suffix as well
1877 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1879 } elseif (!isFileReadable($FQFN)) {
1880 // Not readable so skip it
1881 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1885 // Get file' extension (last 4 chars)
1886 $fileExtension = substr($baseFile, -4, 4);
1888 // Is the file a PHP script or other?
1889 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1890 if (($fileExtension == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
1891 // Is this a valid include file?
1892 if ($extension == '.php') {
1893 // Remove both for extension name
1894 $extName = substr($baseFile, strlen($prefix), -4);
1896 // Add file with or without base path
1897 if ($addBaseDir === true) {
1899 $files[] = $fileName;
1902 $files[] = $baseFile;
1905 // We found .php file but should not search for them, why?
1906 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1908 } elseif ($fileExtension == $extension) {
1909 // Other, generic file found
1910 $files[] = $fileName;
1915 closedir($dirPointer);
1920 // Return array with include files
1921 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1925 // Checks wether $prefix is found in $fileName
1926 function isFilePrefixFound ($fileName, $prefix) {
1927 // @TODO Find a way to cache this
1928 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1931 // Maps a module name into a database table name
1932 function mapModuleToTable ($moduleName) {
1933 // Map only these, still lame code...
1934 switch ($moduleName) {
1935 // 'index' is the guest's menu
1936 case 'index': $moduleName = 'guest'; break;
1937 // ... and 'login' the member's menu
1938 case 'login': $moduleName = 'member'; break;
1939 // Anything else will not be mapped, silently.
1946 // Add SQL debug data to array for later output
1947 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1948 // Do we have cache?
1949 if (!isset($GLOBALS['debug_sql_available'])) {
1950 // Check it and cache it in $GLOBALS
1951 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1954 // Don't execute anything here if we don't need or ext-other is missing
1955 if ($GLOBALS['debug_sql_available'] === false) {
1959 // Already executed?
1960 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1961 // Then abort here, we don't need to profile a query twice
1965 // Remeber this as profiled (or not, but we don't care here)
1966 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
1970 'num_rows' => SQL_NUMROWS($result),
1971 'affected' => SQL_AFFECTEDROWS(),
1972 'sql_str' => $sqlString,
1973 'timing' => $timing,
1974 'file' => basename($F),
1979 $GLOBALS['debug_sqls'][] = $record;
1982 // Initializes the cache instance
1983 function initCacheInstance () {
1984 // Check for double-initialization
1985 if (isset($GLOBALS['cache_instance'])) {
1986 // This should not happen and must be fixed
1987 debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1990 // Load include for CacheSystem class
1991 loadIncludeOnce('inc/classes/cachesystem.class.php');
1993 // Initialize cache system only when it's needed
1994 $GLOBALS['cache_instance'] = new CacheSystem();
1997 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1998 // Failed to initialize cache sustem
1999 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
2003 // Getter for message from array or raw message
2004 function getMessageFromIndexedArray ($message, $pos, $array) {
2005 // Check if the requested message was found in array
2006 if (isset($array[$pos])) {
2007 // ... if yes then use it!
2008 $ret = $array[$pos];
2010 // ... else use default message
2018 // Convert ';' to ', ' for e.g. receiver list
2019 function convertReceivers ($old) {
2020 return str_replace(';', ', ', $old);
2023 // Get a module from filename and access level
2024 function getModuleFromFileName ($file, $accessLevel) {
2025 // Default is 'invalid';
2026 $modCheck = 'invalid';
2028 // @TODO This is still very static, rewrite it somehow
2029 switch ($accessLevel) {
2031 $modCheck = 'admin';
2037 $modCheck = getModule();
2040 default: // Unsupported file name / access level
2041 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2049 // Encodes an URL for adding session id, etc.
2050 function encodeUrl ($url, $outputMode = '0') {
2051 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2052 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) {
2053 // Raw output mode detected or session_name() found in URL
2057 // Do we have a valid session?
2058 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2060 // Determine right seperator
2061 $seperator = '&';
2062 if (strpos($url, '?') === false) {
2065 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2066 // Non-HTML mode (or forced non-HTML mode
2071 if (session_id() != '') {
2072 $url .= $seperator . session_name() . '=' . session_id();
2077 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2079 $url = '{?URL?}/' . $url;
2086 // Simple check for spider
2087 function isSpider () {
2088 // Get the UA and trim it down
2089 $userAgent = trim(strtolower(detectUserAgent(true)));
2091 // It should not be empty, if so it is better a spider/bot
2092 if (empty($userAgent)) {
2093 // It is a spider/bot
2098 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2101 // Function to search for the last modified file
2102 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2104 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2105 // Does it match what we are looking for? (We skip a lot files already!)
2106 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2107 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2109 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2110 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2112 // Walk through all entries
2113 foreach ($ds as $d) {
2114 // Generate proper FQFN
2115 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2117 // Is it a file and readable?
2118 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2119 if (isFileReadable($FQFN)) {
2120 // $FQFN is a readable file so extract the requested data from it
2121 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2122 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2124 // Is the file more recent?
2125 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2126 // This file is newer as the file before
2127 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2128 $last_changed['path_name'] = $FQFN;
2129 $last_changed[$lookFor] = $check;
2133 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2138 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2139 function handleFieldWithBraces ($field) {
2140 // Are there braces [] at the end?
2141 if (substr($field, -2, 2) == '[]') {
2142 // Try to find one and replace it. I do it this way to allow easy
2143 // extending of this code.
2144 foreach (array('admin_list_builder_id_value') as $key) {
2145 // Is the cache entry set?
2146 if (isset($GLOBALS[$key])) {
2148 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2160 // Converts a userid so it can be used in SQL queries
2161 function makeDatabaseUserId ($userid) {
2162 // Is it a valid username?
2163 if (isValidUserId($userid)) {
2165 $userid = bigintval($userid);
2167 // Is not valid or zero
2175 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2176 // Note: This function is cached
2177 function capitalizeUnderscoreString ($str) {
2178 // Do we have cache?
2179 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2180 // Init target string
2183 // Explode it with the underscore, but rewrite dashes to underscore before
2184 $strArray = explode('_', str_replace('-', '_', $str));
2186 // "Walk" through all elements and make them lower-case but first upper-case
2187 foreach ($strArray as $part) {
2188 // Capitalize the string part
2189 $capitalized .= firstCharUpperCase($part);
2192 // Store the converted string in cache array
2193 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2197 return $GLOBALS[__FUNCTION__][$str];
2200 // Generate admin links for mail order
2201 // mailType can be: 'mid' or 'bid'
2202 function generateAdminMailLinks ($mailType, $mailId) {
2207 // Default column for mail status is 'data_type'
2208 // @TODO Rename column data_type to e.g. mail_status
2209 $statusColumn = 'data_type';
2211 // Which mail do we have?
2212 switch ($mailType) {
2213 case 'bid': // Bonus mail
2217 case 'mid': // Member mail
2221 default: // Handle unsupported types
2222 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2223 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2227 // Is the mail type supported?
2228 if (!empty($table)) {
2229 // Query for the mail
2230 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2231 array($statusColumn, $table, bigintval($mailId)), __FILE__, __LINE__);
2233 // Do we have one entry there?
2234 if (SQL_NUMROWS($result) == 1) {
2236 $content = SQL_FETCHARRAY($result);
2237 die('Unfinished area:<br />'.__FUNCTION__.':<br />content=<pre>'.print_r($content, true).'</pre>');
2241 SQL_FREERESULT($result);
2244 // Return generated HTML code
2250 * determine if a string can represent a number in hexadecimal
2252 * @param $hex A string to check if it is hex-encoded
2253 * @return $foo True if the string is a hex, otherwise false
2254 * @author Marques Johansson
2255 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2257 function isHexadecimal ($hex) {
2258 // Make it lowercase
2259 $hex = strtolower(trim(ltrim($hex, '0')));
2261 // Fix empty strings to zero
2266 // Simply compare decode->encode result with original
2267 return ($hex == dechex(hexdec($hex)));
2270 // Replace "\r" with "[r]" and "\n" with "[n]" and add a final new-line to make
2271 // them visible to the developer. Use this function to debug e.g. buggy HTTP
2272 // response handler functions.
2273 function replaceReturnNewLine ($str) {
2274 return str_replace("\r", '[r]', str_replace("\n", '[n]
2278 // Converts a given string by splitting it up with given delimiter similar to
2279 // explode(), but appending the delimiter again
2280 function stringToArray ($delimiter, $string) {
2282 $strArray = array();
2284 // "Walk" through all entries
2285 foreach (explode($delimiter, $string) as $split) {
2286 // Append the delimiter and add it to the array
2287 $strArray[] = $split . $delimiter;
2294 // Detects the prefix 'mb_' if a multi-byte string is given
2295 function detectMultiBytePrefix ($str) {
2296 // Default is without multi-byte
2299 // Detect multi-byte (strictly)
2300 if (mb_detect_encoding($str, 'auto', true) !== false) {
2301 // With multi-byte encoded string
2305 // Return the prefix
2309 // Searches the given array for a sub-string match and returns all found keys in an array
2310 function getArrayKeysFromSubStrArray ($heystack, array $needles, $offset = 0) {
2311 // Init array for all found keys
2314 // Now check all entries
2315 foreach ($needles as $key => $needle) {
2316 // Do we have found a partial string?
2317 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2318 if (strpos($heystack, $needle, $offset) !== false) {
2319 // Add the found key
2328 // Determines database column name from given subject and locked
2329 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2330 // Default is 'normal' points
2331 $pointsColumn = 'points';
2333 // Which points, locked or normal?
2334 if ($locked === true) {
2335 $pointsColumn = 'locked_points';
2338 // Prepare array for filter
2339 $filterData = array(
2340 'subject' => $subject,
2341 'locked' => $locked,
2342 'column' => $pointsColumn
2346 $filterData = runFilterChain('determine_points_column_name', $filterData);
2348 // Extract column name from array
2349 $pointsColumn = $filterData['column'];
2352 return $pointsColumn;
2355 // Setter for referal id (no bigintval, or nicknames will fail!)
2356 function setReferalId ($refid) {
2357 $GLOBALS['refid'] = $refid;
2360 // Checks if 'refid' is valid
2361 function isReferalIdValid () {
2362 return ((isset($GLOBALS['refid'])) && (getReferalId() !== NULL) && (getReferalId() > 0));
2365 // Getter for referal id
2366 function getReferalId () {
2367 return $GLOBALS['refid'];
2370 //-----------------------------------------------------------------------------
2371 // Automatically re-created functions, all taken from user comments on www.php.net
2372 //-----------------------------------------------------------------------------
2373 if (!function_exists('html_entity_decode')) {
2374 // Taken from documentation on www.php.net
2375 function html_entity_decode ($string) {
2376 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2377 $trans_tbl = array_flip($trans_tbl);
2378 return strtr($string, $trans_tbl);