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') {
245 // Auto-fix invalid length of zero
246 if ($length == '0') $length = getPassLen();
248 // Initialize array with all allowed chars
249 $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,-,+,_,/,.');
251 // Start creating password
253 for ($i = '0'; $i < $length; $i++) {
254 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
257 // When the size is below 40 we can also add additional security by scrambling
258 // it. Otherwise we may corrupt hashes
259 if (strlen($PASS) <= 40) {
260 // Also scramble the password
261 $PASS = scrambleString($PASS);
264 // Return the password
268 // Generates a human-readable timestamp from the Uni* stamp
269 function generateDateTime ($time, $mode = '0') {
270 // If the stamp is zero it mostly didn't "happen"
273 return '{--NEVER_HAPPENED--}';
276 // Filter out numbers
277 $time = bigintval($time);
280 if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
282 return $GLOBALS[__FUNCTION__][$time][$mode];
286 switch (getLanguage()) {
287 case 'de': // German date / time format
289 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
290 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
291 case '2': $ret = date('d.m.Y|H:i', $time); break;
292 case '3': $ret = date('d.m.Y', $time); break;
293 case '4': $ret = date('d.m.Y|H:i:s', $time); break;
294 case '5': $ret = date('d-m-Y (l-F-T)', $time); break;
295 case '6': $ret = date('Ymd', $time); break;
297 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
302 default: // Default is the US date / time format!
304 case '0': $ret = date('r', $time); break;
305 case '1': $ret = strtolower(date('Y-m-d - g:i A', $time)); break;
306 case '2': $ret = date('y-m-d|H:i', $time); break;
307 case '3': $ret = date('y-m-d', $time); break;
308 case '4': $ret = date('d.m.Y|H:i:s', $time); break;
309 case '5': $ret = date('d-m-Y (l-F-T)', $time); break;
310 case '6': $ret = date('Ymd', $time); break;
312 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
318 $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
324 // Translates Y/N to yes/no
325 function translateYesNo ($yn) {
327 if (!isset($GLOBALS[__FUNCTION__][$yn])) {
329 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
331 case 'Y': $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; break;
332 case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break;
335 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
341 return $GLOBALS[__FUNCTION__][$yn];
344 // Translates the american decimal dot into a german comma
345 function translateComma ($dotted, $cut = true, $max = '0') {
346 // First, cast all to double, due to PHP changes
347 $dotted = (double) $dotted;
349 // Default is 3 you can change this in admin area "Misc -> Misc Options"
350 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
352 // Use from config is default
353 $maxComma = getConfig('max_comma');
355 // Use from parameter?
356 if ($max > 0) $maxComma = $max;
359 if (($cut === true) && ($max == '0')) {
360 // Test for commata if in cut-mode
361 $com = explode('.', $dotted);
362 if (count($com) < 2) {
363 // Don't display commatas even if there are none... ;-)
371 $translated = $dotted;
372 switch (getLanguage()) {
373 case 'de': // German language
374 $translated = number_format($dotted, $maxComma, ',', '.');
377 default: // All others
378 $translated = number_format($dotted, $maxComma, '.', ',');
382 // Return translated value
383 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
387 // Translate Uni*-like gender to human-readable
388 function translateGender ($gender) {
390 $ret = '!' . $gender . '!';
392 // Male/female or company?
397 $ret = sprintf("{--GENDER_%s--}", $gender);
401 // Please report bugs on unknown genders
402 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
406 // Return translated gender
410 // "Translates" the user status
411 function translateUserStatus ($status) {
412 // Default status is unknown if something goes through
413 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
415 // Generate message depending on status
420 $ret = sprintf("{--ACCOUNT_STATUS_%s--}", $status);
425 $ret = '{--ACCOUNT_STATUS_DELETED--}';
429 // Please report all unknown status
430 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
438 // "Translates" 'visible' and 'locked' to a CSS class
439 function translateMenuVisibleLocked ($content, $prefix = '') {
440 // Default is 'menu_unknown'
441 $content['visible_css'] = $prefix . 'menu_unknown';
443 // Translate 'visible' and keep an eye on the prefix
444 switch ($content['visible']) {
446 case 'Y': $content['visible_css'] = $prefix . 'menu_visible' ; break;
447 case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break;
449 // Please report this
450 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, true) . '</pre>');
454 // Translate 'locked' and keep an eye on the prefix
455 switch ($content['locked']) {
457 case 'Y': $content['locked_css'] = $prefix . 'menu_locked' ; break;
458 case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break;
460 // Please report this
461 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, true) . '</pre>');
465 // Return the resulting array
469 // Generates an URL for the dereferer
470 function generateDerefererUrl ($URL) {
471 // Don't de-refer our own links!
472 if (substr($URL, 0, strlen(getUrl())) != getUrl()) {
473 // De-refer this link
474 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
481 // Generates an URL for the frametester
482 function generateFrametesterUrl ($URL) {
483 // Prepare frametester URL
484 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
485 encodeString(compileUriCode($URL))
488 // Return the new URL
489 return $frametesterUrl;
492 // Count entries from e.g. a selection box
493 function countSelection ($array) {
495 if (!is_array($array)) {
497 debug_report_bug(__FUNCTION__, __LINE__, 'No array provided.');
504 foreach ($array as $key => $selected) {
506 if (!empty($selected)) $ret++;
509 // Return counted selections
513 // Generates a timestamp (some wrapper for mktime())
514 function makeTime ($hours, $minutes, $seconds, $stamp) {
515 // Extract day, month and year from given timestamp
516 $days = getDay($stamp);
517 $months = getMonth($stamp);
518 $years = getYear($stamp);
520 // Create timestamp for wished time which depends on extracted date
531 // Redirects to an URL and if neccessarry extends it with own base URL
532 function redirectToUrl ($URL, $allowSpider = true) {
534 if (substr($URL, 0, 6) == '{%url=') $URL = substr($URL, 6, -2);
537 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
539 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
540 $rel = ' rel="external"';
542 // Do we have internal or external URL?
543 if (substr($URL, 0, strlen(getUrl())) == getUrl()) {
544 // Own (=internal) URL
548 // Three different ways to debug...
549 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'URL=' . $URL);
550 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
551 //* DEBUG: */ die($URL);
553 // Simple probe for bots/spiders from search engines
554 if ((isSpider()) && ($allowSpider === true)) {
556 setHttpStatus('200 OK');
558 // Set content-type here to fix a missing array element
559 setContentType('text/html');
561 // Output new location link as anchor
562 outputHtml('<a href="' . $URL . '"' . $rel . '>' . secureString($URL) . '</a>');
563 } elseif (!headers_sent()) {
564 // Clear output buffer
567 // Clear own output buffer
568 $GLOBALS['output'] = '';
570 // Load URL when headers are not sent
571 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $URL), false));
573 // Output error message
574 loadInclude('inc/header.php');
575 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
576 loadInclude('inc/footer.php');
579 // Shut the mailer down here
583 /************************************************************************
585 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
586 * $a_sort sortiert: *
588 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
589 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
590 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
591 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
592 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
594 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
595 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
596 * Sie, dass es doch nicht so schwer ist! :-) *
598 ************************************************************************/
599 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
601 while ($primary_key < count($a_sort)) {
602 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
603 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
605 if ($nums === false) {
606 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
607 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
608 } elseif ($key != $key2) {
609 // Sort numbers (E.g.: 9 < 10)
610 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
611 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
615 // We have found two different values, so let's sort whole array
616 foreach ($dummy as $sort_key => $sort_val) {
617 $t = $dummy[$sort_key][$key];
618 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
619 $dummy[$sort_key][$key2] = $t;
630 // Write back sorted array
636 // Deprecated : $length (still has one reference in this function)
637 // Optional : $extraData
639 function generateRandomCode ($length, $code, $userid, $extraData = '') {
640 // Build server string
641 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
644 $keys = getSiteKey() . getEncryptSeperator() . getDateKey();
645 if (isConfigEntrySet('secret_key')) {
646 $keys .= getEncryptSeperator().getSecretKey();
648 if (isConfigEntrySet('file_hash')) {
649 $keys .= getEncryptSeperator().getFileHash();
651 $keys .= getEncryptSeperator() . getDateFromPatchTime();
652 if (isConfigEntrySet('master_salt')) {
653 $keys .= getEncryptSeperator().getMasterSalt();
656 // Build string from misc data
657 $data = $code . getEncryptSeperator() . $userid . getEncryptSeperator() . $extraData;
659 // Add more additional data
660 if (isSessionVariableSet('u_hash')) {
661 $data .= getEncryptSeperator() . getSession('u_hash');
664 // Add referal id, language, theme and userid
665 $data .= getEncryptSeperator() . determineReferalId();
666 $data .= getEncryptSeperator() . getLanguage();
667 $data .= getEncryptSeperator() . getCurrentTheme();
668 $data .= getEncryptSeperator() . getMemberId();
670 // Calculate number for generating the code
671 $a = $code + getConfig('_ADD') - 1;
673 if (isConfigEntrySet('master_salt')) {
674 // Generate hash with master salt from modula of number with the prime number and other data
675 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a, getMasterSalt());
677 // Create number from hash
678 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
680 // Generate hash with "hash of site key" from modula of number with the prime number and other data
681 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
683 // Create number from hash
684 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
687 // At least 10 numbers shall be secure enought!
688 $len = getCodeLength();
696 // Cut off requested counts of number
697 $return = substr(str_replace('.', '', $rcode), 0, $len);
699 // Done building code
703 // Does only allow numbers
704 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
705 // Filter all numbers out
706 $ret = preg_replace('/[^0123456789]/', '', $num);
709 if ($castValue === true) {
710 // Cast to biggest numeric type
711 $ret = (double) $ret;
714 // Has the whole value changed?
715 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true) && (!is_null($num))) {
717 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
724 // Creates a Uni* timestamp from given selection data and prefix
725 function createTimestampFromSelections ($prefix, $postData) {
726 // Initial return value
729 // Do we have a leap year?
731 $TEST = getYear() / 4;
734 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
735 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getOneDay();
737 // First add years...
738 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
741 $ret += $postData[$prefix . '_mo'] * 2628000;
744 $ret += $postData[$prefix . '_we'] * 604800;
747 $ret += $postData[$prefix . '_da'] * 86400;
750 $ret += $postData[$prefix . '_ho'] * 3600;
753 $ret += $postData[$prefix . '_mi'] * 60;
755 // And at last seconds...
756 $ret += $postData[$prefix . '_se'];
758 // Return calculated value
762 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
763 function createFancyTime ($stamp) {
764 // Get data array with years/months/weeks/days/...
765 $data = createTimeSelections($stamp, '', '', '', true);
767 foreach ($data as $k => $v) {
769 // Value is greater than 0 "eval" data to return string
770 $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
775 // Do we have something there?
776 if (strlen($ret) > 0) {
777 // Remove leading commata and space
778 $ret = substr($ret, 2);
781 $ret = '0 {--_SECONDS--}';
784 // Return fancy time string
788 // Extract host from script name
789 function extractHostnameFromUrl (&$script) {
790 // Use default SERVER_URL by default... ;) So?
791 $url = getServerUrl();
793 // Is this URL valid?
794 if (substr($script, 0, 7) == 'http://') {
795 // Use the hostname from script URL as new hostname
796 $url = substr($script, 7);
797 $extract = explode('/', $url);
799 // Done extracting the URL :)
803 $host = str_replace('http://', '', $url);
804 if (isInString('/', $host)) {
805 $host = substr($host, 0, strpos($host, '/'));
808 // Generate relative URL
809 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
810 if (substr(strtolower($script), 0, 7) == 'http://') {
811 // But only if http:// is in front!
812 $script = substr($script, (strlen($url) + 7));
813 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
815 $script = substr($script, (strlen($url) + 8));
818 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
819 if (substr($script, 0, 1) == '/') {
820 $script = substr($script, 1);
827 // Taken from www.php.net isInStringIgnoreCase() user comments
828 function isEmailValid ($email) {
829 // Check first part of email address
830 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
833 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
836 $regex = '@^' . $first . '\@' . $domain . '$@iU';
838 // Return check result
839 return preg_match($regex, $email);
842 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
843 function isUrlValid ($URL, $compile=true) {
845 $URL = trim(urldecode($URL));
846 //* DEBUG: */ debugOutput($URL);
848 // Compile some chars out...
849 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
850 //* DEBUG: */ debugOutput($URL);
852 // Check for the extension filter
853 if (isExtensionActive('filter')) {
854 // Use the extension's filter set
855 return FILTER_VALIDATE_URL($URL, false);
858 // If not installed, perform a simple test. Just make it sure there is always a http:// or
859 // https:// in front of the URLs
860 return isUrlValidSimple($URL);
863 // Generate a hash for extra-security for all passwords
864 function generateHash ($plainText, $salt = '', $hash = true) {
866 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
868 // Is the required extension 'sql_patches' there and a salt is not given?
869 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
870 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
871 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
872 if ($hash === true) {
874 return md5($plainText);
881 // Do we miss an arry element here?
882 if (!isConfigEntrySet('file_hash')) {
884 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
887 // When the salt is empty build a new one, else use the first x configured characters as the salt
889 // Build server string for more entropy
890 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
893 $keys = getSiteKey() . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
896 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
898 // Calculate number for generating the code
899 $a = time() + getConfig('_ADD') - 1;
901 // Generate SHA1 sum from modula of number and the prime number
902 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a);
903 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
904 $sha1 = scrambleString($sha1);
905 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
906 //* DEBUG: */ $sha1b = descrambleString($sha1);
907 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
909 // Generate the password salt string
910 $salt = substr($sha1, 0, getSaltLength());
911 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
914 //* DEBUG: */ debugOutput('salt=' . $salt);
915 $salt = substr($salt, 0, getSaltLength());
916 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
918 // Sanity check on salt
919 if (strlen($salt) != getSaltLength()) {
921 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
925 // Generate final hash (for debug output)
926 $finalHash = $salt . sha1($salt . $plainText);
929 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
936 function scrambleString ($str) {
940 // Final check, in case of failture it will return unscrambled string
941 if (strlen($str) > 40) {
942 // The string is to long
944 } elseif (strlen($str) == 40) {
946 $scrambleNums = explode(':', getPassScramble());
948 // Generate new numbers
949 $scrambleNums = explode(':', genScrambleString(strlen($str)));
952 // Compare both lengths and abort if different
953 if (strlen($str) != count($scrambleNums)) return $str;
955 // Scramble string here
956 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
957 for ($idx = 0; $idx < strlen($str); $idx++) {
958 // Get char on scrambled position
959 $char = substr($str, $scrambleNums[$idx], 1);
961 // Add it to final output string
965 // Return scrambled string
966 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
970 // De-scramble a string scrambled by scrambleString()
971 function descrambleString ($str) {
972 // Scramble only 40 chars long strings
973 if (strlen($str) != 40) return $str;
975 // Load numbers from config
976 $scrambleNums = explode(':', getPassScramble());
979 if (count($scrambleNums) != 40) return $str;
981 // Begin descrambling
982 $orig = str_repeat(' ', 40);
983 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
984 for ($idx = 0; $idx < 40; $idx++) {
985 $char = substr($str, $idx, 1);
986 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
989 // Return scrambled string
990 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
994 // Generated a "string" for scrambling
995 function genScrambleString ($len) {
996 // Prepare array for the numbers
997 $scrambleNumbers = array();
999 // First we need to setup randomized numbers from 0 to 31
1000 for ($idx = 0; $idx < $len; $idx++) {
1002 $rand = mt_rand(0, ($len - 1));
1004 // Check for it by creating more numbers
1005 while (array_key_exists($rand, $scrambleNumbers)) {
1006 $rand = mt_rand(0, ($len - 1));
1010 $scrambleNumbers[$rand] = $rand;
1013 // So let's create the string for storing it in database
1014 $scrambleString = implode(':', $scrambleNumbers);
1015 return $scrambleString;
1018 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1019 function encodeHashForCookie ($passHash) {
1020 // Return vanilla password hash
1023 // Is a secret key and master salt already initialized?
1024 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1025 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1026 // Only calculate when the secret key is generated
1027 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1028 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1029 // Both keys must have same length so return unencrypted
1030 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1034 $newHash = ''; $start = 9;
1035 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1036 for ($idx = 0; $idx < 20; $idx++) {
1037 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1038 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1039 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1040 $mod = dechex($idx);
1041 if ($part1 > $part2) {
1042 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1043 } elseif ($part2 > $part1) {
1044 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1046 $mod = substr($mod, 0, 2);
1047 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1048 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1049 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1054 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1055 $ret = generateHash($newHash, getMasterSalt());
1059 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1063 // Fix "deleted" cookies
1064 function fixDeletedCookies ($cookies) {
1065 // Is this an array with entries?
1066 if ((is_array($cookies)) && (count($cookies) > 0)) {
1067 // Then check all cookies if they are marked as deleted!
1068 foreach ($cookies as $cookieName) {
1069 // Is the cookie set to "deleted"?
1070 if (getSession($cookieName) == 'deleted') {
1071 setSession($cookieName, '');
1077 // Checks if a given apache module is loaded
1078 function isApacheModuleLoaded ($apacheModule) {
1079 // Check it and return result
1080 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1083 // Get current theme name
1084 function getCurrentTheme () {
1085 // The default theme is 'default'... ;-)
1088 // Do we have ext-theme installed and active?
1089 if (isExtensionActive('theme')) {
1090 // Call inner method
1091 $ret = getActualTheme();
1094 // Return theme value
1098 // Generates an error code from given account status
1099 function generateErrorCodeFromUserStatus ($status = '') {
1100 // If no status is provided, use the default, cached
1101 if ((empty($status)) && (isMember())) {
1103 $status = getUserData('status');
1106 // Default error code if unknown account status
1107 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1109 // Generate constant name
1110 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1112 // Is the constant there?
1113 if (isCodeSet($codeName)) {
1115 $errorCode = getCode($codeName);
1118 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1121 // Return error code
1125 // Back-ported from the new ship-simu engine. :-)
1126 function debug_get_printable_backtrace () {
1128 $backtrace = '<ol>';
1130 // Get and prepare backtrace for output
1131 $backtraceArray = debug_backtrace();
1132 foreach ($backtraceArray as $key => $trace) {
1133 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1134 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1135 if (!isset($trace['args'])) $trace['args'] = array();
1136 $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>';
1140 $backtrace .= '</ol>';
1142 // Return the backtrace
1146 // A mail-able backtrace
1147 function debug_get_mailable_backtrace () {
1151 // Get and prepare backtrace for output
1152 $backtraceArray = debug_backtrace();
1153 foreach ($backtraceArray as $key => $trace) {
1154 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1155 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1156 if (!isset($trace['args'])) $trace['args'] = array();
1157 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1160 // Return the backtrace
1164 // Generates a ***weak*** seed
1165 function generateSeed () {
1166 return microtime(true) * 100000;
1169 // Converts a message code to a human-readable message
1170 function getMessageFromErrorCode ($code) {
1174 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1175 case getCode('LOGOUT_FAILED') : $message = '<span class="notice">{--LOGOUT_FAILED--}</span>'; break;
1176 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1177 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1178 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1179 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1180 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1181 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1182 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1183 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1184 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1185 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1186 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1187 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1188 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1189 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1190 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1191 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1192 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1193 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1194 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1195 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1196 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1197 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1198 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1199 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1200 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1201 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1202 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1203 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1205 case getCode('ERROR_MAILID'):
1206 if (isExtensionActive('mailid', true)) {
1207 $message = '{--ERROR_CONFIRMING_MAIL--}';
1209 $message = generateExtensionInactiveNotInstalledMessage('mailid');
1213 case getCode('EXTENSION_PROBLEM'):
1214 if (isGetRequestParameterSet('ext')) {
1215 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1217 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1221 case getCode('URL_TIME_LOCK'):
1222 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1223 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1224 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1226 // Load timestamp from last order
1227 $content = SQL_FETCHARRAY($result);
1230 SQL_FREERESULT($result);
1232 // Translate it for templates
1233 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1235 // Calculate hours...
1236 $content['hours'] = round(getUrlTlock() / 60 / 60);
1239 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1242 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1244 // Finally contruct the message
1245 $message = loadTemplate('tlock_message', true, $content);
1249 // Missing/invalid code
1250 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1253 logDebugMessage(__FUNCTION__, __LINE__, $message);
1257 // Return the message
1261 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1262 function isUrlValidSimple ($url) {
1264 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1266 // Allows http and https
1267 $http = "(http|https)+(:\/\/)";
1269 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1270 // Test double-domains (e.g. .de.vu)
1271 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1273 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1275 $dir = "((/)+([-_\.[:alnum:]])+)*";
1277 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1278 // ... and the string after and including question character
1279 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1280 // Pattern for URLs like http://url/dir/doc.html?var=value
1281 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1282 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1283 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1284 // Pattern for URLs like http://url/dir/?var=value
1285 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1286 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1287 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1288 // Pattern for URLs like http://url/dir/page.ext
1289 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1290 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1291 $pattern['ipdp'] = $http . $ip . $dir . $page;
1292 // Pattern for URLs like http://url/dir
1293 $pattern['d1d'] = $http . $domain1 . $dir;
1294 $pattern['d2d'] = $http . $domain2 . $dir;
1295 $pattern['ipd'] = $http . $ip . $dir;
1296 // Pattern for URLs like http://url/?var=value
1297 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1298 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1299 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1300 // Pattern for URLs like http://url?var=value
1301 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1302 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1303 $pattern['ipg12'] = $http . $ip . $getstring1;
1305 // Test all patterns
1307 foreach ($pattern as $key => $pat) {
1309 if (isDebugRegularExpressionEnabled()) {
1310 // @TODO Are these convertions still required?
1311 $pat = str_replace('.', '\.', $pat);
1312 $pat = str_replace('@', '\@', $pat);
1313 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1316 // Check if expression matches
1317 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1320 if ($reg === true) break;
1323 // Return true/false
1327 // Wtites data to a config.php-style file
1328 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1329 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1330 // Initialize some variables
1336 // Is the file there and read-/write-able?
1337 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1338 $search = 'CFG: ' . $comment;
1339 $tmp = $FQFN . '.tmp';
1341 // Open the source file
1342 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1344 // Is the resource valid?
1345 if (is_resource($fp)) {
1346 // Open temporary file
1347 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1349 // Is the resource again valid?
1350 if (is_resource($fp_tmp)) {
1351 // Mark temporary file as readable
1352 $GLOBALS['file_readable'][$tmp] = true;
1355 while (!feof($fp)) {
1356 // Read from source file
1357 $line = fgets ($fp, 1024);
1359 if (strpos($line, $search) > -1) {
1365 if ($next === $seek) {
1367 $line = $prefix . $DATA . $suffix . "\n";
1373 // Write to temp file
1374 fwrite($fp_tmp, $line);
1380 // Finished writing tmp file
1384 // Close source file
1387 if (($done === true) && ($found === true)) {
1388 // Copy back tmp file and delete tmp :-)
1389 copyFileVerified($tmp, $FQFN, 0644);
1390 return removeFile($tmp);
1391 } elseif ($found === false) {
1392 outputHtml('<strong>CHANGE:</strong> 404!');
1394 outputHtml('<strong>TMP:</strong> UNDONE!');
1398 // File not found, not readable or writeable
1399 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1402 // An error was detected!
1406 // Send notification to admin
1407 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = '0') {
1408 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1410 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName);
1411 sendAdminsEmails($subject, $templateName, $content, $userid);
1413 // Send out-dated way
1414 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName);
1415 $message = loadEmailTemplate($templateName, $content, $userid);
1416 sendAdminEmails($subject, $message);
1420 // Debug message logger
1421 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1422 // Is debug mode enabled?
1423 if ((isDebugModeEnabled()) || ($force === true)) {
1425 $message = str_replace("\r", '', str_replace("\n", '', $message));
1427 // Log this message away
1428 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1432 // Handle extra values
1433 function handleExtraValues ($filterFunction, $value, $extraValue) {
1434 // Default is the value itself
1437 // Do we have a special filter function?
1438 if (!empty($filterFunction)) {
1439 // Does the filter function exist?
1440 if (function_exists($filterFunction)) {
1441 // Do we have extra parameters here?
1442 if (!empty($extraValue)) {
1443 // Put both parameters in one new array by default
1444 $args = array($value, $extraValue);
1446 // If we have an array simply use it and pre-extend it with our value
1447 if (is_array($extraValue)) {
1448 // Make the new args array
1449 $args = merge_array(array($value), $extraValue);
1452 // Call the multi-parameter call-back
1453 $ret = call_user_func_array($filterFunction, $args);
1455 // One parameter call
1456 $ret = call_user_func($filterFunction, $value);
1465 // Converts timestamp selections into a timestamp
1466 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
1467 // Init test variable
1471 // Get last three chars
1472 $test = substr($id, -3);
1474 // Improved way of checking! :-)
1475 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1476 // Found a multi-selection for timings?
1477 $test = substr($id, 0, -3);
1478 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)) {
1479 // Generate timestamp
1480 $postData[$test] = createTimestampFromSelections($test, $postData);
1481 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1482 $GLOBALS['skip_config'][$test] = true;
1484 // Remove data from array
1485 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1486 unset($postData[$test . '_' . $rem]);
1497 // Reverts the german decimal comma into Computer decimal dot
1498 function convertCommaToDot ($str) {
1499 // Default float is not a float... ;-)
1502 // Which language is selected?
1503 switch (getLanguage()) {
1504 case 'de': // German language
1505 // Remove german thousand dots first
1506 $str = str_replace('.', '', $str);
1508 // Replace german commata with decimal dot and cast it
1509 $float = (float)str_replace(',', '.', $str);
1512 default: // US and so on
1513 // Remove thousand dots first and cast
1514 $float = (float)str_replace(',', '', $str);
1522 // Handle menu-depending failed logins and return the rendered content
1523 function handleLoginFailures ($accessLevel) {
1524 // Default output is empty ;-)
1527 // Is the session data set?
1528 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1529 // Ignore zero values
1530 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1531 // Non-guest has login failures found, get both data and prepare it for template
1532 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1534 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1535 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1539 $OUT = loadTemplate('login_failures', true, $content);
1542 // Reset session data
1543 setSession('mailer_' . $accessLevel . '_failures', '');
1544 setSession('mailer_' . $accessLevel . '_last_failure', '');
1547 // Return rendered content
1552 function rebuildCache ($cache, $inc = '', $force = false) {
1554 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1556 // Shall I remove the cache file?
1557 if (isCacheInstanceValid()) {
1559 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1561 $GLOBALS['cache_instance']->removeCacheFile($force);
1564 // Include file given?
1567 $inc = sprintf("inc/loader/load-%s.php", $inc);
1569 // Is the include there?
1570 if (isIncludeReadable($inc)) {
1571 // And rebuild it from scratch
1572 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1575 // Include not found
1576 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1582 // Determines the real remote address
1583 function determineRealRemoteAddress ($remoteAddr = false) {
1584 // Is a proxy in use?
1585 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1587 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1588 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1589 // Yet, another proxy
1590 $address = $_SERVER['HTTP_CLIENT_IP'];
1592 // The regular address when no proxy was used
1593 $address = $_SERVER['REMOTE_ADDR'];
1596 // This strips out the real address from proxy output
1597 if (strstr($address, ',')) {
1598 $addressArray = explode(',', $address);
1599 $address = $addressArray[0];
1602 // Return the result
1606 // Adds a bonus mail to the queue
1607 // This is a high-level function!
1608 function addNewBonusMail ($data, $mode = '', $output = true) {
1609 // Use mode from data if not set and availble ;-)
1610 if ((empty($mode)) && (isset($data['mode']))) {
1611 $mode = $data['mode'];
1614 // Generate receiver list
1615 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1618 if (!empty($receiver)) {
1619 // Add bonus mail to queue
1620 addBonusMailToQueue(
1632 // Mail inserted into bonus pool
1633 if ($output === true) {
1634 displayMessage('{--ADMIN_BONUS_SEND--}');
1636 } elseif ($output === true) {
1637 // More entered than can be reached!
1638 displayMessage('{--ADMIN_MORE_SELECTED--}');
1641 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1645 // Determines referal id and sets it
1646 function determineReferalId () {
1647 // Skip this in non-html-mode and outside ref.php
1648 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) {
1652 // Check if refid is set
1653 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1655 } elseif (isPostRequestParameterSet('refid')) {
1656 // Get referal id from POST element refid
1657 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1658 } elseif (isGetRequestParameterSet('refid')) {
1659 // Get referal id from GET parameter refid
1660 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1661 } elseif (isGetRequestParameterSet('ref')) {
1662 // Set refid=ref (the referal link uses such variable)
1663 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1664 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1665 // The variable user comes from click.php
1666 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1667 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1668 // Set session refid als global
1669 $GLOBALS['refid'] = bigintval(getSession('refid'));
1670 } elseif (isRandomReferalIdEnabled()) {
1671 // Select a random user which has confirmed enougth mails
1672 $GLOBALS['refid'] = determineRandomReferalId();
1673 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
1674 // Set default refid as refid in URL
1675 $GLOBALS['refid'] = getDefRefid();
1677 // No default id when sql_patches is not installed or none set
1678 $GLOBALS['refid'] = null;
1681 // Set cookie when default refid > 0
1682 if (!isSessionVariableSet('refid') || (isValidUserId($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
1683 // Default is not found
1686 // Do we have nickname or userid set?
1687 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1688 // Nickname in URL, so load the id
1689 $found = fetchUserData($GLOBALS['refid'], 'nickname');
1690 } elseif (isValidUserId($GLOBALS['refid'])) {
1691 // Direct userid entered
1692 $found = fetchUserData($GLOBALS['refid']);
1695 // Is the record valid?
1696 if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
1697 // No, then reset referal id
1698 $GLOBALS['refid'] = getDefRefid();
1702 setSession('refid', $GLOBALS['refid']);
1705 // Return determined refid
1706 return $GLOBALS['refid'];
1709 // Enables the reset mode and runs it
1710 function doReset () {
1711 // Enable the reset mode
1712 $GLOBALS['reset_enabled'] = true;
1715 runFilterChain('reset');
1718 // Enables the reset mode (hourly, weekly and monthly) and runs it
1719 function doHourly () {
1720 // Enable the hourly reset mode
1721 $GLOBALS['hourly_enabled'] = true;
1723 // Run filters (one always!)
1724 runFilterChain('hourly');
1727 // Our shutdown-function
1728 function shutdown () {
1729 // Call the filter chain 'shutdown'
1730 runFilterChain('shutdown', null);
1732 // Check if not in installation phase and the link is up
1733 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1735 SQL_CLOSE(__FUNCTION__, __LINE__);
1736 } elseif (!isInstallationPhase()) {
1738 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
1741 // Stop executing here
1746 function initMemberId () {
1747 $GLOBALS['member_id'] = '0';
1750 // Setter for member id
1751 function setMemberId ($memberid) {
1752 // We should not set member id to zero
1753 if ($memberid == '0') {
1754 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1758 $GLOBALS['member_id'] = bigintval($memberid);
1761 // Getter for member id or returns zero
1762 function getMemberId () {
1763 // Default member id
1766 // Is the member id set?
1767 if (isMemberIdSet()) {
1769 $memberid = $GLOBALS['member_id'];
1776 // Checks ether the member id is set
1777 function isMemberIdSet () {
1778 return (isset($GLOBALS['member_id']));
1781 // Setter for extra title
1782 function setExtraTitle ($extraTitle) {
1783 $GLOBALS['extra_title'] = $extraTitle;
1786 // Getter for extra title
1787 function getExtraTitle () {
1788 // Is the extra title set?
1789 if (!isExtraTitleSet()) {
1790 // No, then abort here
1791 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1795 return $GLOBALS['extra_title'];
1798 // Checks if the extra title is set
1799 function isExtraTitleSet () {
1800 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1803 // Reads a directory recursively by default and searches for files not matching
1804 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
1805 // a whole directory.
1806 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
1807 // Add default entries we should exclude
1808 $excludeArray[] = '.';
1809 $excludeArray[] = '..';
1810 $excludeArray[] = '.svn';
1811 $excludeArray[] = '.htaccess';
1813 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1818 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1821 while ($baseFile = readdir($dirPointer)) {
1822 // Exclude '.', '..' and entries in $excludeArray automatically
1823 if (in_array($baseFile, $excludeArray, true)) {
1825 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1829 // Construct include filename and FQFN
1830 $fileName = $baseDir . $baseFile;
1831 $FQFN = getPath() . $fileName;
1833 // Remove double slashes
1834 $FQFN = str_replace('//', '/', $FQFN);
1836 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1837 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1838 // These Lines are only for debugging!!
1839 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
1840 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
1841 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
1847 // Skip also files with non-matching prefix genericly
1848 if (($recursive === true) && (isDirectory($FQFN))) {
1849 // Is a redirectory so read it as well
1850 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1852 // And skip further processing
1854 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1856 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1858 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1859 // Skip wrong suffix as well
1860 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1862 } elseif (!isFileReadable($FQFN)) {
1863 // Not readable so skip it
1864 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1868 // Get file' extension (last 4 chars)
1869 $fileExtension = substr($baseFile, -4, 4);
1871 // Is the file a PHP script or other?
1872 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1873 if (($fileExtension == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
1874 // Is this a valid include file?
1875 if ($extension == '.php') {
1876 // Remove both for extension name
1877 $extName = substr($baseFile, strlen($prefix), -4);
1879 // Add file with or without base path
1880 if ($addBaseDir === true) {
1882 $files[] = $fileName;
1885 $files[] = $baseFile;
1888 // We found .php file but should not search for them, why?
1889 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1891 } elseif ($fileExtension == $extension) {
1892 // Other, generic file found
1893 $files[] = $fileName;
1898 closedir($dirPointer);
1903 // Return array with include files
1904 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1908 // Checks wether $prefix is found in $fileName
1909 function isFilePrefixFound ($fileName, $prefix) {
1910 // @TODO Find a way to cache this
1911 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1914 // Maps a module name into a database table name
1915 function mapModuleToTable ($moduleName) {
1916 // Map only these, still lame code...
1917 switch ($moduleName) {
1918 // 'index' is the guest's menu
1919 case 'index': $moduleName = 'guest'; break;
1920 // ... and 'login' the member's menu
1921 case 'login': $moduleName = 'member'; break;
1922 // Anything else will not be mapped, silently.
1929 // Add SQL debug data to array for later output
1930 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1931 // Do we have cache?
1932 if (!isset($GLOBALS['debug_sql_available'])) {
1933 // Check it and cache it in $GLOBALS
1934 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1937 // Don't execute anything here if we don't need or ext-other is missing
1938 if ($GLOBALS['debug_sql_available'] === false) {
1942 // Already executed?
1943 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1944 // Then abort here, we don't need to profile a query twice
1948 // Remeber this as profiled (or not, but we don't care here)
1949 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
1953 'num_rows' => SQL_NUMROWS($result),
1954 'affected' => SQL_AFFECTEDROWS(),
1955 'sql_str' => $sqlString,
1956 'timing' => $timing,
1957 'file' => basename($F),
1962 $GLOBALS['debug_sqls'][] = $record;
1965 // Initializes the cache instance
1966 function initCacheInstance () {
1967 // Check for double-initialization
1968 if (isset($GLOBALS['cache_instance'])) {
1969 // This should not happen and must be fixed
1970 debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1973 // Load include for CacheSystem class
1974 loadIncludeOnce('inc/classes/cachesystem.class.php');
1976 // Initialize cache system only when it's needed
1977 $GLOBALS['cache_instance'] = new CacheSystem();
1980 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1981 // Failed to initialize cache sustem
1982 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
1986 // Getter for message from array or raw message
1987 function getMessageFromIndexedArray ($message, $pos, $array) {
1988 // Check if the requested message was found in array
1989 if (isset($array[$pos])) {
1990 // ... if yes then use it!
1991 $ret = $array[$pos];
1993 // ... else use default message
2001 // Convert ';' to ', ' for e.g. receiver list
2002 function convertReceivers ($old) {
2003 return str_replace(';', ', ', $old);
2006 // Get a module from filename and access level
2007 function getModuleFromFileName ($file, $accessLevel) {
2008 // Default is 'invalid';
2009 $modCheck = 'invalid';
2011 // @TODO This is still very static, rewrite it somehow
2012 switch ($accessLevel) {
2014 $modCheck = 'admin';
2020 $modCheck = getModule();
2023 default: // Unsupported file name / access level
2024 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2032 // Encodes an URL for adding session id, etc.
2033 function encodeUrl ($url, $outputMode = '0') {
2034 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2035 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) {
2036 // Raw output mode detected or session_name() found in URL
2040 // Do we have a valid session?
2041 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2043 // Determine right seperator
2044 $seperator = '&';
2045 if (strpos($url, '?') === false) {
2048 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2049 // Non-HTML mode (or forced non-HTML mode
2054 if (session_id() != '') {
2055 $url .= $seperator . session_name() . '=' . session_id();
2060 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2062 $url = '{?URL?}/' . $url;
2069 // Simple check for spider
2070 function isSpider () {
2071 // Get the UA and trim it down
2072 $userAgent = trim(strtolower(detectUserAgent(true)));
2074 // It should not be empty, if so it is better a spider/bot
2075 if (empty($userAgent)) {
2076 // It is a spider/bot
2081 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2084 // Function to search for the last modified file
2085 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2087 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2088 // Does it match what we are looking for? (We skip a lot files already!)
2089 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2090 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2092 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2093 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2095 // Walk through all entries
2096 foreach ($ds as $d) {
2097 // Generate proper FQFN
2098 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2100 // Is it a file and readable?
2101 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2102 if (isFileReadable($FQFN)) {
2103 // $FQFN is a readable file so extract the requested data from it
2104 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2105 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2107 // Is the file more recent?
2108 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2109 // This file is newer as the file before
2110 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2111 $last_changed['path_name'] = $FQFN;
2112 $last_changed[$lookFor] = $check;
2116 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2121 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2122 function handleFieldWithBraces ($field) {
2123 // Are there braces [] at the end?
2124 if (substr($field, -2, 2) == '[]') {
2125 // Try to find one and replace it. I do it this way to allow easy
2126 // extending of this code.
2127 foreach (array('admin_list_builder_id_value') as $key) {
2128 // Is the cache entry set?
2129 if (isset($GLOBALS[$key])) {
2131 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2143 // Converts a userid so it can be used in SQL queries
2144 function makeDatabaseUserId ($userid) {
2145 // Is it a valid username?
2146 if (isValidUserId($userid)) {
2148 $userid = bigintval($userid);
2150 // Is not valid or zero
2158 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2159 // Note: This function is cached
2160 function capitalizeUnderscoreString ($str) {
2161 // Do we have cache?
2162 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2163 // Init target string
2166 // Explode it with the underscore, but rewrite dashes to underscore before
2167 $strArray = explode('_', str_replace('-', '_', $str));
2169 // "Walk" through all elements and make them lower-case but first upper-case
2170 foreach ($strArray as $part) {
2171 // Capitalize the string part
2172 $capitalized .= firstCharUpperCase($part);
2175 // Store the converted string in cache array
2176 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2180 return $GLOBALS[__FUNCTION__][$str];
2183 // Generate admin links for mail order
2184 // mailType can be: 'mid' or 'bid'
2185 function generateAdminMailLinks ($mailType, $mailId) {
2190 // Default column for mail status is 'data_type'
2191 // @TODO Rename column data_type to e.g. mail_status
2192 $statusColumn = 'data_type';
2194 // Which mail do we have?
2195 switch ($mailType) {
2196 case 'bid': // Bonus mail
2200 case 'mid': // Member mail
2204 default: // Handle unsupported types
2205 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2206 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2210 // Is the mail type supported?
2211 if (!empty($table)) {
2212 // Query for the mail
2213 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2214 array($statusColumn, $table, bigintval($mailId)), __FILE__, __LINE__);
2216 // Do we have one entry there?
2217 if (SQL_NUMROWS($result) == 1) {
2219 $content = SQL_FETCHARRAY($result);
2220 die('Unfinished area:<br />'.__FUNCTION__.':<br />content=<pre>'.print_r($content, true).'</pre>');
2224 SQL_FREERESULT($result);
2227 // Return generated HTML code
2233 * determine if a string can represent a number in hexadecimal
2235 * @param $hex A string to check if it is hex-encoded
2236 * @return $foo True if the string is a hex, otherwise false
2237 * @author Marques Johansson
2238 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2240 function isHexadecimal ($hex) {
2241 // Make it lowercase
2242 $hex = strtolower(trim(ltrim($hex, '0')));
2244 // Fix empty strings to zero
2249 // Simply compare decode->encode result with original
2250 return ($hex == dechex(hexdec($hex)));
2253 // Replace "\r" with "[r]" and "\n" with "[n]" and add a final new-line to make
2254 // them visible to the developer. Use this function to debug e.g. buggy HTTP
2255 // response handler functions.
2256 function replaceReturnNewLine ($str) {
2257 return str_replace("\r", '[r]', str_replace("\n", '[n]
2261 // Converts a given string by splitting it up with given delimiter similar to
2262 // explode(), but appending the delimiter again
2263 function stringToArray ($delimiter, $string) {
2265 $strArray = array();
2267 // "Walk" through all entries
2268 foreach (explode($delimiter, $string) as $split) {
2269 // Append the delimiter and add it to the array
2270 $strArray[] = $split . $delimiter;
2277 // Detects the prefix 'mb_' if a multi-byte string is given
2278 function detectMultiBytePrefix ($str) {
2279 // Default is without multi-byte
2282 // Detect multi-byte (strictly)
2283 if (mb_detect_encoding($str, 'auto', true) !== false) {
2284 // With multi-byte encoded string
2288 // Return the prefix
2292 // Searches the given array for a sub-string match and returns all found keys in an array
2293 function getArrayKeysFromSubStrArray ($heystack, array $needles, $offset = 0) {
2294 // Init array for all found keys
2297 // Now check all entries
2298 foreach ($needles as $key => $needle) {
2299 // Do we have found a partial string?
2300 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2301 if (strpos($heystack, $needle, $offset) !== false) {
2302 // Add the found key
2311 //-----------------------------------------------------------------------------
2312 // Automatically re-created functions, all taken from user comments on www.php.net
2313 //-----------------------------------------------------------------------------
2314 if (!function_exists('html_entity_decode')) {
2315 // Taken from documentation on www.php.net
2316 function html_entity_decode ($string) {
2317 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2318 $trans_tbl = array_flip($trans_tbl);
2319 return strtr($string, $trans_tbl);