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-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
44 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
45 function outputHtml ($htmlCode, $newLine = true) {
47 if (!isset($GLOBALS['output'])) $GLOBALS['output'] = '';
50 $username = getMessage('USERNAME_UNKNOWN');
51 if (isset($GLOBALS['username'])) $username = getUsername();
53 // Do we have HTML-Code here?
54 if (!empty($htmlCode)) {
55 // Yes, so we handle it as you have configured
56 switch (getConfig('OUTPUT_MODE')) {
58 // That's why you don't need any \n at the end of your HTML code... :-)
59 if (getPhpCaching() == 'on') {
60 // Output into PHP's internal buffer
61 outputRawCode($htmlCode);
63 // That's why you don't need any \n at the end of your HTML code... :-)
64 if ($newLine === true) print("\n");
66 // Render mode for old or lame servers...
67 $GLOBALS['output'] .= $htmlCode;
69 // That's why you don't need any \n at the end of your HTML code... :-)
70 if ($newLine === true) $GLOBALS['output'] .= "\n";
75 // If we are switching from render to direct output rendered code
76 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
78 // The same as above... ^
79 outputRawCode($htmlCode);
80 if ($newLine === true) print("\n");
84 // Huh, something goes wrong or maybe you have edited config.php ???
85 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
88 } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
89 // Headers already sent?
92 logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
94 // Trigger an user error
95 debug_report_bug('Headers are already sent!');
98 // Output cached HTML code
99 $GLOBALS['output'] = ob_get_contents();
101 // Clear output buffer for later output if output is found
102 if (!empty($GLOBALS['output'])) {
106 // Extension 'rewrite' installed?
107 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
108 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
111 // Compile and run finished rendered HTML code
112 compileFinalOutput();
114 // Send all HTTP headers
117 // Output code here, DO NOT REMOVE! ;-)
118 outputRawCode($GLOBALS['output']);
119 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
120 // Rewrite links when rewrite extension is active
121 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
122 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
125 // Compile and run finished rendered HTML code
126 compileFinalOutput();
128 // Send all HTTP headers
131 // Output code here, DO NOT REMOVE! ;-)
132 outputRawCode($GLOBALS['output']);
136 // Sends out all headers required for HTTP/1.1 reply
137 function sendHttpHeaders () {
139 $now = gmdate('D, d M Y H:i:s') . ' GMT';
142 sendHeader('HTTP/1.1 200');
144 // General headers for no caching
145 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
146 sendHeader('Last-Modified: ' . $now);
147 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
148 sendHeader('Pragma: no-cache'); // HTTP/1.0
149 sendHeader('Connection: Close');
150 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
151 sendHeader('Content-Language: ' . getLanguage());
154 // Compiles the final output
155 function compileFinalOutput () {
160 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
161 // Init common variables
166 $eval = "\$newContent = \"".compileCode(escapeQuotes($GLOBALS['output']))."\";";
169 // Was that eval okay?
170 if (empty($newContent)) {
171 // Something went wrong!
172 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
174 $GLOBALS['output'] = $newContent;
181 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
184 // Output the raw HTML code
185 function outputRawCode ($htmlCode) {
186 // Output stripped HTML code to avoid broken JavaScript code, etc.
187 print(str_replace('{BACK}', "\\", $htmlCode));
189 // Flush the output if only getPhpCaching() is not 'on'
190 if (getPhpCaching() != 'on') {
196 // Init fatal message array
197 function initFatalMessages () {
198 $GLOBALS['fatal_messages'] = array();
201 // Getter for whole fatal error messages
202 function getFatalArray () {
203 return $GLOBALS['fatal_messages'];
206 // Add a fatal error message to the queue array
207 function addFatalMessage ($F, $L, $message, $extra = '') {
208 if (is_array($extra)) {
209 // Multiple extras for a message with masks
210 $message = call_user_func_array('sprintf', $extra);
211 } elseif (!empty($extra)) {
212 // $message is text with a mask plus extras to insert into the text
213 $message = sprintf($message, $extra);
216 // Add message to $GLOBALS['fatal_messages']
217 $GLOBALS['fatal_messages'][] = $message;
219 // Log fatal messages away
220 debug_report_bug($message);
221 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
224 // Getter for total fatal message count
225 function getTotalFatalErrors () {
229 // Do we have at least the first entry?
230 if (!empty($GLOBALS['fatal_messages'][0])) {
232 $count = count($GLOBALS['fatal_messages']);
239 // Load a template file and return it's content (only it's name; do not use ' or ")
240 function loadTemplate ($template, $return = false, $content = array()) {
241 // @TODO Remove this sanity-check if all is fine
242 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
244 // @TODO Try to rewrite all $DATA to $content
248 if (isTemplateCached($template)) {
249 // Evaluate the cache
250 eval(readTemplateCache($template));
251 } elseif (!isset($GLOBALS['template_eval'][$template])) {
252 // Add more variables which you want to use in your template files
253 $username = getUsername();
255 // Make all template names lowercase
256 $template = strtolower($template);
260 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
263 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
264 $extraPath = detectExtraTemplatePath($template);;
266 ////////////////////////
267 // Generate file name //
268 ////////////////////////
269 $FQFN = $basePath . $extraPath . $template . '.tpl';
271 // Does the special template exists?
272 if (!isFileReadable($FQFN)) {
273 // Reset to default template
274 $FQFN = $basePath . $template . '.tpl';
277 // Now does the final template exists?
278 if (isFileReadable($FQFN)) {
279 // Count the template load
280 incrementConfigEntry('num_templates');
282 // The local file does exists so we load it. :)
283 $GLOBALS['tpl_content'] = readFromFile($FQFN);
285 // Do we have to compile the code?
287 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
288 // Normal HTML output?
289 if (getOutputMode() == '0') {
290 // Add surrounding HTML comments to help finding bugs faster
291 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
293 // Prepare eval() command
294 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
295 } elseif (substr($template, 0, 3) == 'js_') {
296 // JavaScripts don't like entities and timings
297 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
299 // Prepare eval() command, other output doesn't like entities, maybe
300 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
303 // Add surrounding HTML comments to help finding bugs faster
304 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
305 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
308 // Cache the eval() command here
309 $GLOBALS['template_eval'][$template] = $eval;
312 eval($GLOBALS['template_eval'][$template]);
313 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
314 // Only admins shall see this warning or when installation mode is active
315 $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
316 (' . $template . ')<br />
318 {--TEMPLATE_CONTENT--}
319 <pre>' . print_r($content, true) . '</pre>
321 <pre>' . print_r($DATA, true) . '</pre>
325 $GLOBALS['template_eval'][$template] = '404';
329 eval($GLOBALS['template_eval'][$template]);
332 // Do we have some content to output or return?
334 // Not empty so let's put it out! ;)
335 if ($return === true) {
336 // Return the HTML code
342 } elseif (isDebugModeEnabled()) {
343 // Warning, empty output!
344 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
348 // Detects the extra template path from given template name
349 function detectExtraTemplatePath ($template) {
354 if (!isset($GLOBALS['extra_path'][$template])) {
355 // Check for admin/guest/member/etc. templates
356 if (substr($template, 0, 6) == 'admin_') {
357 // Admin template found
358 $extraPath = 'admin/';
359 } elseif (substr($template, 0, 6) == 'guest_') {
360 // Guest template found
361 $extraPath = 'guest/';
362 } elseif (substr($template, 0, 7) == 'member_') {
363 // Member template found
364 $extraPath = 'member/';
365 } elseif (substr($template, 0, 7) == 'select_') {
366 // Selection template found
367 $extraPath = 'select/';
368 } elseif (substr($template, 0, 8) == 'install_') {
369 // Installation template found
370 $extraPath = 'install/';
371 } elseif (substr($template, 0, 4) == 'ext_') {
372 // Extension template found
374 } elseif (substr($template, 0, 3) == 'la_') {
375 // 'Logical-area' template found
377 } elseif (substr($template, 0, 3) == 'js_') {
378 // JavaScript template found
380 } elseif (substr($template, 0, 5) == 'menu_') {
381 // Menu template found
382 $extraPath = 'menu/';
384 // Test for extension
385 $test = substr($template, 0, strpos($template, '_'));
387 // Probe for valid extension name
388 if (isExtensionNameValid($test)) {
389 // Set extra path to extension's name
390 $extraPath = $test . '/';
395 $GLOBALS['extra_path'][$template] = $extraPath;
399 return $GLOBALS['extra_path'][$template];
402 // Loads an email template and compiles it
403 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
406 // Make sure all template names are lowercase!
407 $template = strtolower($template);
409 // Default 'nickname' if extension is not installed
412 // Neutral email address is default
413 $email = getConfig('WEBMASTER');
415 // Is content an array?
416 if (is_array($content)) {
417 // Add expiration to array
418 if (getConfig('auto_purge') == '0') {
419 // Will never expire!
420 $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
422 // Create nice date string
423 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
428 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$userid},template={$template},content[]=".gettype($content).'<br />');
429 if (($userid > 0) && (is_array($content))) {
430 // If nickname extension is installed, fetch nickname as well
431 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
432 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
434 fetchUserData($userid, 'nickname');
436 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
438 fetchUserData($userid);
441 // Merge data if valid
442 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
443 if (isUserDataValid()) {
444 $content = merge_array($content, getUserDataArray());
446 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
449 // Translate M to male or F to female if present
450 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
452 // Overwrite email from data if present
453 if (isset($content['email'])) $email = $content['email'];
455 // Store email for some functions in global data array
456 // @TODO Do only use $content, not $DATA or raw variables
457 $DATA['email'] = $email;
460 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
463 $extraPath = detectExtraTemplatePath($template);
465 // Generate full FQFN
466 $FQFN = $basePath . $extraPath . $template . '.tpl';
468 // Does the special template exists?
469 if (!isFileReadable($FQFN)) {
470 // Reset to default template
471 $FQFN = $basePath . $template . '.tpl';
474 // Now does the final template exists?
476 if (isFileReadable($FQFN)) {
477 // The local file does exists so we load it. :)
478 $GLOBALS['tpl_content'] = readFromFile($FQFN);
481 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileRawCode(escapeQuotes($GLOBALS['tpl_content']))."\");";
482 eval($GLOBALS['tpl_content']);
483 } elseif (!empty($template)) {
484 // Template file not found!
485 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
486 {--TEMPLATE_CONTENT--}
487 <pre>' . print_r($content, true) . '</pre>
489 <pre>' . print_r($DATA, true) . '</pre>
492 // Debug mode not active? Then remove the HTML tags
493 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
495 // No template name supplied!
496 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
499 // Is there some content?
500 if (empty($newContent)) {
502 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
504 // Add last error if the required function exists
505 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
508 // Remove content and data
516 // Send mail out to an email address
517 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
518 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
520 // Compile subject line (for POINTS constant etc.)
521 eval("\$subject = decodeEntities(\"".compileRawCode(escapeQuotes($subject))."\");");
524 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
525 // Value detected, is the message extension installed?
526 // @TODO Extension 'msg' does not exist
527 if (isExtensionActive('msg')) {
528 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
531 // Does the user exist?
532 if (fetchUserData($toEmail)) {
534 $toEmail = getUserData('email');
537 $toEmail = getConfig('WEBMASTER');
540 } elseif ($toEmail == '0') {
542 $toEmail = getConfig('WEBMASTER');
544 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
546 // Check for PHPMailer or debug-mode
547 if (!checkPhpMailerUsage()) {
548 // Not in PHPMailer-Mode
549 if (empty($mailHeader)) {
550 // Load email header template
551 $mailHeader = loadEmailTemplate('header');
554 $mailHeader .= loadEmailTemplate('header');
556 } elseif (isDebugModeEnabled()) {
557 if (empty($mailHeader)) {
558 // Load email header template
559 $mailHeader = loadEmailTemplate('header');
562 $mailHeader .= loadEmailTemplate('header');
567 eval("\$toEmail = \"".compileRawCode(escapeQuotes($toEmail))."\";");
570 eval("\$message = \"".str_replace('$', '$', compileRawCode(escapeQuotes($message)))."\";");
572 // Fix HTML parameter (default is no!)
573 if (empty($isHtml)) $isHtml = 'N';
574 if (isDebugModeEnabled()) {
575 // In debug mode we want to display the mail instead of sending it away so we can debug this part
577 Headers : ' . str_replace('<', '<', str_replace('>', '>', secureString(trim($mailHeader)))) . '
578 To : ' . $toEmail . '
579 Subject : ' . $subject . '
580 Message : ' . $message . '
582 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
583 // Send mail as HTML away
584 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
585 } elseif (!empty($toEmail)) {
587 sendRawEmail($toEmail, $subject, $message, $mailHeader);
588 } elseif ($isHtml != 'Y') {
590 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
594 // Check to use wether legacy mail() command or PHPMailer class
595 // @TODO Rewrite this to an extension 'smtp'
597 function checkPhpMailerUsage() {
598 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
601 // Send out a raw email with PHPMailer class or legacy mail() command
602 function sendRawEmail ($toEmail, $subject, $message, $from) {
603 // Just compile all again, to put out all configs, etc.
604 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
605 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
606 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
607 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
609 // Shall we use PHPMailer class or legacy mode?
610 if (checkPhpMailerUsage()) {
611 // Use PHPMailer class with SMTP enabled
612 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
613 loadIncludeOnce('inc/phpmailer/class.smtp.php');
616 $mail = new PHPMailer();
618 // Set charset to UTF-8
619 $mail->CharSet('UTF-8');
621 // Path for PHPMailer
622 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
625 $mail->SMTPAuth = true;
626 $mail->Host = getConfig('SMTP_HOSTNAME');
628 $mail->Username = getConfig('SMTP_USER');
629 $mail->Password = getConfig('SMTP_PASSWORD');
631 $mail->From = getConfig('WEBMASTER');
635 $mail->FromName = getConfig('MAIN_TITLE');
636 $mail->Subject = $subject;
637 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
638 $mail->Body = $message;
639 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
640 $mail->WordWrap = 70;
643 $mail->Body = decodeEntities($message);
645 $mail->AddAddress($toEmail, '');
646 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
647 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
648 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
651 // Use legacy mail() command
652 mail($toEmail, $subject, decodeEntities($message), $from);
656 // Generate a password in a specified length or use default password length
657 function generatePassword ($length = '0') {
658 // Auto-fix invalid length of zero
659 if ($length == '0') $length = getConfig('pass_len');
661 // Initialize array with all allowed chars
662 $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,-,+,_,/,.');
664 // Start creating password
666 for ($i = '0'; $i < $length; $i++) {
667 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
670 // When the size is below 40 we can also add additional security by scrambling
671 // it. Otherwise we may corrupt hashes
672 if (strlen($PASS) <= 40) {
673 // Also scramble the password
674 $PASS = scrambleString($PASS);
677 // Return the password
681 // Generates a human-readable timestamp from the Uni* stamp
682 function generateDateTime ($time, $mode = '0') {
683 // Filter out numbers
684 $time = bigintval($time);
686 // If the stamp is zero it mostly didn't "happen"
689 return getMessage('NEVER_HAPPENED');
692 switch (getLanguage()) {
693 case 'de': // German date / time format
695 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
696 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
697 case '2': $ret = date('d.m.Y|H:i', $time); break;
698 case '3': $ret = date('d.m.Y', $time); break;
700 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
705 default: // Default is the US date / time format!
707 case '0': $ret = date('r', $time); break;
708 case '1': $ret = date('Y-m-d - g:i A', $time); break;
709 case '2': $ret = date('y-m-d|H:i', $time); break;
710 case '3': $ret = date('y-m-d', $time); break;
712 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
721 // Translates Y/N to yes/no
722 function translateYesNo ($yn) {
724 $translated = '??? (' . $yn . ')';
726 case 'Y': $translated = getMessage('YES'); break;
727 case 'N': $translated = getMessage('NO'); break;
730 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
738 // Translates the "pool type" into human-readable
739 function translatePoolType ($type) {
740 // Default?type is unknown
741 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
744 $constName = sprintf("POOL_TYPE_%s", $type);
747 if (isMessageIdValid($constName)) {
749 $translated = getMessage($constName);
752 // Return "translation"
756 // Translates the american decimal dot into a german comma
757 function translateComma ($dotted, $cut = true, $max = '0') {
758 // Default is 3 you can change this in admin area "Misc -> Misc Options"
759 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
761 // Use from config is default
762 $maxComma = getConfig('max_comma');
764 // Use from parameter?
765 if ($max > 0) $maxComma = $max;
768 if (($cut === true) && ($max == '0')) {
769 // Test for commata if in cut-mode
770 $com = explode('.', $dotted);
771 if (count($com) < 2) {
772 // Don't display commatas even if there are none... ;-)
778 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
781 switch (getLanguage()) {
782 case 'de': // German language
783 $dotted = number_format($dotted, $maxComma, ',', '.');
786 default: // All others
787 $dotted = number_format($dotted, $maxComma, '.', ',');
791 // Return translated value
795 // Translate Uni*-like gender to human-readable
796 function translateGender ($gender) {
798 $ret = '!' . $gender . '!';
800 // Male/female or company?
802 case 'M': $ret = getMessage('GENDER_M'); break;
803 case 'F': $ret = getMessage('GENDER_F'); break;
804 case 'C': $ret = getMessage('GENDER_C'); break;
806 // Log unknown gender
807 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
811 // Return translated gender
815 // "Translates" the user status
816 function translateUserStatus ($status) {
817 // Generate message depending on status
822 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
827 $ret = getMessage('ACCOUNT_DELETED');
831 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
832 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
840 // Generates an URL for the dereferer
841 function generateDerefererUrl ($URL) {
842 // Don't de-refer our own links!
843 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
844 // De-refer this link
845 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
852 // Generates an URL for the frametester
853 function generateFrametesterUrl ($URL) {
854 // Prepare frametester URL
855 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
856 encodeString(compileUriCode($URL))
859 // Return the new URL
860 return $frametesterUrl;
863 // Count entries from e.g. a selection box
864 function countSelection ($array) {
866 if (!is_array($array)) {
868 debug_report_bug(__FUNCTION__.': No array provided.');
875 foreach ($array as $key => $selected) {
877 if (!empty($selected)) $ret++;
880 // Return counted selections
884 // Generate XHTML code for the CAPTCHA
885 function generateCaptchaCode ($code, $type, $DATA, $userid) {
886 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
889 // Generates a timestamp (some wrapper for mktime())
890 function makeTime ($hours, $minutes, $seconds, $stamp) {
891 // Extract day, month and year from given timestamp
892 $days = date('d', $stamp);
893 $months = date('m', $stamp);
894 $years = date('Y', $stamp);
896 // Create timestamp for wished time which depends on extracted date
907 // Redirects to an URL and if neccessarry extends it with own base URL
908 function redirectToUrl ($URL) {
910 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
912 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
913 $rel = ' rel="external"';
915 // Do we have internal or external URL?
916 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
917 // Own (=internal) URL
922 $GLOBALS['output'] = ob_get_contents();
924 // Clear it only if there is content
925 if (!empty($GLOBALS['output'])) {
929 // Three different ways to debug...
930 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
931 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
932 //* DEBUG: */ die($URL);
934 // Simple probe for bots/spiders from search engines
935 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
936 // Secure the URL against bad things such als HTML insertions and so on...
937 $URL = secureString($URL);
939 // Output new location link as anchor
940 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
941 } elseif (!headers_sent()) {
942 //* DEBUG: */ debug_report_bug("URL={$URL}");
943 // Clear own output buffer
944 $GLOBALS['output'] = '';
946 // Load URL when headers are not sent
947 sendHeader('Location: '.str_replace('&', '&', $URL));
949 // Output error message
950 loadInclude('inc/header.php');
951 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
952 loadInclude('inc/footer.php');
955 // Shut the mailer down here
959 // Wrapper for redirectToUrl but URL comes from a configuration entry
960 function redirectToConfiguredUrl ($configEntry) {
962 $URL = getConfig($configEntry);
967 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
974 // Compiles the given HTML/mail code
975 function compileCode ($code, $simple = false, $constants = true, $full = true) {
976 // Is the code a string?
977 if (!is_string($code)) {
978 // Silently return it
983 $startCompile = microtime(true);
986 $code = compileRawCode($code, $simple, $constants, $full);
989 $compiled = microtime(true);
992 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
994 // Return compiled code
998 // Compiles the code (use compileCode() only for HTML because of the comments)
999 // @TODO $simple is deprecated
1000 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1001 // Is the code a string?
1002 if (!is_string($code)) {
1003 // Silently return it
1007 // Init replacement-array with smaller set of security characters
1008 $secChars = $GLOBALS['url_chars'];
1010 // Select full set of chars to replace when we e.g. want to compile URLs
1011 if ($full === true) $secChars = $GLOBALS['security_chars'];
1013 // Compile more through a filter
1014 $code = runFilterChain('compile_code', $code);
1016 // Compile constants
1017 if ($constants === true) {
1018 // BEFORE 0.2.1 : Language and data constants
1019 // WITH 0.2.1+ : Only language constants
1020 $code = str_replace('{--', "\" . getMessage('", str_replace('--}', "') . \"", $code));
1022 // BEFORE 0.2.1 : Not used
1023 // WITH 0.2.1+ : Data constants
1024 $code = str_replace('{!', "\" . constant('", str_replace('!}', "') . \"", $code));
1027 // Compile QUOT and other non-HTML codes
1028 foreach ($secChars['to'] as $k => $to) {
1029 // Do the reversed thing as in inc/libs/security_functions.php
1030 $code = str_replace($to, $secChars['from'][$k], $code);
1033 // Find $content[bla][blub] entries
1034 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1035 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1037 // Are some matches found?
1038 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1039 // Replace all matches
1040 $matchesFound = array();
1041 foreach ($matches[0] as $key => $match) {
1042 // Fuzzy look has failed by default
1043 $fuzzyFound = false;
1045 // Fuzzy look on match if already found
1046 foreach ($matchesFound as $found => $set) {
1048 $test = substr($found, 0, strlen($match));
1050 // Does this entry exist?
1051 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1052 if ($test == $match) {
1054 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1061 if ($fuzzyFound === true) continue;
1063 // Take all string elements
1064 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1065 // Replace it in the code
1066 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1067 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1068 $code = str_replace($match, '".' . $newMatch . '."', $code);
1069 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1070 $matchesFound[$match] = 1;
1071 } elseif (!isset($matchesFound[$match])) {
1072 // Not yet replaced!
1073 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1074 $code = str_replace($match, '".' . $match . '."', $code);
1075 $matchesFound[$match] = 1;
1084 /************************************************************************
1086 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1087 * $a_sort sortiert: *
1089 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1090 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1091 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1092 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1093 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1095 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1096 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1097 * Sie, dass es doch nicht so schwer ist! :-) *
1099 ************************************************************************/
1100 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1102 while ($primary_key < count($a_sort)) {
1103 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1104 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1106 if ($nums === false) {
1107 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1108 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1109 } elseif ($key != $key2) {
1110 // Sort numbers (E.g.: 9 < 10)
1111 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1112 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1116 // We have found two different values, so let's sort whole array
1117 foreach ($dummy as $sort_key => $sort_val) {
1118 $t = $dummy[$sort_key][$key];
1119 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1120 $dummy[$sort_key][$key2] = $t;
1131 // Write back sorted array
1136 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1139 if ($type == 'yn') {
1140 // This is a yes/no selection only!
1141 if ($id > 0) $prefix .= "[" . $id."]";
1142 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1144 // Begin with regular selection box here
1145 if (!empty($prefix)) $prefix .= "_";
1147 if ($id > 0) $type2 .= "[" . $id."]";
1148 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1153 for ($idx = 1; $idx < 32; $idx++) {
1154 $OUT .= "<option value=\"" . $idx."\"";
1155 if ($default == $idx) $OUT .= ' selected="selected"';
1156 $OUT .= ">" . $idx."</option>\n";
1160 case 'month': // Month
1161 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1162 $OUT .= "<option value=\"" . $month."\"";
1163 if ($default == $month) $OUT .= ' selected="selected"';
1164 $OUT .= ">" . $descr."</option>\n";
1168 case 'year': // Year
1170 $year = date('Y', time());
1172 // Use configured min age or fixed?
1173 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1175 $startYear = $year - getConfig('min_age');
1178 $startYear = $year - 16;
1181 // Calculate earliest year (100 years old people can still enter Internet???)
1182 $minYear = $year - 100;
1184 // Check if the default value is larger than minimum and bigger than actual year
1185 if (($default > $minYear) && ($default >= $year)) {
1186 for ($idx = $year; $idx < ($year + 11); $idx++) {
1187 $OUT .= "<option value=\"" . $idx."\"";
1188 if ($default == $idx) $OUT .= ' selected="selected"';
1189 $OUT .= ">" . $idx."</option>\n";
1191 } elseif ($default == -1) {
1192 // Current year minus 1
1193 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1195 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1198 // Get current year and subtract the configured minimum age
1199 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1200 // Calculate earliest year depending on extension version
1201 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1202 // Use configured minimum age
1203 $year = date('Y', time()) - getConfig('min_age');
1205 // Use fixed 16 years age
1206 $year = date('Y', time()) - 16;
1209 // Construct year selection list
1210 for ($idx = $minYear; $idx <= $year; $idx++) {
1211 $OUT .= "<option value=\"" . $idx."\"";
1212 if ($default == $idx) $OUT .= ' selected="selected"';
1213 $OUT .= ">" . $idx."</option>\n";
1220 for ($idx = '0'; $idx < 60; $idx+=5) {
1221 if (strlen($idx) == 1) $idx = '0' . $idx;
1222 $OUT .= "<option value=\"" . $idx."\"";
1223 if ($default == $idx) $OUT .= ' selected="selected"';
1224 $OUT .= ">" . $idx."</option>\n";
1229 for ($idx = '0'; $idx < 24; $idx++) {
1230 if (strlen($idx) == 1) $idx = '0' . $idx;
1231 $OUT .= "<option value=\"" . $idx."\"";
1232 if ($default == $idx) $OUT .= ' selected="selected"';
1233 $OUT .= ">" . $idx."</option>\n";
1238 $OUT .= "<option value=\"Y\"";
1239 if ($default == 'Y') $OUT .= ' selected="selected"';
1240 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1241 if ($default != 'Y') $OUT .= ' selected="selected"';
1242 $OUT .= ">{--NO--}</option>\n";
1245 $OUT .= " </select>\n";
1250 // Deprecated : $length
1253 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1254 // Build server string
1255 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1258 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1259 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1260 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1261 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1262 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1264 // Build string from misc data
1265 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1267 // Add more additional data
1268 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1270 // Add referal id, language, theme and userid
1271 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1272 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1273 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1274 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1276 // Calculate number for generating the code
1277 $a = $code + getConfig('_ADD') - 1;
1279 if (isConfigEntrySet('master_salt')) {
1280 // Generate hash with master salt from modula of number with the prime number and other data
1281 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, getConfig('master_salt'));
1283 // Create number from hash
1284 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1286 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1287 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, getConfig('salt_length')));
1289 // Create number from hash
1290 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1293 // At least 10 numbers shall be secure enought!
1294 $len = getConfig('code_length');
1295 if ($len == '0') $len = $length;
1296 if ($len == '0') $len = 10;
1298 // Cut off requested counts of number
1299 $return = substr(str_replace('.', '', $rcode), 0, $len);
1301 // Done building code
1305 // Does only allow numbers
1306 function bigintval ($num, $castValue = true) {
1307 // Filter all numbers out
1308 $ret = preg_replace('/[^0123456789]/', '', $num);
1311 if ($castValue === true) $ret = (double)$ret;
1313 // Has the whole value changed?
1314 if ('' . $ret . '' != '' . $num . '') {
1316 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1323 // Insert the code in $img_code into jpeg or PNG image
1324 function generateImageOrCode ($img_code, $headerSent = true) {
1325 // Is the code size oversized or shouldn't we display it?
1326 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1327 // Stop execution of function here because of over-sized code length
1328 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1329 } elseif ($headerSent === false) {
1330 // Return an HTML code here
1331 return "<img src=\"{%url=img.php?code=" . $img_code."%}\" alt=\"Image\" />\n";
1335 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1338 getConfig('img_type')
1342 if (isFileReadable($img)) {
1343 // Switch image type
1344 switch (getConfig('img_type'))
1347 // Okay, load image and hide all errors
1348 $image = imagecreatefromjpeg($img);
1352 // Okay, load image and hide all errors
1353 $image = imagecreatefrompng($img);
1357 // Exit function here
1358 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1362 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1363 $text_color = imagecolorallocate($image, 0, 0, 0);
1365 // Insert code into image
1366 imagestring($image, 5, 14, 2, $img_code, $text_color);
1368 // Return to browser
1369 sendHeader('Content-Type: image/' . getConfig('img_type'));
1371 // Output image with matching image factory
1372 switch (getConfig('img_type')) {
1373 case 'jpg': imagejpeg($image); break;
1374 case 'png': imagepng($image); break;
1377 // Remove image from memory
1378 imagedestroy($image);
1380 // Create selection box or array of splitted timestamp
1381 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1382 // Calculate 2-seconds timestamp
1383 $stamp = round($timestamp);
1384 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1386 // Do we have a leap year?
1388 $TEST = date('Y', time()) / 4;
1389 $M1 = date('m', time());
1390 $M2 = date('m', (time() + $timestamp));
1392 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1393 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1395 // First of all years...
1396 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1397 //* DEBUG: */ print("Y={$Y}<br />");
1399 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1400 //* DEBUG: */ print("M={$M}<br />");
1402 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1403 //* DEBUG: */ print("W={$W}<br />");
1405 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1406 //* DEBUG: */ print("D={$D}<br />");
1408 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24) - $W * 7 * 24 - $D * 24));
1409 //* DEBUG: */ print("h={$h}<br />");
1411 $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1412 //* DEBUG: */ print("m={$m}<br />");
1413 // And at last seconds...
1414 $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1415 //* DEBUG: */ print("s={$s}<br />");
1417 // Is seconds zero and time is < 60 seconds?
1418 if (($s == '0') && ($timestamp < 60)) {
1420 $s = round($timestamp);
1424 // Now we convert them in seconds...
1426 if ($return_array) {
1427 // Just put all data in an array for later use
1439 $OUT = "<div align=\"" . $align."\">\n";
1440 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"timebox_table dashed\">\n";
1443 if (ereg('Y', $display) || (empty($display))) {
1444 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1447 if (ereg('M', $display) || (empty($display))) {
1448 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1451 if (ereg('W', $display) || (empty($display))) {
1452 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1455 if (ereg('D', $display) || (empty($display))) {
1456 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1459 if (ereg('h', $display) || (empty($display))) {
1460 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1463 if (ereg('m', $display) || (empty($display))) {
1464 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1467 if (ereg('s', $display) || (empty($display))) {
1468 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1474 if (ereg('Y', $display) || (empty($display))) {
1475 // Generate year selection
1476 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1477 for ($idx = '0'; $idx <= 10; $idx++) {
1478 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1479 if ($idx == $Y) $OUT .= ' selected="selected"';
1480 $OUT .= ">" . $idx."</option>\n";
1482 $OUT .= " </select></td>\n";
1484 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1487 if (ereg('M', $display) || (empty($display))) {
1488 // Generate month selection
1489 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1490 for ($idx = '0'; $idx <= 11; $idx++)
1492 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1493 if ($idx == $M) $OUT .= ' selected="selected"';
1494 $OUT .= ">" . $idx."</option>\n";
1496 $OUT .= " </select></td>\n";
1498 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1501 if (ereg('W', $display) || (empty($display))) {
1502 // Generate week selection
1503 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1504 for ($idx = '0'; $idx <= 4; $idx++) {
1505 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1506 if ($idx == $W) $OUT .= ' selected="selected"';
1507 $OUT .= ">" . $idx."</option>\n";
1509 $OUT .= " </select></td>\n";
1511 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1514 if (ereg('D', $display) || (empty($display))) {
1515 // Generate day selection
1516 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1517 for ($idx = '0'; $idx <= 31; $idx++) {
1518 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1519 if ($idx == $D) $OUT .= ' selected="selected"';
1520 $OUT .= ">" . $idx."</option>\n";
1522 $OUT .= " </select></td>\n";
1524 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\" />\n";
1527 if (ereg('h', $display) || (empty($display))) {
1528 // Generate hour selection
1529 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1530 for ($idx = '0'; $idx <= 23; $idx++) {
1531 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1532 if ($idx == $h) $OUT .= ' selected="selected"';
1533 $OUT .= ">" . $idx."</option>\n";
1535 $OUT .= " </select></td>\n";
1537 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\" />\n";
1540 if (ereg('m', $display) || (empty($display))) {
1541 // Generate minute selection
1542 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1543 for ($idx = '0'; $idx <= 59; $idx++) {
1544 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1545 if ($idx == $m) $OUT .= ' selected="selected"';
1546 $OUT .= ">" . $idx."</option>\n";
1548 $OUT .= " </select></td>\n";
1550 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\" />\n";
1553 if (ereg('s', $display) || (empty($display))) {
1554 // Generate second selection
1555 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1556 for ($idx = '0'; $idx <= 59; $idx++) {
1557 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1558 if ($idx == $s) $OUT .= ' selected="selected"';
1559 $OUT .= ">" . $idx."</option>\n";
1561 $OUT .= " </select></td>\n";
1563 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\" />\n";
1566 $OUT .= "</table>\n";
1568 // Return generated HTML code
1574 function createTimestampFromSelections ($prefix, $postData) {
1575 // Initial return value
1578 // Do we have a leap year?
1580 $TEST = date('Y', time()) / 4;
1581 $M1 = date('m', time());
1582 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1583 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1584 // First add years...
1585 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1587 $ret += $postData[$prefix."_mo"] * 2628000;
1589 $ret += $postData[$prefix."_we"] * 604800;
1591 $ret += $postData[$prefix."_da"] * 86400;
1593 $ret += $postData[$prefix."_ho"] * 3600;
1595 $ret += $postData[$prefix."_mi"] * 60;
1596 // And at last seconds...
1597 $ret += $postData[$prefix."_se"];
1598 // Return calculated value
1602 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1603 function createFancyTime ($stamp) {
1604 // Get data array with years/months/weeks/days/...
1605 $data = createTimeSelections($stamp, '', '', '', true);
1607 foreach($data as $k => $v) {
1609 // Value is greater than 0 "eval" data to return string
1610 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1615 // Do we have something there?
1616 if (strlen($ret) > 0) {
1617 // Remove leading commata and space
1618 $ret = substr($ret, 2);
1621 $ret = "0 {--_SECONDS--}";
1624 // Return fancy time string
1628 // Generates a navigation row for listing emails
1629 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1630 $SEP = ''; $TOP = '';
1631 if ($show_form === false) {
1633 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1637 for ($page = 1; $page <= $PAGES; $page++) {
1638 // Is the page currently selected or shall we generate a link to it?
1639 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1640 // Is currently selected, so only highlight it
1641 $NAV .= '<strong>-';
1643 // Open anchor tag and add base URL
1644 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1646 // Add userid when we shall show all mails from a single member
1647 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1649 // Close open anchor tag
1653 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1654 // Is currently selected, so only highlight it
1655 $NAV .= '-</strong>';
1661 // Add seperator if we have not yet reached total pages
1662 if ($page < $PAGES) $NAV .= ' | ';
1665 // Define constants only once
1666 $content['nav'] = $NAV;
1667 $content['span'] = $colspan;
1668 $content['top'] = $TOP;
1669 $content['sep'] = $SEP;
1671 // Load navigation template
1672 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1674 if ($return === true) {
1675 // Return generated HTML-Code
1683 // Extract host from script name
1684 function extractHostnameFromUrl (&$script) {
1685 // Use default SERVER_URL by default... ;) So?
1686 $url = getConfig('SERVER_URL');
1688 // Is this URL valid?
1689 if (substr($script, 0, 7) == 'http://') {
1690 // Use the hostname from script URL as new hostname
1691 $url = substr($script, 7);
1692 $extract = explode('/', $url);
1694 // Done extracting the URL :)
1697 // Extract host name
1698 $host = str_replace('http://', '', $url);
1699 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1701 // Generate relative URL
1702 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1703 if (substr(strtolower($script), 0, 7) == 'http://') {
1704 // But only if http:// is in front!
1705 $script = substr($script, (strlen($url) + 7));
1706 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1708 $script = substr($script, (strlen($url) + 8));
1711 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1712 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1718 // Send a GET request
1719 function sendGetRequest ($script, $data = array()) {
1720 // Extract host name from script
1721 $host = extractHostnameFromUrl($script);
1724 $scriptData = http_build_query($data, '', '&');
1726 // Do we have a question-mark in the script?
1727 if (strpos($script, '?') === false) {
1728 // No, so first char must be question mark
1729 $scriptData = '?' . $scriptData;
1732 $scriptData = '&' . $scriptData;
1736 $script .= $scriptData;
1738 // Generate GET request header
1739 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1740 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1741 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1742 if (isConfigEntrySet('FULL_VERSION')) {
1743 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1745 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1747 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1748 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1749 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1751 // Send the raw request
1752 $response = sendRawRequest($host, $request);
1754 // Return the result to the caller function
1758 // Send a POST request
1759 function sendPostRequest ($script, $postData) {
1760 // Is postData an array?
1761 if (!is_array($postData)) {
1763 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1764 return array('', '', '');
1767 // Extract host name from script
1768 $host = extractHostnameFromUrl($script);
1770 // Construct request
1771 $data = http_build_query($postData, '', '&');
1773 // Generate POST request header
1774 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1775 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1776 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1777 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1778 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1779 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1780 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1781 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1784 // Send the raw request
1785 $response = sendRawRequest($host, $request);
1787 // Return the result to the caller function
1791 // Sends a raw request to another host
1792 function sendRawRequest ($host, $request) {
1793 // Init errno and errdesc with 'all fine' values
1794 $errno = '0'; $errdesc = '';
1797 $response = array('', '', '');
1799 // Default is not to use proxy
1802 // Are proxy settins set?
1803 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1809 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1810 if ($useProxy === true) {
1811 // Connect to host through proxy connection
1812 $fp = @fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1814 // Connect to host directly
1815 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1819 if (!is_resource($fp)) {
1825 if ($useProxy === true) {
1826 // Generate CONNECT request header
1827 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1828 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1830 // Use login data to proxy? (username at least!)
1831 if (getConfig('proxy_username') != '') {
1833 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
1834 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1837 // Add last new-line
1838 $proxyTunnel .= getConfig('HTTP_EOL');
1839 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1842 fputs($fp, $proxyTunnel);
1846 // No response received
1850 // Read the first line
1851 $resp = trim(fgets($fp, 10240));
1852 $respArray = explode(' ', $resp);
1853 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1854 // Invalid response!
1860 fputs($fp, $request);
1863 while (!feof($fp)) {
1864 $response[] = trim(fgets($fp, 1024));
1870 // Skip first empty lines
1872 foreach ($resp as $idx => $line) {
1874 $line = trim($line);
1876 // Is this line empty?
1879 array_shift($response);
1881 // Abort on first non-empty line
1886 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1888 // Proxy agent found?
1889 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1890 // Proxy header detected, so remove two lines
1891 array_shift($response);
1892 array_shift($response);
1895 // Was the request successfull?
1896 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1897 // Not found / access forbidden
1898 $response = array('', '', '');
1905 // Taken from www.php.net eregi() user comments
1906 function isEmailValid ($email) {
1907 // Check first part of email address
1908 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1911 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1914 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1916 // Return check result
1917 return preg_match($regex, $email);
1920 // Function taken from user comments on www.php.net / function eregi()
1921 function isUrlValid ($URL, $compile=true) {
1922 // Trim URL a little
1923 $URL = trim(urldecode($URL));
1924 //* DEBUG: */ outputHtml($URL.'<br />');
1926 // Compile some chars out...
1927 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1928 //* DEBUG: */ outputHtml($URL.'<br />');
1930 // Check for the extension filter
1931 if (isExtensionActive('filter')) {
1932 // Use the extension's filter set
1933 return FILTER_VALIDATE_URL($URL, false);
1936 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1937 // https:// in front of the URLs
1938 return isUrlValidSimple($URL);
1941 // Generate a list of administrative links to a given userid
1942 function generateMemberAdminActionLinks ($userid, $status = '') {
1943 // Make sure userid is a number
1944 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1946 // Define all main targets
1947 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1949 // Begin of navigation links
1952 foreach ($targetArray as $tar) {
1953 $OUT .= "<span class=\"admin_user_link\"><a href=\"{%url=modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "%}\" title=\"{--ADMIN_LINK_";
1954 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1955 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1956 // Locked accounts shall be unlocked
1957 $OUT .= 'UNLOCK_USER';
1959 // All other status is fine
1960 $OUT .= strtoupper($tar);
1962 $OUT .= "_TITLE--}\">{--ADMIN_";
1963 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1964 // Locked accounts shall be unlocked
1965 $OUT .= 'UNLOCK_USER';
1967 // All other status is fine
1968 $OUT .= strtoupper($tar);
1970 $OUT .= "--}</a></span> | ";
1973 // Finish navigation link
1974 $OUT = substr($OUT, 0, -7) . ']';
1980 // Generate an email link
1981 function generateEmailLink ($email, $table = 'admins') {
1982 // Default email link (INSECURE! Spammer can read this by harvester programs)
1983 $EMAIL = 'mailto:' . $email;
1985 // Check for several extensions
1986 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1987 // Create email link for contacting admin in guest area
1988 $EMAIL = generateAdminEmailLink($email);
1989 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
1990 // Create email link for contacting a member within admin area (or later in other areas, too?)
1991 $EMAIL = generateUserEmailLink($email, 'admin');
1992 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1993 // Create email link to contact sponsor within admin area (or like the link above?)
1994 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
1997 // Shall I close the link when there is no admin?
1998 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2000 // Return email link
2004 // Generate a hash for extra-security for all passwords
2005 function generateHash ($plainText, $salt = '') {
2006 // Is the required extension 'sql_patches' there and a salt is not given?
2007 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2008 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2009 return md5($plainText);
2012 // Do we miss an arry element here?
2013 if (!isConfigEntrySet('file_hash')) {
2015 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2018 // When the salt is empty build a new one, else use the first x configured characters as the salt
2020 // Build server string (inc/databases.php is no longer updated with every commit)
2021 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2024 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('secret_key') . getConfig('ENCRYPT_SEPERATOR') . getConfig('file_hash') . getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime')) . getConfig('ENCRYPT_SEPERATOR') . getConfig('master_salt');
2027 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2029 // Calculate number for generating the code
2030 $a = time() + getConfig('_ADD') - 1;
2032 // Generate SHA1 sum from modula of number and the prime number
2033 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2034 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2035 $sha1 = scrambleString($sha1);
2036 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2037 //* DEBUG: */ $sha1b = descrambleString($sha1);
2038 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2040 // Generate the password salt string
2041 $salt = substr($sha1, 0, getConfig('salt_length'));
2042 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2045 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2046 $salt = substr($salt, 0, getConfig('salt_length'));
2047 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2049 // Sanity check on salt
2050 if (strlen($salt) != getConfig('salt_length')) {
2052 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2057 return $salt.sha1($salt . $plainText);
2060 // Scramble a string
2061 function scrambleString($str) {
2065 // Final check, in case of failture it will return unscrambled string
2066 if (strlen($str) > 40) {
2067 // The string is to long
2069 } elseif (strlen($str) == 40) {
2071 $scrambleNums = explode(':', getConfig('pass_scramble'));
2073 // Generate new numbers
2074 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2077 // Scramble string here
2078 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2079 for ($idx = '0'; $idx < strlen($str); $idx++) {
2080 // Get char on scrambled position
2081 $char = substr($str, $scrambleNums[$idx], 1);
2083 // Add it to final output string
2084 $scrambled .= $char;
2087 // Return scrambled string
2088 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2092 // De-scramble a string scrambled by scrambleString()
2093 function descrambleString($str) {
2094 // Scramble only 40 chars long strings
2095 if (strlen($str) != 40) return $str;
2097 // Load numbers from config
2098 $scrambleNums = explode(':', getConfig('pass_scramble'));
2101 if (count($scrambleNums) != 40) return $str;
2103 // Begin descrambling
2104 $orig = str_repeat(' ', 40);
2105 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2106 for ($idx = '0'; $idx < 40; $idx++) {
2107 $char = substr($str, $idx, 1);
2108 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2111 // Return scrambled string
2112 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2116 // Generated a "string" for scrambling
2117 function genScrambleString ($len) {
2118 // Prepare array for the numbers
2119 $scrambleNumbers = array();
2121 // First we need to setup randomized numbers from 0 to 31
2122 for ($idx = '0'; $idx < $len; $idx++) {
2124 $rand = mt_rand(0, ($len -1));
2126 // Check for it by creating more numbers
2127 while (array_key_exists($rand, $scrambleNumbers)) {
2128 $rand = mt_rand(0, ($len -1));
2132 $scrambleNumbers[$rand] = $rand;
2135 // So let's create the string for storing it in database
2136 $scrambleString = implode(':', $scrambleNumbers);
2137 return $scrambleString;
2140 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2141 function generatePassString ($passHash) {
2142 // Return vanilla password hash
2145 // Is a secret key and master salt already initialized?
2146 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2147 // Only calculate when the secret key is generated
2148 $newHash = ''; $start = 9;
2149 for ($idx = '0'; $idx < 10; $idx++) {
2150 $part1 = hexdec(substr($passHash, $start, 4));
2151 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2152 $mod = dechex($idx);
2153 if ($part1 > $part2) {
2154 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2155 } elseif ($part2 > $part1) {
2156 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2158 $mod = substr($mod, 0, 4);
2159 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2160 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2161 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2166 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2167 $ret = generateHash($newHash, getConfig('master_salt'));
2168 //* DEBUG: */ print('ret='.$ret.'<br />');
2171 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2172 $ret = md5($passHash);
2173 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2180 // Fix "deleted" cookies
2181 function fixDeletedCookies ($cookies) {
2182 // Is this an array with entries?
2183 if ((is_array($cookies)) && (count($cookies) > 0)) {
2184 // Then check all cookies if they are marked as deleted!
2185 foreach ($cookies as $cookieName) {
2186 // Is the cookie set to "deleted"?
2187 if (getSession($cookieName) == 'deleted') {
2188 setSession($cookieName, '');
2194 // Output error messages in a fasioned way and die...
2195 function app_die ($F, $L, $message) {
2196 // Check if Script is already dieing and not let it kill itself another 1000 times
2197 if (!isset($GLOBALS['app_died'])) {
2198 // Make sure, that the script realy realy diese here and now
2199 $GLOBALS['app_died'] = true;
2202 loadIncludeOnce('inc/header.php');
2204 // Rewrite message for output
2205 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2207 // Better log this message away
2208 logDebugMessage($F, $L, $message);
2210 // Load the message template
2211 loadTemplate('admin_settings_saved', false, $message);
2214 loadIncludeOnce('inc/footer.php');
2216 // Script tried to kill itself twice
2217 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2221 // Display parsing time and number of SQL queries in footer
2222 function displayParsingTime() {
2223 // Is the timer started?
2224 if (!isset($GLOBALS['startTime'])) {
2230 $endTime = microtime(true);
2232 // "Explode" both times
2233 $start = explode(' ', $GLOBALS['startTime']);
2234 $end = explode(' ', $endTime);
2235 $runTime = $end[0] - $start[0];
2236 if ($runTime < 0) $runTime = '0';
2240 'runtime' => translateComma($runTime),
2241 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2244 // Load the template
2245 loadTemplate('show_timings', false, $content);
2248 // Check wether a boolean constant is set
2249 // Taken from user comments in PHP documentation for function constant()
2250 function isBooleanConstantAndTrue ($constName) { // : Boolean
2251 // Failed by default
2255 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2257 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2258 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2261 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2262 if (defined($constName)) {
2264 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2265 $res = (constant($constName) === true);
2269 $GLOBALS['cache_array']['const'][$constName] = $res;
2271 //* DEBUG: */ var_dump($res);
2277 // Checks if a given apache module is loaded
2278 function isApacheModuleLoaded ($apacheModule) {
2279 // Check it and return result
2280 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2283 // Get current theme name
2284 function getCurrentTheme () {
2285 // The default theme is 'default'... ;-)
2288 // Do we have ext-theme installed and active?
2289 if (isExtensionActive('theme')) {
2290 // Call inner method
2291 $ret = getActualTheme();
2294 // Return theme value
2298 // Generates an error code from given account status
2299 function generateErrorCodeFromUserStatus ($status='') {
2300 // If no status is provided, use the default, cached
2301 if ((empty($status)) && (isMember())) {
2303 $status = getUserData('status');
2306 // Default error code if unknown account status
2307 $errorCode = getCode('UNKNOWN_STATUS');
2309 // Generate constant name
2310 $codeName = sprintf("ID_%s", $status);
2312 // Is the constant there?
2313 if (isCodeSet($codeName)) {
2315 $errorCode = getCode($codeName);
2318 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2321 // Return error code
2325 // Function to search for the last modifified file
2326 function searchDirsRecursive ($dir, &$last_changed) {
2328 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2329 // Does it match what we are looking for? (We skip a lot files already!)
2330 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2331 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2332 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2333 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2335 // Walk through all entries
2336 foreach ($ds as $d) {
2337 // Generate proper FQFN
2338 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2340 // Is it a file and readable?
2341 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2342 if (isDirectory($FQFN)) {
2343 // $FQFN is a directory so also crawl into this directory
2345 if (!empty($dir)) $newDir = $dir . '/'. $d;
2346 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2347 searchDirsRecursive($newDir, $last_changed);
2348 } elseif (isFileReadable($FQFN)) {
2349 // $FQFN is a filename and no directory
2350 $time = filemtime($FQFN);
2351 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2352 if ($last_changed['time'] < $time) {
2353 // This file is newer as the file before
2354 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2355 $last_changed['path_name'] = $FQFN;
2356 $last_changed['time'] = $time;
2362 // "Getter" for revision/version data
2363 function getActualVersion ($type = 'Revision') {
2364 // By default nothing is new... ;-)
2367 // Is the cache entry there?
2368 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2369 // Found so increase cache hit
2370 incrementStatsEntry('cache_hits');
2373 return $GLOBALS['cache_array']['revision'][$type][0];
2375 // FQFN of revision file
2376 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2378 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2379 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2380 // Forced rebuild of .revision file
2383 // Check for revision file
2384 if (!isFileReadable($FQFN)) {
2385 // Not found, so we need to create it
2388 // Revision file found
2389 $ins_vers = explode("\n", readFromFile($FQFN));
2391 // Get array for mapping information
2392 $mapper = array_flip(getSearchFor());
2393 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2395 // Is the content valid?
2396 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2397 // File needs update!
2400 // Generate fake cache entry
2401 foreach ($mapper as $map => $idx) {
2402 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2405 // Return found value
2406 return trim($ins_vers[$mapper[$type]]);
2411 // Has it been updated?
2412 if ($new === true) {
2414 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2416 // ... and call recursive
2417 return getActualVersion($type);
2422 // Repares an array we are looking for
2423 // The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
2424 function getSearchFor () {
2425 // Add Revision, Date, Tag and Author
2426 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2428 // Return the created array
2432 // @TODO Please describe this function
2433 function getArrayFromActualVersion () {
2437 // Directory to start with search
2438 $last_changed = array(
2443 // Init return array
2444 $akt_vers = array();
2446 // Init value for counting the founded keywords
2449 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2450 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2453 $last_file = readFromFile($last_changed['path_name']);
2455 // Get all the keywords to search for
2456 $searchFor = getSearchFor();
2458 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2459 foreach ($searchFor as $search) {
2460 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2461 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2462 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2463 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2466 // Save the last-changed filename for debugging
2467 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2469 // at least 3 keyword-Tags are needed for propper values
2470 if ($res && $res >= 3
2471 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2472 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2473 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2474 // Prepare content witch need special treadment
2476 // Prepare timestamp for date
2477 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2478 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2480 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2481 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2482 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2486 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2487 $version = sendGetRequest('check-updates3.php');
2490 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2491 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2492 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2493 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2494 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2495 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2498 // Return prepared array
2499 return $GLOBALS['cache_array']['revision'];
2502 // Back-ported from the new ship-simu engine. :-)
2503 function debug_get_printable_backtrace () {
2505 $backtrace = "<ol>\n";
2507 // Get and prepare backtrace for output
2508 $backtraceArray = debug_backtrace();
2509 foreach ($backtraceArray as $key => $trace) {
2510 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2511 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2512 if (!isset($trace['args'])) $trace['args'] = array();
2513 $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>\n";
2517 $backtrace .= "</ol>\n";
2519 // Return the backtrace
2523 // A mail-able backtrace
2524 function debug_get_mailable_backtrace () {
2528 // Get and prepare backtrace for output
2529 $backtraceArray = debug_backtrace();
2530 foreach ($backtraceArray as $key => $trace) {
2531 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2532 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2533 if (!isset($trace['args'])) $trace['args'] = array();
2534 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2537 // Return the backtrace
2541 // Output a debug backtrace to the user
2542 function debug_report_bug ($message = '', $sendEmail = true) {
2543 // Is this already called?
2544 if (isset($GLOBALS[__FUNCTION__])) {
2546 print 'Message:'.$message.'<br />Backtrace:<pre>';
2547 debug_print_backtrace();
2551 // Set this function as called
2552 $GLOBALS[__FUNCTION__] = true;
2557 // Is the optional message set?
2558 if (!empty($message)) {
2560 $debug = sprintf("Note: %s<br />\n",
2564 // @TODO Add a little more infos here
2565 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2569 $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">http://bugs.mxchange.org</a> and include the logfile from <strong>" . str_replace(getConfig('PATH'), '', getConfig('CACHE_PATH')) . "debug.log</strong> in your report (you can now attach files):<pre>";
2570 $debug .= debug_get_printable_backtrace();
2571 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2572 $debug .= "Thank you for finding bugs.";
2574 // Send an email? (e.g. not wanted for evaluation errors)
2575 if ($sendEmail === true) {
2578 'message' => trim($message),
2579 'backtrace' => trim(debug_get_mailable_backtrace())
2582 // Send email to webmaster
2583 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2587 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2591 // Generates a ***weak*** seed
2592 function generateSeed () {
2593 return microtime(true) * 100000;
2596 // Converts a message code to a human-readable message
2597 function getMessageFromErrorCode ($code) {
2601 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2602 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2603 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2604 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2605 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2606 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2607 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2608 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2609 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2610 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2611 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2612 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2613 case getCode('ID_GUEST') : $message = getMessage('LOGIN_ID_GUEST'); break;
2614 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2615 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2616 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2617 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2618 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2619 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2620 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2621 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2622 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2623 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2624 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2625 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2626 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2627 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2628 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2630 case getCode('ERROR_MAILID'):
2631 if (isExtensionActive('mailid', true)) {
2632 $message = getMessage('ERROR_CONFIRMING_MAIL');
2634 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2638 case getCode('EXTENSION_PROBLEM'):
2639 if (isGetRequestElementSet('ext')) {
2640 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2642 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2646 case getCode('URL_TLOCK'):
2647 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2648 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2650 // Load timestamp from last order
2651 list($timestamp) = SQL_FETCHROW($result);
2652 $timestamp = generateDateTime($timestamp, 1);
2655 SQL_FREERESULT($result);
2657 // Calculate hours...
2658 $STD = round(getConfig('url_tlock') / 60 / 60);
2661 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2664 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2666 // Finally contruct the message
2667 // @TODO Rewrite this old lost code to a template
2668 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2669 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2670 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2674 // Missing/invalid code
2675 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2678 logDebugMessage(__FUNCTION__, __LINE__, $message);
2682 // Return the message
2686 // Compile characters which are allowed in URLs
2687 function compileUriCode ($code, $simple = true) {
2688 // Compile constants
2689 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2691 // Compile QUOT and other non-HTML codes
2692 $code = str_replace('{DOT}', '.',
2693 str_replace('{SLASH}', '/',
2694 str_replace('{QUOT}', "'",
2695 str_replace('{DOLLAR}', '$',
2696 str_replace('{OPEN_ANCHOR}', '(',
2697 str_replace('{CLOSE_ANCHOR}', ')',
2698 str_replace('{OPEN_SQR}', '[',
2699 str_replace('{CLOSE_SQR}', ']',
2700 str_replace('{PER}', '%',
2704 // Return compiled code
2708 // Function taken from user comments on www.php.net / function eregi()
2709 function isUrlValidSimple ($url) {
2711 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2713 // Allows http and https
2714 $http = "(http|https)+(:\/\/)";
2716 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2717 // Test double-domains (e.g. .de.vu)
2718 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2720 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2722 $dir = "((/)+([-_\.[:alnum:]])+)*";
2724 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2725 // ... and the string after and including question character
2726 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2727 // Pattern for URLs like http://url/dir/doc.html?var=value
2728 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2729 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2730 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2731 // Pattern for URLs like http://url/dir/?var=value
2732 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2733 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2734 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2735 // Pattern for URLs like http://url/dir/page.ext
2736 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2737 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2738 $pattern['ipdp'] = $http . $ip . $dir . $page;
2739 // Pattern for URLs like http://url/dir
2740 $pattern['d1d'] = $http . $domain1 . $dir;
2741 $pattern['d2d'] = $http . $domain2 . $dir;
2742 $pattern['ipd'] = $http . $ip . $dir;
2743 // Pattern for URLs like http://url/?var=value
2744 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2745 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2746 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2747 // Pattern for URLs like http://url?var=value
2748 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2749 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2750 $pattern['ipg12'] = $http . $ip . $getstring1;
2751 // Test all patterns
2753 foreach ($pattern as $key => $pat) {
2755 if (isDebugRegExpressionEnabled()) {
2756 // @TODO Are these convertions still required?
2757 $pat = str_replace('.', "\.", $pat);
2758 $pat = str_replace('@', "\@", $pat);
2759 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2762 // Check if expression matches
2763 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2766 if ($reg === true) break;
2769 // Return true/false
2773 // Wtites data to a config.php-style file
2774 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2775 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2776 // Initialize some variables
2782 // Is the file there and read-/write-able?
2783 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2784 $search = 'CFG: ' . $comment;
2785 $tmp = $FQFN . '.tmp';
2787 // Open the source file
2788 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2790 // Is the resource valid?
2791 if (is_resource($fp)) {
2792 // Open temporary file
2793 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2795 // Is the resource again valid?
2796 if (is_resource($fp_tmp)) {
2797 // Mark temporary file as readable
2798 $GLOBALS['file_readable'][$tmp] = true;
2801 while (!feof($fp)) {
2802 // Read from source file
2803 $line = fgets ($fp, 1024);
2805 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2808 if ($next === $seek) {
2810 $line = $prefix . $DATA . $suffix . "\n";
2816 // Write to temp file
2817 fputs($fp_tmp, $line);
2823 // Finished writing tmp file
2827 // Close source file
2830 if (($done === true) && ($found === true)) {
2831 // Copy back tmp file and delete tmp :-)
2832 copyFileVerified($tmp, $FQFN, 0644);
2833 return removeFile($tmp);
2834 } elseif ($found === false) {
2835 outputHtml('<strong>CHANGE:</strong> 404!');
2837 outputHtml('<strong>TMP:</strong> UNDONE!');
2841 // File not found, not readable or writeable
2842 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2845 // An error was detected!
2848 // Send notification to admin
2849 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2850 if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
2852 sendAdminsEmails($subject, $templateName, $content, $userid);
2854 // Send out out-dated way
2855 $message = loadEmailTemplate($templateName, $content, $userid);
2856 sendAdminEmails($subject, $message);
2860 // Debug message logger
2861 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2862 // Is debug mode enabled?
2863 if ((isDebugModeEnabled()) || ($force === true)) {
2865 $message = str_replace("\r", '', str_replace("\n", '', $message));
2867 // Log this message away, we better don't call app_die() here to prevent an endless loop
2868 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2869 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2874 // Handle extra values
2875 function handleExtraValues ($filterFunction, $value, $extraValue) {
2876 // Default is the value itself
2879 // Do we have a special filter function?
2880 if (!empty($filterFunction)) {
2881 // Does the filter function exist?
2882 if (function_exists($filterFunction)) {
2883 // Do we have extra parameters here?
2884 if (!empty($extraValue)) {
2885 // Put both parameters in one new array by default
2886 $args = array($value, $extraValue);
2888 // If we have an array simply use it and pre-extend it with our value
2889 if (is_array($extraValue)) {
2890 // Make the new args array
2891 $args = merge_array(array($value), $extraValue);
2894 // Call the multi-parameter call-back
2895 $ret = call_user_func_array($filterFunction, $args);
2897 // One parameter call
2898 $ret = call_user_func($filterFunction, $value);
2907 // Converts timestamp selections into a timestamp
2908 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2909 // Init test variable
2913 // Get last three chars
2914 $test = substr($id, -3);
2916 // Improved way of checking! :-)
2917 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2918 // Found a multi-selection for timings?
2919 $test = substr($id, 0, -3);
2920 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)) {
2921 // Generate timestamp
2922 $postData[$test] = createTimestampFromSelections($test, $postData);
2923 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2924 $GLOBALS['skip_config'][$test] = true;
2926 // Remove data from array
2927 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2928 unset($postData[$test . '_' . $rem]);
2939 // Reverts the german decimal comma into Computer decimal dot
2940 function convertCommaToDot ($str) {
2941 // Default float is not a float... ;-)
2944 // Which language is selected?
2945 switch (getLanguage()) {
2946 case 'de': // German language
2947 // Remove german thousand dots first
2948 $str = str_replace('.', '', $str);
2950 // Replace german commata with decimal dot and cast it
2951 $float = (float)str_replace(',', '.', $str);
2954 default: // US and so on
2955 // Remove thousand dots first and cast
2956 $float = (float)str_replace(',', '', $str);
2964 // Handle menu-depending failed logins and return the rendered content
2965 function handleLoginFailtures ($accessLevel) {
2966 // Default output is empty ;-)
2969 // Is the session data set?
2970 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
2971 // Ignore zero values
2972 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
2973 // Non-guest has login failures found, get both data and prepare it for template
2974 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
2976 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
2977 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
2981 $OUT = loadTemplate('login_failures', true, $content);
2984 // Reset session data
2985 setSession('mxchange_' . $accessLevel.'_failures', '');
2986 setSession('mxchange_' . $accessLevel.'_last_fail', '');
2989 // Return rendered content
2994 function rebuildCacheFile ($cache, $inc = '', $force = false) {
2996 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
2998 // Shall I remove the cache file?
2999 if (isCacheInstanceValid()) {
3001 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3003 $GLOBALS['cache_instance']->removeCacheFile($force);
3006 // Include file given?
3009 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3011 // Is the include there?
3012 if (isIncludeReadable($inc)) {
3013 // And rebuild it from scratch
3014 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3017 // Include not found!
3018 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3024 // Determines the real remote address
3025 function determineRealRemoteAddress () {
3026 // Is a proxy in use?
3027 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3029 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3030 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3031 // Yet, another proxy
3032 $address = $_SERVER['HTTP_CLIENT_IP'];
3034 // The regular address when no proxy was used
3035 $address = $_SERVER['REMOTE_ADDR'];
3038 // This strips out the real address from proxy output
3039 if (strstr($address, ',')) {
3040 $addressArray = explode(',', $address);
3041 $address = $addressArray[0];
3044 // Return the result
3048 // Adds a bonus mail to the queue
3049 // This is a high-level function!
3050 function addNewBonusMail ($data, $mode = '', $output=true) {
3051 // Use mode from data if not set and availble ;-)
3052 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3054 // Generate receiver list
3055 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3058 if (!empty($receiver)) {
3059 // Add bonus mail to queue
3060 addBonusMailToQueue(
3072 // Mail inserted into bonus pool
3073 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3074 } elseif ($output) {
3075 // More entered than can be reached!
3076 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3079 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3083 // Determines referal id and sets it
3084 function determineReferalId () {
3085 // Skip this in non-html-mode and outside ref.php
3086 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3088 // Check if refid is set
3089 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3091 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3092 // The variable user comes from the click-counter script click.php and we only accept this here
3093 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3094 } elseif (isPostRequestElementSet('refid')) {
3095 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3096 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3097 } elseif (isGetRequestElementSet('refid')) {
3098 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3099 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3100 } elseif (isGetRequestElementSet('ref')) {
3101 // Set refid=ref (the referal link uses such variable)
3102 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3103 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3104 // Set session refid als global
3105 $GLOBALS['refid'] = bigintval(getSession('refid'));
3106 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3107 // Select a random user which has confirmed enougth mails
3108 $GLOBALS['refid'] = determineRandomReferalId();
3109 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3110 // Set default refid as refid in URL
3111 $GLOBALS['refid'] = getConfig('def_refid');
3113 // No default id when sql_patches is not installed or none set
3114 $GLOBALS['refid'] = '0';
3117 // Set cookie when default refid > 0
3118 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3119 // Default is not found
3122 // Do we have nickname or userid set?
3123 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3124 // Nickname in URL, so load the id
3125 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3126 } elseif ($GLOBALS['refid'] > 0) {
3127 // Direct userid entered
3128 $found = fetchUserData($GLOBALS['refid']);
3131 // Is the record valid?
3132 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3133 // No, then reset referal id
3134 $GLOBALS['refid'] = getConfig('def_refid');
3138 setSession('refid', $GLOBALS['refid']);
3141 // Return determined refid
3142 return $GLOBALS['refid'];
3145 // Enables the reset mode and runs it
3146 function doReset () {
3147 // Enable the reset mode
3148 $GLOBALS['reset_enabled'] = true;
3151 runFilterChain('reset');
3154 // Our shutdown-function
3155 function shutdown () {
3156 // Call the filter chain 'shutdown'
3157 runFilterChain('shutdown', null);
3159 if (SQL_IS_LINK_UP()) {
3161 SQL_CLOSE(__FILE__, __LINE__);
3162 } elseif (!isInstallationPhase()) {
3164 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3167 // Stop executing here
3172 function initMemberId () {
3173 $GLOBALS['member_id'] = '0';
3176 // Setter for member id
3177 function setMemberId ($memberid) {
3178 // We should not set member id to zero
3179 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3182 $GLOBALS['member_id'] = bigintval($memberid);
3185 // Getter for member id or returns zero
3186 function getMemberId () {
3187 // Default member id
3190 // Is the member id set?
3191 if (isMemberIdSet()) {
3193 $memberid = $GLOBALS['member_id'];
3200 // Checks ether the member id is set
3201 function isMemberIdSet () {
3202 return (isset($GLOBALS['member_id']));
3205 // Handle message codes from URL
3206 function handleCodeMessage () {
3207 if (isGetRequestElementSet('code')) {
3208 // Default extension is 'unknown'
3211 // Is extension given?
3212 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3214 // Convert the 'code' parameter from URL to a human-readable message
3215 $message = getMessageFromErrorCode(getRequestElement('code'));
3217 // Load message template
3218 loadTemplate('message', false, $message);
3222 // Setter for extra title
3223 function setExtraTitle ($extraTitle) {
3224 $GLOBALS['extra_title'] = $extraTitle;
3227 // Getter for extra title
3228 function getExtraTitle () {
3229 // Is the extra title set?
3230 if (!isExtraTitleSet()) {
3231 // No, then abort here
3232 debug_report_bug('extra_title is not set!');
3236 return $GLOBALS['extra_title'];
3239 // Checks if the extra title is set
3240 function isExtraTitleSet () {
3241 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3244 // Generates a 'extension foo inactive' message
3245 function generateExtensionInactiveMessage ($ext_name) {
3246 // Is the extension empty?
3247 if (empty($ext_name)) {
3248 // This should not happen
3249 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3253 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3255 // Is an admin logged in?
3257 // Then output admin message
3258 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3261 // Return prepared message
3265 // Generates a 'extension foo not installed' message
3266 function generateExtensionNotInstalledMessage ($ext_name) {
3267 // Is the extension empty?
3268 if (empty($ext_name)) {
3269 // This should not happen
3270 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3274 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3276 // Is an admin logged in?
3278 // Then output admin message
3279 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3282 // Return prepared message
3286 // Generates a message depending on if the extension is not installed or not
3288 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3292 // Is the extension not installed or just deactivated?
3293 switch (isExtensionInstalled($ext_name)) {
3294 case true; // Deactivated!
3295 $message = generateExtensionInactiveMessage($ext_name);
3298 case false; // Not installed!
3299 $message = generateExtensionNotInstalledMessage($ext_name);
3302 default: // Should not happen!
3303 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3304 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3308 // Return the message
3312 // Reads a directory recursively by default and searches for files not matching
3313 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3314 // a whole directory.
3315 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3316 // Add default entries we should exclude
3317 $excludeArray[] = '.';
3318 $excludeArray[] = '..';
3319 $excludeArray[] = '.svn';
3320 $excludeArray[] = '.htaccess';
3322 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3327 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3330 while ($baseFile = readdir($dirPointer)) {
3331 // Exclude '.', '..' and entries in $excludeArray automatically
3332 if (in_array($baseFile, $excludeArray, true)) {
3334 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3338 // Construct include filename and FQFN
3339 $fileName = $baseDir . $baseFile;
3340 $FQFN = getConfig('PATH') . $fileName;
3342 // Remove double slashes
3343 $FQFN = str_replace('//', '/', $FQFN);
3345 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3346 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3347 // These Lines are only for debugging!!
3348 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3349 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3350 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3356 // Skip also files with non-matching prefix genericly
3357 if (($recursive === true) && (isDirectory($FQFN))) {
3358 // Is a redirectory so read it as well
3359 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3361 // And skip further processing
3363 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3365 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3367 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3368 // Skip wrong suffix as well
3369 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3371 } elseif (!isFileReadable($FQFN)) {
3372 // Not readable so skip it
3373 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3377 // Is the file a PHP script or other?
3378 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3379 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3380 // Is this a valid include file?
3381 if ($extension == '.php') {
3382 // Remove both for extension name
3383 $extName = substr($baseFile, strlen($prefix), -4);
3385 // Is the extension valid and active?
3386 if (isExtensionNameValid($extName)) {
3387 // Then add this file
3388 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3389 $files[] = $fileName;
3391 // Add non-extension files as well
3392 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3393 if ($addBaseDir === true) {
3394 $files[] = $fileName;
3396 $files[] = $baseFile;
3400 // We found .php file but should not search for them, why?
3401 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3403 } elseif (substr($baseFile, -4, 4) == $extension) {
3404 // Other, generic file found
3405 $files[] = $fileName;
3410 closedir($dirPointer);
3415 // Return array with include files
3416 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3420 // Maps a module name into a database table name
3421 function mapModuleToTable ($moduleName) {
3422 // Map only these, still lame code...
3423 switch ($moduleName) {
3424 // 'index' is the guest's menu
3425 case 'index': $moduleName = 'guest'; break;
3426 // ... and 'login' the member's menu
3427 case 'login': $moduleName = 'member'; break;
3428 // Anything else will not be mapped, silently.
3435 // Add SQL debug data to array for later output
3436 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3437 // Already executed?
3438 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3439 // Then abort here, we don't need to profile a query twice
3443 // Remeber this as profiled (or not, but we don't care here)
3444 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3446 // Do we have cache?
3447 if (!isset($GLOBALS['debug_sql_available'])) {
3448 // Check it and cache it in $GLOBALS
3449 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3452 // Don't execute anything here if we don't need or ext-other is missing
3453 if ($GLOBALS['debug_sql_available'] === false) {
3459 'num_rows' => SQL_NUMROWS($result),
3460 'affected' => SQL_AFFECTEDROWS(),
3461 'sql_str' => $sqlString,
3462 'timing' => $timing,
3463 'file' => basename($F),
3468 $GLOBALS['debug_sqls'][] = $record;
3471 // Initializes the cache instance
3472 function initCacheInstance () {
3473 // Load include for CacheSystem class
3474 loadIncludeOnce('inc/classes/cachesystem.class.php');
3476 // Initialize cache system only when it's needed
3477 $GLOBALS['cache_instance'] = new CacheSystem();
3478 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3479 // Failed to initialize cache sustem
3480 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3484 // Getter for message from array or raw message
3485 function getMessageFromIndexedArray ($message, $pos, $array) {
3486 // Check if the requested message was found in array
3487 if (isset($array[$pos])) {
3488 // ... if yes then use it!
3489 $ret = $array[$pos];
3491 // ... else use default message
3499 // Print code with line numbers
3500 function linenumberCode ($code) {
3501 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3502 $count_lines = count($codeE);
3504 $r = 'Line | Code:<br />';
3505 foreach($codeE as $line => $c) {
3506 $r .= '<div class="line"><span class="linenum">';
3507 if ($count_lines == 1) {
3510 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3515 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3518 return '<div class="code">' . $r . '</div>';
3521 // Convert ';' to ', ' for e.g. receiver list
3522 function convertReceivers ($old) {
3523 return str_replace(';', ', ', $old);
3526 // Determines the right page title
3527 function determinePageTitle () {
3528 // Config and database connection valid?
3529 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3533 // Title decoration enabled?
3534 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
3536 // Do we have some extra title?
3537 if (isExtraTitleSet()) {
3539 $TITLE .= getExtraTitle() . ' by ';
3543 $TITLE .= getConfig('MAIN_TITLE');
3545 // Add title of module? (middle decoration will also be added!)
3546 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3547 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3550 // Add title from what file
3552 if (getModule() == 'login') $mode = 'member';
3553 elseif (getModule() == 'index') $mode = 'guest';
3554 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3556 // Add title decorations? (right)
3557 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3559 // Remember title in constant for the template
3560 $pageTitle = $TITLE;
3561 } elseif ((isInstalled()) && (isAdminRegistered())) {
3562 // Installed, admin registered but no ext-sql_patches
3563 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3564 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3565 // Installed but no admin registered
3566 $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
3567 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3568 // Installation mode
3569 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3571 // Configuration not found!
3572 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3574 // Do not add the fatal message in installation mode
3575 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3579 return decodeEntities($pageTitle);
3582 // Checks wethere there is a cache file there. This function is cached.
3583 function isTemplateCached ($template) {
3584 // Do we have cached this result?
3585 if (!isset($GLOBALS['template_cache'][$template])) {
3587 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3590 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3594 return $GLOBALS['template_cache'][$template];
3597 // Flushes non-flushed template cache to disk
3598 function flushTemplateCache ($template, $eval) {
3599 // Is this cache flushed?
3600 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3602 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3604 // Replace username with a call
3605 $eval = str_replace('$username', '".getUsername()."', $eval);
3608 writeToFile($FQFN, $eval, true);
3612 // Reads a template cache
3613 function readTemplateCache ($template) {
3615 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3617 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3620 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3624 return $GLOBALS['template_eval'][$template];
3627 // Escapes quotes (default is only double-quotes)
3628 function escapeQuotes ($str, $single = false) {
3629 // Should we escape all?
3630 if ($single === true) {
3631 // Escape all (including null)
3632 $str = addslashes($str);
3634 // Escape only double-quotes but prevent double-quoting
3635 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3638 // Return the escaped string
3642 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3643 function escapeJavaScriptQuotes ($str) {
3644 // Replace all double-quotes and secure back-ticks
3645 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3651 // Send out mails depending on the 'mod/modes' combination
3652 // @TODO Lame description for this function
3653 function sendModeMails ($mod, $modes) {
3655 if (fetchUserData(getMemberId())) {
3656 // Extract salt from cookie
3657 $salt = substr(getSession('u_hash'), 0, -40);
3659 // Now let's compare passwords
3660 $hash = generatePassString(getUserData('password'));
3662 // Does the hash match or should we change it?
3663 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
3665 $content = getUserDataArray();
3668 $content['gender'] = translateGender($content['gender']);
3670 // Clear/init the content variable
3671 $content['message'] = '';
3674 // @TODO Move this in a filter
3677 foreach ($modes as $mode) {
3679 case 'normal': break; // Do not add any special lines
3680 case 'email': // Email was changed!
3681 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestElement('old_email')."\n";
3684 case 'pass': // Password was changed
3685 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3689 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3690 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3695 if (isExtensionActive('country')) {
3696 // Replace code with description
3697 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
3700 // Merge content with data from POST
3701 $content = merge_array($content, postRequestArray());
3704 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3706 if (getConfig('admin_notify') == 'Y') {
3707 // The admin needs to be notified about a profile change
3708 $message_admin = 'admin_mydata_notify';
3709 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3712 $message_admin = '';
3716 // Set subject lines
3717 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3719 // Output success message
3720 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3723 default: // Unsupported module!
3724 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3725 $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
3729 // Passwords mismatch
3730 $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
3733 // Could not load profile
3734 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
3737 // Send email to user if required
3738 if ((!empty($sub_mem)) && (!empty($message))) {
3740 sendEmail($content['email'], $sub_mem, $message);
3743 // Send only if no other error has occured
3744 if (empty($content)) {
3745 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3747 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3748 } elseif (getConfig('admin_notify') == 'Y') {
3749 // Cannot send mails to admin!
3750 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3753 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3758 loadTemplate('admin_settings_saved', false, $content);
3761 // Generates a 'selection box' from given array
3762 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent) {
3764 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3765 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3767 // Walk through all options
3768 foreach ($options as $option) {
3769 // Add the <option> entry
3770 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3773 // Finish selection box
3774 $OUT .= '</select>';
3778 'selection_box' => $OUT,
3779 'module' => getModule(),
3783 // Load template and return it
3784 return loadTemplate('select_' . $name . '_box', true, $content);
3787 // Get a module from filename and access level
3788 function getModuleFromFileName ($file, $accessLevel) {
3789 // Default is 'invalid';
3790 $modCheck = 'invalid';
3792 // @TODO This is still very static, rewrite it somehow
3793 switch ($accessLevel) {
3795 $modCheck = 'admin';
3801 $modCheck = getModule();
3804 default: // Unsupported file name / access level
3805 debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3813 // Encodes an URL for adding session id, etc.
3814 function encodeUrl ($url, $outputMode = '0') {
3815 // Do we have already have a PHPSESSID inside? Then it is already converted...
3816 if (strpos($url, session_name()) !== false) return $url;
3818 // Do we have a valid session?
3819 if ((($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3821 // Determine right seperator
3822 $seperator = '&';
3823 if (strpos($url, '?') === false) {
3826 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3832 if (session_id() != '') {
3833 $url .= $seperator . session_name() . '=' . session_id();
3838 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3840 $url = '{?URL?}/' . $url;
3847 // Simple check for spider
3848 function isSpider () {
3849 // It should not be empty, if so it is better a spider/bot
3850 if (detectUserAgent(true) == '') return true;
3853 return ((strpos('spider', strtolower(detectUserAgent(true))) !== false) || (strpos('bot', strtolower(detectUserAgent(true))) !== false));
3856 //////////////////////////////////////////////////
3857 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3858 //////////////////////////////////////////////////
3860 if (!function_exists('html_entity_decode')) {
3861 // Taken from documentation on www.php.net
3862 function html_entity_decode ($string) {
3863 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3864 $trans_tbl = array_flip($trans_tbl);
3865 return strtr($string, $trans_tbl);
3869 if (!function_exists('http_build_query')) {
3870 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3871 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
3873 foreach ((array)$data as $k => $v) {
3874 if (is_int($k) && $prefix != null) {
3875 $k = urlencode($prefix . $k);
3878 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3880 if (is_array($v) || is_object($v)) {
3881 array_push($ret, http_build_query($v, '', $sep, $k));
3883 array_push($ret, $k.'='.urlencode($v));
3887 if (empty($sep)) $sep = ini_get('arg_separator.output');
3889 return implode($sep, $ret);