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 "Settings -> Misc Options"
350 if (!isConfigEntrySet('max_comma')) {
351 setConfigEntry('max_comma', 3);
354 // Use from config is default
355 $maxComma = getConfig('max_comma');
357 // Use from parameter?
363 if (($cut === true) && ($max == '0')) {
364 // Test for commata if in cut-mode
365 $com = explode('.', $dotted);
366 if (count($com) < 2) {
367 // Don't display commatas even if there are none... ;-)
375 $translated = $dotted;
376 switch (getLanguage()) {
377 case 'de': // German language
378 $translated = number_format($dotted, $maxComma, ',', '.');
381 default: // All others
382 $translated = number_format($dotted, $maxComma, '.', ',');
386 // Return translated value
387 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
391 // Translate Uni*-like gender to human-readable
392 function translateGender ($gender) {
394 $ret = '!' . $gender . '!';
396 // Male/female or company?
401 $ret = sprintf("{--GENDER_%s--}", $gender);
405 // Please report bugs on unknown genders
406 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
410 // Return translated gender
414 // "Translates" the user status
415 function translateUserStatus ($status) {
416 // Default status is unknown if something goes through
417 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
419 // Generate message depending on status
424 $ret = sprintf("{--ACCOUNT_STATUS_%s--}", $status);
429 $ret = '{--ACCOUNT_STATUS_DELETED--}';
433 // Please report all unknown status
434 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
442 // "Translates" 'visible' and 'locked' to a CSS class
443 function translateMenuVisibleLocked ($content, $prefix = '') {
444 // Default is 'menu_unknown'
445 $content['visible_css'] = $prefix . 'menu_unknown';
447 // Translate 'visible' and keep an eye on the prefix
448 switch ($content['visible']) {
450 case 'Y': $content['visible_css'] = $prefix . 'menu_visible' ; break;
451 case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break;
453 // Please report this
454 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, true) . '</pre>');
458 // Translate 'locked' and keep an eye on the prefix
459 switch ($content['locked']) {
461 case 'Y': $content['locked_css'] = $prefix . 'menu_locked' ; break;
462 case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break;
464 // Please report this
465 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, true) . '</pre>');
469 // Return the resulting array
473 // Generates an URL for the dereferer
474 function generateDerefererUrl ($URL) {
475 // Don't de-refer our own links!
476 if (substr($URL, 0, strlen(getUrl())) != getUrl()) {
477 // De-refer this link
478 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
485 // Generates an URL for the frametester
486 function generateFrametesterUrl ($URL) {
487 // Prepare frametester URL
488 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
489 encodeString(compileUriCode($URL))
492 // Return the new URL
493 return $frametesterUrl;
496 // Count entries from e.g. a selection box
497 function countSelection ($array) {
499 if (!is_array($array)) {
501 debug_report_bug(__FUNCTION__, __LINE__, 'No array provided.');
508 foreach ($array as $key => $selected) {
510 if (!empty($selected)) $ret++;
513 // Return counted selections
517 // Generates a timestamp (some wrapper for mktime())
518 function makeTime ($hours, $minutes, $seconds, $stamp) {
519 // Extract day, month and year from given timestamp
520 $days = getDay($stamp);
521 $months = getMonth($stamp);
522 $years = getYear($stamp);
524 // Create timestamp for wished time which depends on extracted date
535 // Redirects to an URL and if neccessarry extends it with own base URL
536 function redirectToUrl ($URL, $allowSpider = true) {
538 if (substr($URL, 0, 6) == '{%url=') $URL = substr($URL, 6, -2);
541 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
543 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
544 $rel = ' rel="external"';
546 // Do we have internal or external URL?
547 if (substr($URL, 0, strlen(getUrl())) == getUrl()) {
548 // Own (=internal) URL
552 // Three different ways to debug...
553 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'URL=' . $URL);
554 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
555 //* DEBUG: */ die($URL);
557 // We should not sent a redirect if headers are already sent
558 if (!headers_sent()) {
559 // Clear output buffer
562 // Clear own output buffer
563 $GLOBALS['output'] = '';
565 // Load URL when headers are not sent
566 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $URL), false));
568 // Output error message
569 loadInclude('inc/header.php');
570 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
571 loadInclude('inc/footer.php');
574 // Shut the mailer down here
578 /************************************************************************
580 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
581 * $a_sort sortiert: *
583 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
584 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
585 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
586 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
587 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
589 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
590 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
591 * Sie, dass es doch nicht so schwer ist! :-) *
593 ************************************************************************/
594 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
596 while ($primary_key < count($a_sort)) {
597 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
598 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
600 if ($nums === false) {
601 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
602 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
603 } elseif ($key != $key2) {
604 // Sort numbers (E.g.: 9 < 10)
605 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
606 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
610 // We have found two different values, so let's sort whole array
611 foreach ($dummy as $sort_key => $sort_val) {
612 $t = $dummy[$sort_key][$key];
613 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
614 $dummy[$sort_key][$key2] = $t;
625 // Write back sorted array
631 // Deprecated : $length (still has one reference in this function)
632 // Optional : $extraData
634 function generateRandomCode ($length, $code, $userid, $extraData = '') {
635 // Build server string
636 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
639 $keys = getSiteKey() . getEncryptSeperator() . getDateKey();
640 if (isConfigEntrySet('secret_key')) {
641 $keys .= getEncryptSeperator().getSecretKey();
643 if (isConfigEntrySet('file_hash')) {
644 $keys .= getEncryptSeperator().getFileHash();
646 $keys .= getEncryptSeperator() . getDateFromPatchTime();
647 if (isConfigEntrySet('master_salt')) {
648 $keys .= getEncryptSeperator().getMasterSalt();
651 // Build string from misc data
652 $data = $code . getEncryptSeperator() . $userid . getEncryptSeperator() . $extraData;
654 // Add more additional data
655 if (isSessionVariableSet('u_hash')) {
656 $data .= getEncryptSeperator() . getSession('u_hash');
659 // Add referal id, language, theme and userid
660 $data .= getEncryptSeperator() . determineReferalId();
661 $data .= getEncryptSeperator() . getLanguage();
662 $data .= getEncryptSeperator() . getCurrentTheme();
663 $data .= getEncryptSeperator() . getMemberId();
665 // Calculate number for generating the code
666 $a = $code + getConfig('_ADD') - 1;
668 if (isConfigEntrySet('master_salt')) {
669 // Generate hash with master salt from modula of number with the prime number and other data
670 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a, getMasterSalt());
672 // Create number from hash
673 $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
675 // Generate hash with "hash of site key" from modula of number with the prime number and other data
676 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
678 // Create number from hash
679 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
682 // At least 10 numbers shall be secure enought!
683 $len = getCodeLength();
691 // Cut off requested counts of number
692 $return = substr(str_replace('.', '', $rcode), 0, $len);
694 // Done building code
698 // Does only allow numbers
699 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
700 // Filter all numbers out
701 $ret = preg_replace('/[^0123456789]/', '', $num);
704 if ($castValue === true) {
705 // Cast to biggest numeric type
706 $ret = (double) $ret;
709 // Has the whole value changed?
710 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true) && (!is_null($num))) {
712 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
719 // Creates a Uni* timestamp from given selection data and prefix
720 function createEpocheTimeFromSelections ($prefix, $postData) {
721 // Initial return value
724 // Do we have a leap year?
726 $TEST = getYear() / 4;
729 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
730 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) {
731 $SWITCH = getOneDay();
734 // First add years...
735 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
738 $ret += $postData[$prefix . '_mo'] * 2628000;
741 $ret += $postData[$prefix . '_we'] * 604800;
744 $ret += $postData[$prefix . '_da'] * 86400;
747 $ret += $postData[$prefix . '_ho'] * 3600;
750 $ret += $postData[$prefix . '_mi'] * 60;
752 // And at last seconds...
753 $ret += $postData[$prefix . '_se'];
755 // Return calculated value
759 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
760 function createFancyTime ($stamp) {
761 // Get data array with years/months/weeks/days/...
762 $data = createTimeSelections($stamp, '', '', '', true);
764 foreach ($data as $k => $v) {
766 // Value is greater than 0 "eval" data to return string
767 $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}';
772 // Do we have something there?
773 if (strlen($ret) > 0) {
774 // Remove leading commata and space
775 $ret = substr($ret, 2);
778 $ret = '0 {--_SECONDS--}';
781 // Return fancy time string
785 // Extract host from script name
786 function extractHostnameFromUrl (&$script) {
787 // Use default SERVER_URL by default... ;) So?
788 $url = getServerUrl();
790 // Is this URL valid?
791 if (substr($script, 0, 7) == 'http://') {
792 // Use the hostname from script URL as new hostname
793 $url = substr($script, 7);
794 $extract = explode('/', $url);
796 // Done extracting the URL :)
800 $host = str_replace('http://', '', $url);
801 if (isInString('/', $host)) {
802 $host = substr($host, 0, strpos($host, '/'));
805 // Generate relative URL
806 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
807 if (substr(strtolower($script), 0, 7) == 'http://') {
808 // But only if http:// is in front!
809 $script = substr($script, (strlen($url) + 7));
810 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
812 $script = substr($script, (strlen($url) + 8));
815 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
816 if (substr($script, 0, 1) == '/') {
817 $script = substr($script, 1);
824 // Taken from www.php.net isInStringIgnoreCase() user comments
825 function isEmailValid ($email) {
826 // Check first part of email address
827 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
830 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
833 $regex = '@^' . $first . '\@' . $domain . '$@iU';
835 // Return check result
836 return preg_match($regex, $email);
839 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
840 function isUrlValid ($URL, $compile=true) {
842 $URL = trim(urldecode($URL));
843 //* DEBUG: */ debugOutput($URL);
845 // Compile some chars out...
846 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
847 //* DEBUG: */ debugOutput($URL);
849 // Check for the extension filter
850 if (isExtensionActive('filter')) {
851 // Use the extension's filter set
852 return FILTER_VALIDATE_URL($URL, false);
855 // If not installed, perform a simple test. Just make it sure there is always a http:// or
856 // https:// in front of the URLs
857 return isUrlValidSimple($URL);
860 // Generate a hash for extra-security for all passwords
861 function generateHash ($plainText, $salt = '', $hash = true) {
863 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
865 // Is the required extension 'sql_patches' there and a salt is not given?
866 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
867 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
868 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
869 if ($hash === true) {
871 return md5($plainText);
878 // Do we miss an arry element here?
879 if (!isConfigEntrySet('file_hash')) {
881 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
884 // When the salt is empty build a new one, else use the first x configured characters as the salt
886 // Build server string for more entropy
887 $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr();
890 $keys = getSiteKey() . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt();
893 $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time();
895 // Calculate number for generating the code
896 $a = time() + getConfig('_ADD') - 1;
898 // Generate SHA1 sum from modula of number and the prime number
899 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a);
900 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
901 $sha1 = scrambleString($sha1);
902 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
903 //* DEBUG: */ $sha1b = descrambleString($sha1);
904 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
906 // Generate the password salt string
907 $salt = substr($sha1, 0, getSaltLength());
908 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
911 //* DEBUG: */ debugOutput('salt=' . $salt);
912 $salt = substr($salt, 0, getSaltLength());
913 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
915 // Sanity check on salt
916 if (strlen($salt) != getSaltLength()) {
918 debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
922 // Generate final hash (for debug output)
923 $finalHash = $salt . sha1($salt . $plainText);
926 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
933 function scrambleString ($str) {
937 // Final check, in case of failture it will return unscrambled string
938 if (strlen($str) > 40) {
939 // The string is to long
941 } elseif (strlen($str) == 40) {
943 $scrambleNums = explode(':', getPassScramble());
945 // Generate new numbers
946 $scrambleNums = explode(':', genScrambleString(strlen($str)));
949 // Compare both lengths and abort if different
950 if (strlen($str) != count($scrambleNums)) return $str;
952 // Scramble string here
953 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
954 for ($idx = 0; $idx < strlen($str); $idx++) {
955 // Get char on scrambled position
956 $char = substr($str, $scrambleNums[$idx], 1);
958 // Add it to final output string
962 // Return scrambled string
963 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
967 // De-scramble a string scrambled by scrambleString()
968 function descrambleString ($str) {
969 // Scramble only 40 chars long strings
970 if (strlen($str) != 40) return $str;
972 // Load numbers from config
973 $scrambleNums = explode(':', getPassScramble());
976 if (count($scrambleNums) != 40) return $str;
978 // Begin descrambling
979 $orig = str_repeat(' ', 40);
980 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
981 for ($idx = 0; $idx < 40; $idx++) {
982 $char = substr($str, $idx, 1);
983 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
986 // Return scrambled string
987 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
991 // Generated a "string" for scrambling
992 function genScrambleString ($len) {
993 // Prepare array for the numbers
994 $scrambleNumbers = array();
996 // First we need to setup randomized numbers from 0 to 31
997 for ($idx = 0; $idx < $len; $idx++) {
999 $rand = mt_rand(0, ($len - 1));
1001 // Check for it by creating more numbers
1002 while (array_key_exists($rand, $scrambleNumbers)) {
1003 $rand = mt_rand(0, ($len - 1));
1007 $scrambleNumbers[$rand] = $rand;
1010 // So let's create the string for storing it in database
1011 $scrambleString = implode(':', $scrambleNumbers);
1012 return $scrambleString;
1015 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
1016 function encodeHashForCookie ($passHash) {
1017 // Return vanilla password hash
1020 // Is a secret key and master salt already initialized?
1021 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
1022 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
1023 // Only calculate when the secret key is generated
1024 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
1025 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
1026 // Both keys must have same length so return unencrypted
1027 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
1031 $newHash = ''; $start = 9;
1032 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
1033 for ($idx = 0; $idx < 20; $idx++) {
1034 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
1035 $part2 = hexdec(substr(getSecretKey(), $start, 2));
1036 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
1037 $mod = dechex($idx);
1038 if ($part1 > $part2) {
1039 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
1040 } elseif ($part2 > $part1) {
1041 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
1043 $mod = substr($mod, 0, 2);
1044 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
1045 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
1046 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
1051 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
1052 $ret = generateHash($newHash, getMasterSalt());
1056 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
1060 // Fix "deleted" cookies
1061 function fixDeletedCookies ($cookies) {
1062 // Is this an array with entries?
1063 if ((is_array($cookies)) && (count($cookies) > 0)) {
1064 // Then check all cookies if they are marked as deleted!
1065 foreach ($cookies as $cookieName) {
1066 // Is the cookie set to "deleted"?
1067 if (getSession($cookieName) == 'deleted') {
1068 setSession($cookieName, '');
1074 // Checks if a given apache module is loaded
1075 function isApacheModuleLoaded ($apacheModule) {
1076 // Check it and return result
1077 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
1080 // Get current theme name
1081 function getCurrentTheme () {
1082 // The default theme is 'default'... ;-)
1085 // Do we have ext-theme installed and active?
1086 if (isExtensionActive('theme')) {
1087 // Call inner method
1088 $ret = getActualTheme();
1091 // Return theme value
1095 // Generates an error code from given account status
1096 function generateErrorCodeFromUserStatus ($status = '') {
1097 // If no status is provided, use the default, cached
1098 if ((empty($status)) && (isMember())) {
1100 $status = getUserData('status');
1103 // Default error code if unknown account status
1104 $errorCode = getCode('ACCOUNT_STATUS_UNKNOWN');
1106 // Generate constant name
1107 $codeName = sprintf("ACCOUNT_STATUS_%s", strtoupper($status));
1109 // Is the constant there?
1110 if (isCodeSet($codeName)) {
1112 $errorCode = getCode($codeName);
1115 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1118 // Return error code
1122 // Back-ported from the new ship-simu engine. :-)
1123 function debug_get_printable_backtrace () {
1125 $backtrace = '<ol>';
1127 // Get and prepare backtrace for output
1128 $backtraceArray = debug_backtrace();
1129 foreach ($backtraceArray as $key => $trace) {
1130 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1131 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1132 if (!isset($trace['args'])) $trace['args'] = array();
1133 $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>';
1137 $backtrace .= '</ol>';
1139 // Return the backtrace
1143 // A mail-able backtrace
1144 function debug_get_mailable_backtrace () {
1148 // Get and prepare backtrace for output
1149 $backtraceArray = debug_backtrace();
1150 foreach ($backtraceArray as $key => $trace) {
1151 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1152 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1153 if (!isset($trace['args'])) $trace['args'] = array();
1154 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1157 // Return the backtrace
1161 // Generates a ***weak*** seed
1162 function generateSeed () {
1163 return microtime(true) * 100000;
1166 // Converts a message code to a human-readable message
1167 function getMessageFromErrorCode ($code) {
1171 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1172 case getCode('LOGOUT_FAILED') : $message = '<span class="notice">{--LOGOUT_FAILED--}</span>'; break;
1173 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1174 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1175 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1176 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1177 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1178 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1179 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1180 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1181 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1182 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1183 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
1184 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1185 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
1186 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1187 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1188 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1189 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
1190 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1191 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1192 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1193 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1194 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1195 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1196 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1197 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1198 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1199 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1200 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1202 case getCode('ERROR_MAILID'):
1203 if (isExtensionActive('mailid', true)) {
1204 $message = '{--ERROR_CONFIRMING_MAIL--}';
1206 $message = generateExtensionInactiveNotInstalledMessage('mailid');
1210 case getCode('EXTENSION_PROBLEM'):
1211 if (isGetRequestParameterSet('ext')) {
1212 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
1214 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1218 case getCode('URL_TIME_LOCK'):
1219 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1220 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1221 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
1223 // Load timestamp from last order
1224 $content = SQL_FETCHARRAY($result);
1227 SQL_FREERESULT($result);
1229 // Translate it for templates
1230 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1232 // Calculate hours...
1233 $content['hours'] = round(getUrlTlock() / 60 / 60);
1236 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1239 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1241 // Finally contruct the message
1242 $message = loadTemplate('tlock_message', true, $content);
1246 // Missing/invalid code
1247 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
1250 logDebugMessage(__FUNCTION__, __LINE__, $message);
1254 // Return the message
1258 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1259 function isUrlValidSimple ($url) {
1261 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
1263 // Allows http and https
1264 $http = "(http|https)+(:\/\/)";
1266 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1267 // Test double-domains (e.g. .de.vu)
1268 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1270 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1272 $dir = "((/)+([-_\.[:alnum:]])+)*";
1274 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1275 // ... and the string after and including question character
1276 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1277 // Pattern for URLs like http://url/dir/doc.html?var=value
1278 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1279 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1280 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1281 // Pattern for URLs like http://url/dir/?var=value
1282 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1283 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1284 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1285 // Pattern for URLs like http://url/dir/page.ext
1286 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1287 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1288 $pattern['ipdp'] = $http . $ip . $dir . $page;
1289 // Pattern for URLs like http://url/dir
1290 $pattern['d1d'] = $http . $domain1 . $dir;
1291 $pattern['d2d'] = $http . $domain2 . $dir;
1292 $pattern['ipd'] = $http . $ip . $dir;
1293 // Pattern for URLs like http://url/?var=value
1294 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1295 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1296 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1297 // Pattern for URLs like http://url?var=value
1298 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1299 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1300 $pattern['ipg12'] = $http . $ip . $getstring1;
1302 // Test all patterns
1304 foreach ($pattern as $key => $pat) {
1306 if (isDebugRegularExpressionEnabled()) {
1307 // @TODO Are these convertions still required?
1308 $pat = str_replace('.', '\.', $pat);
1309 $pat = str_replace('@', '\@', $pat);
1310 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1313 // Check if expression matches
1314 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1317 if ($reg === true) break;
1320 // Return true/false
1324 // Wtites data to a config.php-style file
1325 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1326 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
1327 // Initialize some variables
1333 // Is the file there and read-/write-able?
1334 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1335 $search = 'CFG: ' . $comment;
1336 $tmp = $FQFN . '.tmp';
1338 // Open the source file
1339 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1341 // Is the resource valid?
1342 if (is_resource($fp)) {
1343 // Open temporary file
1344 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1346 // Is the resource again valid?
1347 if (is_resource($fp_tmp)) {
1348 // Mark temporary file as readable
1349 $GLOBALS['file_readable'][$tmp] = true;
1352 while (!feof($fp)) {
1353 // Read from source file
1354 $line = fgets ($fp, 1024);
1356 if (strpos($line, $search) > -1) {
1362 if ($next === $seek) {
1364 $line = $prefix . $DATA . $suffix . "\n";
1370 // Write to temp file
1371 fwrite($fp_tmp, $line);
1377 // Finished writing tmp file
1381 // Close source file
1384 if (($done === true) && ($found === true)) {
1385 // Copy back tmp file and delete tmp :-)
1386 copyFileVerified($tmp, $FQFN, 0644);
1387 return removeFile($tmp);
1388 } elseif ($found === false) {
1389 outputHtml('<strong>CHANGE:</strong> 404!');
1391 outputHtml('<strong>TMP:</strong> UNDONE!');
1395 // File not found, not readable or writeable
1396 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1399 // An error was detected!
1403 // Send notification to admin
1404 function sendAdminNotification ($subject, $templateName, $content = array(), $userid = '0') {
1405 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
1407 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=Y,subject=' . $subject . ',templateName=' . $templateName);
1408 sendAdminsEmails($subject, $templateName, $content, $userid);
1410 // Send out-dated way
1411 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'admins=N,subject=' . $subject . ',templateName=' . $templateName);
1412 $message = loadEmailTemplate($templateName, $content, $userid);
1413 sendAdminEmails($subject, $message);
1417 // Debug message logger
1418 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1419 // Is debug mode enabled?
1420 if ((isDebugModeEnabled()) || ($force === true)) {
1422 $message = str_replace("\r", '', str_replace("\n", '', $message));
1424 // Log this message away
1425 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1429 // Handle extra values
1430 function handleExtraValues ($filterFunction, $value, $extraValue) {
1431 // Default is the value itself
1434 // Do we have a special filter function?
1435 if (!empty($filterFunction)) {
1436 // Does the filter function exist?
1437 if (function_exists($filterFunction)) {
1438 // Do we have extra parameters here?
1439 if (!empty($extraValue)) {
1440 // Put both parameters in one new array by default
1441 $args = array($value, $extraValue);
1443 // If we have an array simply use it and pre-extend it with our value
1444 if (is_array($extraValue)) {
1445 // Make the new args array
1446 $args = merge_array(array($value), $extraValue);
1449 // Call the multi-parameter call-back
1450 $ret = call_user_func_array($filterFunction, $args);
1452 // One parameter call
1453 $ret = call_user_func($filterFunction, $value);
1462 // Converts timestamp selections into a timestamp
1463 function convertSelectionsToEpocheTime (array &$postData, array &$DATA, &$id, &$skip) {
1464 // Init test variable
1468 // Get last three chars
1469 $test = substr($id, -3);
1471 // Improved way of checking! :-)
1472 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1473 // Found a multi-selection for timings?
1474 $test = substr($id, 0, -3);
1475 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)) {
1476 // Generate timestamp
1477 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1478 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
1479 $GLOBALS['skip_config'][$test] = true;
1481 // Remove data from array
1482 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1483 unset($postData[$test . '_' . $rem]);
1494 // Reverts the german decimal comma into Computer decimal dot
1495 function convertCommaToDot ($str) {
1496 // Default float is not a float... ;-)
1499 // Which language is selected?
1500 switch (getLanguage()) {
1501 case 'de': // German language
1502 // Remove german thousand dots first
1503 $str = str_replace('.', '', $str);
1505 // Replace german commata with decimal dot and cast it
1506 $float = (float)str_replace(',', '.', $str);
1509 default: // US and so on
1510 // Remove thousand dots first and cast
1511 $float = (float)str_replace(',', '', $str);
1519 // Handle menu-depending failed logins and return the rendered content
1520 function handleLoginFailures ($accessLevel) {
1521 // Default output is empty ;-)
1524 // Is the session data set?
1525 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1526 // Ignore zero values
1527 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1528 // Non-guest has login failures found, get both data and prepare it for template
1529 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1531 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1532 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1536 $OUT = loadTemplate('login_failures', true, $content);
1539 // Reset session data
1540 setSession('mailer_' . $accessLevel . '_failures', '');
1541 setSession('mailer_' . $accessLevel . '_last_failure', '');
1544 // Return rendered content
1549 function rebuildCache ($cache, $inc = '', $force = false) {
1551 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1553 // Shall I remove the cache file?
1554 if (isCacheInstanceValid()) {
1556 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1558 $GLOBALS['cache_instance']->removeCacheFile($force);
1561 // Include file given?
1564 $inc = sprintf("inc/loader/load-%s.php", $inc);
1566 // Is the include there?
1567 if (isIncludeReadable($inc)) {
1568 // And rebuild it from scratch
1569 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
1572 // Include not found
1573 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1579 // Determines the real remote address
1580 function determineRealRemoteAddress ($remoteAddr = false) {
1581 // Is a proxy in use?
1582 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1584 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1585 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1586 // Yet, another proxy
1587 $address = $_SERVER['HTTP_CLIENT_IP'];
1589 // The regular address when no proxy was used
1590 $address = $_SERVER['REMOTE_ADDR'];
1593 // This strips out the real address from proxy output
1594 if (strstr($address, ',')) {
1595 $addressArray = explode(',', $address);
1596 $address = $addressArray[0];
1599 // Return the result
1603 // Adds a bonus mail to the queue
1604 // This is a high-level function!
1605 function addNewBonusMail ($data, $mode = '', $output = true) {
1606 // Use mode from data if not set and availble ;-)
1607 if ((empty($mode)) && (isset($data['mode']))) {
1608 $mode = $data['mode'];
1611 // Generate receiver list
1612 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1615 if (!empty($receiver)) {
1616 // Add bonus mail to queue
1617 addBonusMailToQueue(
1629 // Mail inserted into bonus pool
1630 if ($output === true) {
1631 displayMessage('{--ADMIN_BONUS_SEND--}');
1633 } elseif ($output === true) {
1634 // More entered than can be reached!
1635 displayMessage('{--ADMIN_MORE_SELECTED--}');
1638 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1642 // Determines referal id and sets it
1643 function determineReferalId () {
1644 // Skip this in non-html-mode and outside ref.php
1645 if ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) {
1649 // Check if refid is set
1650 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
1652 } elseif (isPostRequestParameterSet('refid')) {
1653 // Get referal id from POST element refid
1654 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
1655 } elseif (isGetRequestParameterSet('refid')) {
1656 // Get referal id from GET parameter refid
1657 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
1658 } elseif (isGetRequestParameterSet('ref')) {
1659 // Set refid=ref (the referal link uses such variable)
1660 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
1661 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
1662 // The variable user comes from click.php
1663 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
1664 } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
1665 // Set session refid als global
1666 $GLOBALS['refid'] = bigintval(getSession('refid'));
1667 } elseif (isRandomReferalIdEnabled()) {
1668 // Select a random user which has confirmed enougth mails
1669 $GLOBALS['refid'] = determineRandomReferalId();
1670 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
1671 // Set default refid as refid in URL
1672 $GLOBALS['refid'] = getDefRefid();
1674 // No default id when sql_patches is not installed or none set
1675 $GLOBALS['refid'] = null;
1678 // Set cookie when default refid > 0
1679 if (!isSessionVariableSet('refid') || (isValidUserId($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
1680 // Default is not found
1683 // Do we have nickname or userid set?
1684 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
1685 // Nickname in URL, so load the id
1686 $found = fetchUserData($GLOBALS['refid'], 'nickname');
1687 } elseif (isValidUserId($GLOBALS['refid'])) {
1688 // Direct userid entered
1689 $found = fetchUserData($GLOBALS['refid']);
1692 // Is the record valid?
1693 if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
1694 // No, then reset referal id
1695 $GLOBALS['refid'] = getDefRefid();
1699 setSession('refid', $GLOBALS['refid']);
1702 // Return determined refid
1703 return $GLOBALS['refid'];
1706 // Enables the reset mode and runs it
1707 function doReset () {
1708 // Enable the reset mode
1709 $GLOBALS['reset_enabled'] = true;
1712 runFilterChain('reset');
1715 // Enables the reset mode (hourly, weekly and monthly) and runs it
1716 function doHourly () {
1717 // Enable the hourly reset mode
1718 $GLOBALS['hourly_enabled'] = true;
1720 // Run filters (one always!)
1721 runFilterChain('hourly');
1724 // Our shutdown-function
1725 function shutdown () {
1726 // Call the filter chain 'shutdown'
1727 runFilterChain('shutdown', null);
1729 // Check if not in installation phase and the link is up
1730 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1732 SQL_CLOSE(__FUNCTION__, __LINE__);
1733 } elseif (!isInstallationPhase()) {
1735 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
1738 // Stop executing here
1743 function initMemberId () {
1744 $GLOBALS['member_id'] = '0';
1747 // Setter for member id
1748 function setMemberId ($memberid) {
1749 // We should not set member id to zero
1750 if ($memberid == '0') {
1751 debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1755 $GLOBALS['member_id'] = bigintval($memberid);
1758 // Getter for member id or returns zero
1759 function getMemberId () {
1760 // Default member id
1763 // Is the member id set?
1764 if (isMemberIdSet()) {
1766 $memberid = $GLOBALS['member_id'];
1773 // Checks ether the member id is set
1774 function isMemberIdSet () {
1775 return (isset($GLOBALS['member_id']));
1778 // Setter for extra title
1779 function setExtraTitle ($extraTitle) {
1780 $GLOBALS['extra_title'] = $extraTitle;
1783 // Getter for extra title
1784 function getExtraTitle () {
1785 // Is the extra title set?
1786 if (!isExtraTitleSet()) {
1787 // No, then abort here
1788 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1792 return $GLOBALS['extra_title'];
1795 // Checks if the extra title is set
1796 function isExtraTitleSet () {
1797 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1800 // Reads a directory recursively by default and searches for files not matching
1801 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
1802 // a whole directory.
1803 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
1804 // Add default entries we should exclude
1805 $excludeArray[] = '.';
1806 $excludeArray[] = '..';
1807 $excludeArray[] = '.svn';
1808 $excludeArray[] = '.htaccess';
1810 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1815 $dirPointer = opendir(getPath() . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1818 while ($baseFile = readdir($dirPointer)) {
1819 // Exclude '.', '..' and entries in $excludeArray automatically
1820 if (in_array($baseFile, $excludeArray, true)) {
1822 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1826 // Construct include filename and FQFN
1827 $fileName = $baseDir . $baseFile;
1828 $FQFN = getPath() . $fileName;
1830 // Remove double slashes
1831 $FQFN = str_replace('//', '/', $FQFN);
1833 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1834 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1835 // These Lines are only for debugging!!
1836 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
1837 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
1838 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
1844 // Skip also files with non-matching prefix genericly
1845 if (($recursive === true) && (isDirectory($FQFN))) {
1846 // Is a redirectory so read it as well
1847 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1849 // And skip further processing
1851 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1853 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1855 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1856 // Skip wrong suffix as well
1857 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1859 } elseif (!isFileReadable($FQFN)) {
1860 // Not readable so skip it
1861 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1865 // Get file' extension (last 4 chars)
1866 $fileExtension = substr($baseFile, -4, 4);
1868 // Is the file a PHP script or other?
1869 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1870 if (($fileExtension == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
1871 // Is this a valid include file?
1872 if ($extension == '.php') {
1873 // Remove both for extension name
1874 $extName = substr($baseFile, strlen($prefix), -4);
1876 // Add file with or without base path
1877 if ($addBaseDir === true) {
1879 $files[] = $fileName;
1882 $files[] = $baseFile;
1885 // We found .php file but should not search for them, why?
1886 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1888 } elseif ($fileExtension == $extension) {
1889 // Other, generic file found
1890 $files[] = $fileName;
1895 closedir($dirPointer);
1900 // Return array with include files
1901 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1905 // Checks wether $prefix is found in $fileName
1906 function isFilePrefixFound ($fileName, $prefix) {
1907 // @TODO Find a way to cache this
1908 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1911 // Maps a module name into a database table name
1912 function mapModuleToTable ($moduleName) {
1913 // Map only these, still lame code...
1914 switch ($moduleName) {
1915 // 'index' is the guest's menu
1916 case 'index': $moduleName = 'guest'; break;
1917 // ... and 'login' the member's menu
1918 case 'login': $moduleName = 'member'; break;
1919 // Anything else will not be mapped, silently.
1926 // Add SQL debug data to array for later output
1927 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1928 // Do we have cache?
1929 if (!isset($GLOBALS['debug_sql_available'])) {
1930 // Check it and cache it in $GLOBALS
1931 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1934 // Don't execute anything here if we don't need or ext-other is missing
1935 if ($GLOBALS['debug_sql_available'] === false) {
1939 // Already executed?
1940 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1941 // Then abort here, we don't need to profile a query twice
1945 // Remeber this as profiled (or not, but we don't care here)
1946 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
1950 'num_rows' => SQL_NUMROWS($result),
1951 'affected' => SQL_AFFECTEDROWS(),
1952 'sql_str' => $sqlString,
1953 'timing' => $timing,
1954 'file' => basename($F),
1959 $GLOBALS['debug_sqls'][] = $record;
1962 // Initializes the cache instance
1963 function initCacheInstance () {
1964 // Check for double-initialization
1965 if (isset($GLOBALS['cache_instance'])) {
1966 // This should not happen and must be fixed
1967 debug_report_bug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1970 // Load include for CacheSystem class
1971 loadIncludeOnce('inc/classes/cachesystem.class.php');
1973 // Initialize cache system only when it's needed
1974 $GLOBALS['cache_instance'] = new CacheSystem();
1977 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1978 // Failed to initialize cache sustem
1979 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
1983 // Getter for message from array or raw message
1984 function getMessageFromIndexedArray ($message, $pos, $array) {
1985 // Check if the requested message was found in array
1986 if (isset($array[$pos])) {
1987 // ... if yes then use it!
1988 $ret = $array[$pos];
1990 // ... else use default message
1998 // Convert ';' to ', ' for e.g. receiver list
1999 function convertReceivers ($old) {
2000 return str_replace(';', ', ', $old);
2003 // Get a module from filename and access level
2004 function getModuleFromFileName ($file, $accessLevel) {
2005 // Default is 'invalid';
2006 $modCheck = 'invalid';
2008 // @TODO This is still very static, rewrite it somehow
2009 switch ($accessLevel) {
2011 $modCheck = 'admin';
2017 $modCheck = getModule();
2020 default: // Unsupported file name / access level
2021 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2029 // Encodes an URL for adding session id, etc.
2030 function encodeUrl ($url, $outputMode = '0') {
2031 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
2032 if ((strpos($url, session_name()) !== false) || (isRawOutputMode())) {
2033 // Raw output mode detected or session_name() found in URL
2037 // Do we have a valid session?
2038 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
2040 // Determine right seperator
2041 $seperator = '&';
2042 if (strpos($url, '?') === false) {
2045 } elseif ((!isHtmlOutputMode()) || ($outputMode != '0')) {
2046 // Non-HTML mode (or forced non-HTML mode
2051 if (session_id() != '') {
2052 $url .= $seperator . session_name() . '=' . session_id();
2057 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2059 $url = '{?URL?}/' . $url;
2066 // Simple check for spider
2067 function isSpider () {
2068 // Get the UA and trim it down
2069 $userAgent = trim(strtolower(detectUserAgent(true)));
2071 // It should not be empty, if so it is better a spider/bot
2072 if (empty($userAgent)) {
2073 // It is a spider/bot
2078 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
2081 // Function to search for the last modified file
2082 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2084 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2085 // Does it match what we are looking for? (We skip a lot files already!)
2086 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2087 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2089 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
2090 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2092 // Walk through all entries
2093 foreach ($ds as $d) {
2094 // Generate proper FQFN
2095 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2097 // Is it a file and readable?
2098 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2099 if (isFileReadable($FQFN)) {
2100 // $FQFN is a readable file so extract the requested data from it
2101 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2102 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2104 // Is the file more recent?
2105 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2106 // This file is newer as the file before
2107 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2108 $last_changed['path_name'] = $FQFN;
2109 $last_changed[$lookFor] = $check;
2113 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2118 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2119 function handleFieldWithBraces ($field) {
2120 // Are there braces [] at the end?
2121 if (substr($field, -2, 2) == '[]') {
2122 // Try to find one and replace it. I do it this way to allow easy
2123 // extending of this code.
2124 foreach (array('admin_list_builder_id_value') as $key) {
2125 // Is the cache entry set?
2126 if (isset($GLOBALS[$key])) {
2128 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2140 // Converts a userid so it can be used in SQL queries
2141 function makeDatabaseUserId ($userid) {
2142 // Is it a valid username?
2143 if (isValidUserId($userid)) {
2145 $userid = bigintval($userid);
2147 // Is not valid or zero
2155 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2156 // Note: This function is cached
2157 function capitalizeUnderscoreString ($str) {
2158 // Do we have cache?
2159 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2160 // Init target string
2163 // Explode it with the underscore, but rewrite dashes to underscore before
2164 $strArray = explode('_', str_replace('-', '_', $str));
2166 // "Walk" through all elements and make them lower-case but first upper-case
2167 foreach ($strArray as $part) {
2168 // Capitalize the string part
2169 $capitalized .= firstCharUpperCase($part);
2172 // Store the converted string in cache array
2173 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2177 return $GLOBALS[__FUNCTION__][$str];
2180 // Generate admin links for mail order
2181 // mailType can be: 'mid' or 'bid'
2182 function generateAdminMailLinks ($mailType, $mailId) {
2187 // Default column for mail status is 'data_type'
2188 // @TODO Rename column data_type to e.g. mail_status
2189 $statusColumn = 'data_type';
2191 // Which mail do we have?
2192 switch ($mailType) {
2193 case 'bid': // Bonus mail
2197 case 'mid': // Member mail
2201 default: // Handle unsupported types
2202 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2203 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2207 // Is the mail type supported?
2208 if (!empty($table)) {
2209 // Query for the mail
2210 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2211 array($statusColumn, $table, bigintval($mailId)), __FILE__, __LINE__);
2213 // Do we have one entry there?
2214 if (SQL_NUMROWS($result) == 1) {
2216 $content = SQL_FETCHARRAY($result);
2217 die('Unfinished area:<br />'.__FUNCTION__.':<br />content=<pre>'.print_r($content, true).'</pre>');
2221 SQL_FREERESULT($result);
2224 // Return generated HTML code
2230 * determine if a string can represent a number in hexadecimal
2232 * @param $hex A string to check if it is hex-encoded
2233 * @return $foo True if the string is a hex, otherwise false
2234 * @author Marques Johansson
2235 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2237 function isHexadecimal ($hex) {
2238 // Make it lowercase
2239 $hex = strtolower(trim(ltrim($hex, '0')));
2241 // Fix empty strings to zero
2246 // Simply compare decode->encode result with original
2247 return ($hex == dechex(hexdec($hex)));
2250 // Replace "\r" with "[r]" and "\n" with "[n]" and add a final new-line to make
2251 // them visible to the developer. Use this function to debug e.g. buggy HTTP
2252 // response handler functions.
2253 function replaceReturnNewLine ($str) {
2254 return str_replace("\r", '[r]', str_replace("\n", '[n]
2258 // Converts a given string by splitting it up with given delimiter similar to
2259 // explode(), but appending the delimiter again
2260 function stringToArray ($delimiter, $string) {
2262 $strArray = array();
2264 // "Walk" through all entries
2265 foreach (explode($delimiter, $string) as $split) {
2266 // Append the delimiter and add it to the array
2267 $strArray[] = $split . $delimiter;
2274 // Detects the prefix 'mb_' if a multi-byte string is given
2275 function detectMultiBytePrefix ($str) {
2276 // Default is without multi-byte
2279 // Detect multi-byte (strictly)
2280 if (mb_detect_encoding($str, 'auto', true) !== false) {
2281 // With multi-byte encoded string
2285 // Return the prefix
2289 // Searches the given array for a sub-string match and returns all found keys in an array
2290 function getArrayKeysFromSubStrArray ($heystack, array $needles, $offset = 0) {
2291 // Init array for all found keys
2294 // Now check all entries
2295 foreach ($needles as $key => $needle) {
2296 // Do we have found a partial string?
2297 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2298 if (strpos($heystack, $needle, $offset) !== false) {
2299 // Add the found key
2308 //-----------------------------------------------------------------------------
2309 // Automatically re-created functions, all taken from user comments on www.php.net
2310 //-----------------------------------------------------------------------------
2311 if (!function_exists('html_entity_decode')) {
2312 // Taken from documentation on www.php.net
2313 function html_entity_decode ($string) {
2314 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2315 $trans_tbl = array_flip($trans_tbl);
2316 return strtr($string, $trans_tbl);