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['header'])) || (count($GLOBALS['header']) == 0))) {
89 // Output cached HTML code
90 $GLOBALS['output'] = ob_get_contents();
92 // Clear output buffer for later output if output is found
93 if (!empty($GLOBALS['output'])) {
97 // Extension 'rewrite' installed?
98 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
99 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
102 // Send all HTTP headers
105 // Compile and run finished rendered HTML code
106 compileFinalOutput();
108 // Output code here, DO NOT REMOVE! ;-)
109 outputRawCode($GLOBALS['output']);
110 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
111 // Rewrite links when rewrite extension is active
112 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
113 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
116 // Send all HTTP headers
119 // Compile and run finished rendered HTML code
120 compileFinalOutput();
122 // Output code here, DO NOT REMOVE! ;-)
123 outputRawCode($GLOBALS['output']);
125 // And flush all headers
130 // Sends out all headers required for HTTP/1.1 reply
131 function sendHttpHeaders () {
133 $now = gmdate('D, d M Y H:i:s') . ' GMT';
136 sendHeader('HTTP/1.1 200');
138 // General headers for no caching
139 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
140 sendHeader('Last-Modified: ' . $now);
141 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
142 sendHeader('Pragma: no-cache'); // HTTP/1.0
143 sendHeader('Connection: Close');
144 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
145 sendHeader('Content-Language: ' . getLanguage());
148 // Compiles the final output
149 function compileFinalOutput () {
154 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
155 // Init common variables
160 $eval = "\$newContent = \"".compileCode(escapeQuotes($GLOBALS['output']))."\";";
163 // Was that eval okay?
164 if (empty($newContent)) {
165 // Something went wrong!
166 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
168 $GLOBALS['output'] = $newContent;
175 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
176 // Compress it for HTTP gzip
177 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
180 sendHeader('Content-Encoding: gzip');
181 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
182 // Compress it for HTTP deflate
183 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
186 sendHeader('Content-Encoding: deflate');
190 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
196 // Output the raw HTML code
197 function outputRawCode ($htmlCode) {
198 // Output stripped HTML code to avoid broken JavaScript code, etc.
199 print(str_replace('{BACK}', "\\", $htmlCode));
201 // Flush the output if only getPhpCaching() is not 'on'
202 if (getPhpCaching() != 'on') {
208 // Init fatal message array
209 function initFatalMessages () {
210 $GLOBALS['fatal_messages'] = array();
213 // Getter for whole fatal error messages
214 function getFatalArray () {
215 return $GLOBALS['fatal_messages'];
218 // Add a fatal error message to the queue array
219 function addFatalMessage ($F, $L, $message, $extra = '') {
220 if (is_array($extra)) {
221 // Multiple extras for a message with masks
222 $message = call_user_func_array('sprintf', $extra);
223 } elseif (!empty($extra)) {
224 // $message is text with a mask plus extras to insert into the text
225 $message = sprintf($message, $extra);
228 // Add message to $GLOBALS['fatal_messages']
229 $GLOBALS['fatal_messages'][] = $message;
231 // Log fatal messages away
232 debug_report_bug($message);
233 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
236 // Getter for total fatal message count
237 function getTotalFatalErrors () {
241 // Do we have at least the first entry?
242 if (!empty($GLOBALS['fatal_messages'][0])) {
244 $count = count($GLOBALS['fatal_messages']);
251 // Load a template file and return it's content (only it's name; do not use ' or ")
252 function loadTemplate ($template, $return = false, $content = array()) {
253 // @TODO Remove this sanity-check if all is fine
254 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
256 // @TODO Try to rewrite all $DATA to $content
260 if (isTemplateCached($template)) {
261 // Evaluate the cache
262 eval(readTemplateCache($template));
263 } elseif (!isset($GLOBALS['template_eval'][$template])) {
264 // Add more variables which you want to use in your template files
265 $username = getUsername();
267 // Make all template names lowercase
268 $template = strtolower($template);
272 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
275 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
276 $extraPath = detectExtraTemplatePath($template);;
278 ////////////////////////
279 // Generate file name //
280 ////////////////////////
281 $FQFN = $basePath . $extraPath . $template . '.tpl';
283 // Does the special template exists?
284 if (!isFileReadable($FQFN)) {
285 // Reset to default template
286 $FQFN = $basePath . $template . '.tpl';
289 // Now does the final template exists?
290 if (isFileReadable($FQFN)) {
291 // Count the template load
292 incrementConfigEntry('num_templates');
294 // The local file does exists so we load it. :)
295 $GLOBALS['tpl_content'] = readFromFile($FQFN);
297 // Do we have to compile the code?
299 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
300 // Normal HTML output?
301 if (getOutputMode() == '0') {
302 // Add surrounding HTML comments to help finding bugs faster
303 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
305 // Prepare eval() command
306 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
307 } elseif (substr($template, 0, 3) == 'js_') {
308 // JavaScripts don't like entities and timings
309 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
311 // Prepare eval() command, other output doesn't like entities, maybe
312 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
315 // Add surrounding HTML comments to help finding bugs faster
316 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
317 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
320 // Cache the eval() command here
321 $GLOBALS['template_eval'][$template] = $eval;
324 eval($GLOBALS['template_eval'][$template]);
325 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
326 // Only admins shall see this warning or when installation mode is active
327 $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
328 (' . $template . ')<br />
330 {--TEMPLATE_CONTENT--}
331 <pre>' . print_r($content, true) . '</pre>
333 <pre>' . print_r($DATA, true) . '</pre>
337 $GLOBALS['template_eval'][$template] = '404';
341 eval($GLOBALS['template_eval'][$template]);
344 // Do we have some content to output or return?
346 // Not empty so let's put it out! ;)
347 if ($return === true) {
348 // Return the HTML code
354 } elseif (isDebugModeEnabled()) {
355 // Warning, empty output!
356 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
360 // Detects the extra template path from given template name
361 function detectExtraTemplatePath ($template) {
366 if (!isset($GLOBALS['extra_path'][$template])) {
367 // Check for admin/guest/member/etc. templates
368 if (substr($template, 0, 6) == 'admin_') {
369 // Admin template found
370 $extraPath = 'admin/';
371 } elseif (substr($template, 0, 6) == 'guest_') {
372 // Guest template found
373 $extraPath = 'guest/';
374 } elseif (substr($template, 0, 7) == 'member_') {
375 // Member template found
376 $extraPath = 'member/';
377 } elseif (substr($template, 0, 7) == 'select_') {
378 // Selection template found
379 $extraPath = 'select/';
380 } elseif (substr($template, 0, 8) == 'install_') {
381 // Installation template found
382 $extraPath = 'install/';
383 } elseif (substr($template, 0, 4) == 'ext_') {
384 // Extension template found
386 } elseif (substr($template, 0, 3) == 'la_') {
387 // 'Logical-area' template found
389 } elseif (substr($template, 0, 3) == 'js_') {
390 // JavaScript template found
392 } elseif (substr($template, 0, 5) == 'menu_') {
393 // Menu template found
394 $extraPath = 'menu/';
396 // Test for extension
397 $test = substr($template, 0, strpos($template, '_'));
399 // Probe for valid extension name
400 if (isExtensionNameValid($test)) {
401 // Set extra path to extension's name
402 $extraPath = $test . '/';
407 $GLOBALS['extra_path'][$template] = $extraPath;
411 return $GLOBALS['extra_path'][$template];
414 // Loads an email template and compiles it
415 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
418 // Make sure all template names are lowercase!
419 $template = strtolower($template);
421 // Default 'nickname' if extension is not installed
424 // Neutral email address is default
425 $email = getConfig('WEBMASTER');
427 // Is content an array?
428 if (is_array($content)) {
429 // Add expiration to array
430 if (getConfig('auto_purge') == '0') {
431 // Will never expire!
432 $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
434 // Create nice date string
435 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
440 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$userid},template={$template},content[]=".gettype($content).'<br />');
441 if (($userid > 0) && (is_array($content))) {
442 // If nickname extension is installed, fetch nickname as well
443 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
444 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
446 fetchUserData($userid, 'nickname');
448 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
450 fetchUserData($userid);
453 // Merge data if valid
454 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
455 if (isUserDataValid()) {
456 $content = merge_array($content, getUserDataArray());
458 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
461 // Translate M to male or F to female if present
462 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
464 // Overwrite email from data if present
465 if (isset($content['email'])) $email = $content['email'];
467 // Store email for some functions in global data array
468 // @TODO Do only use $content, not $DATA or raw variables
469 $DATA['email'] = $email;
472 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
475 $extraPath = detectExtraTemplatePath($template);
477 // Generate full FQFN
478 $FQFN = $basePath . $extraPath . $template . '.tpl';
480 // Does the special template exists?
481 if (!isFileReadable($FQFN)) {
482 // Reset to default template
483 $FQFN = $basePath . $template . '.tpl';
486 // Now does the final template exists?
488 if (isFileReadable($FQFN)) {
489 // The local file does exists so we load it. :)
490 $GLOBALS['tpl_content'] = readFromFile($FQFN);
493 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileRawCode(escapeQuotes($GLOBALS['tpl_content']))."\");";
494 eval($GLOBALS['tpl_content']);
495 } elseif (!empty($template)) {
496 // Template file not found!
497 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
498 {--TEMPLATE_CONTENT--}
499 <pre>' . print_r($content, true) . '</pre>
501 <pre>' . print_r($DATA, true) . '</pre>
504 // Debug mode not active? Then remove the HTML tags
505 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
507 // No template name supplied!
508 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
511 // Is there some content?
512 if (empty($newContent)) {
514 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
516 // Add last error if the required function exists
517 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
520 // Remove content and data
528 // Send mail out to an email address
529 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
530 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
532 // Compile subject line (for POINTS constant etc.)
533 eval("\$subject = decodeEntities(\"".compileRawCode(escapeQuotes($subject))."\");");
536 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
537 // Value detected, is the message extension installed?
538 // @TODO Extension 'msg' does not exist
539 if (isExtensionActive('msg')) {
540 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
543 // Does the user exist?
544 if (fetchUserData($toEmail)) {
546 $toEmail = getUserData('email');
549 $toEmail = getConfig('WEBMASTER');
552 } elseif ($toEmail == '0') {
554 $toEmail = getConfig('WEBMASTER');
556 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
558 // Check for PHPMailer or debug-mode
559 if (!checkPhpMailerUsage()) {
560 // Not in PHPMailer-Mode
561 if (empty($mailHeader)) {
562 // Load email header template
563 $mailHeader = loadEmailTemplate('header');
566 $mailHeader .= loadEmailTemplate('header');
568 } elseif (isDebugModeEnabled()) {
569 if (empty($mailHeader)) {
570 // Load email header template
571 $mailHeader = loadEmailTemplate('header');
574 $mailHeader .= loadEmailTemplate('header');
579 eval("\$toEmail = \"".compileRawCode(escapeQuotes($toEmail))."\";");
582 eval("\$message = \"".str_replace('$', '$', compileRawCode(escapeQuotes($message)))."\";");
584 // Fix HTML parameter (default is no!)
585 if (empty($isHtml)) $isHtml = 'N';
586 if (isDebugModeEnabled()) {
587 // In debug mode we want to display the mail instead of sending it away so we can debug this part
589 Headers : ' . htmlentities(trim($mailHeader)) . '
590 To : ' . htmlentities($toEmail) . '
591 Subject : ' . htmlentities($subject) . '
592 Message : ' . htmlentities($message) . '
594 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
595 // Send mail as HTML away
596 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
597 } elseif (!empty($toEmail)) {
599 sendRawEmail($toEmail, $subject, $message, $mailHeader);
600 } elseif ($isHtml != 'Y') {
602 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
606 // Check to use wether legacy mail() command or PHPMailer class
607 // @TODO Rewrite this to an extension 'smtp'
609 function checkPhpMailerUsage() {
610 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
613 // Send out a raw email with PHPMailer class or legacy mail() command
614 function sendRawEmail ($toEmail, $subject, $message, $from) {
615 // Just compile all again, to put out all configs, etc.
616 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
617 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
618 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
619 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
621 // Shall we use PHPMailer class or legacy mode?
622 if (checkPhpMailerUsage()) {
623 // Use PHPMailer class with SMTP enabled
624 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
625 loadIncludeOnce('inc/phpmailer/class.smtp.php');
628 $mail = new PHPMailer();
630 // Set charset to UTF-8
631 $mail->CharSet('UTF-8');
633 // Path for PHPMailer
634 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
637 $mail->SMTPAuth = true;
638 $mail->Host = getConfig('SMTP_HOSTNAME');
640 $mail->Username = getConfig('SMTP_USER');
641 $mail->Password = getConfig('SMTP_PASSWORD');
643 $mail->From = getConfig('WEBMASTER');
647 $mail->FromName = getConfig('MAIN_TITLE');
648 $mail->Subject = $subject;
649 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
650 $mail->Body = $message;
651 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
652 $mail->WordWrap = 70;
655 $mail->Body = decodeEntities($message);
657 $mail->AddAddress($toEmail, '');
658 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
659 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
660 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
663 // Use legacy mail() command
664 mail($toEmail, $subject, decodeEntities($message), $from);
668 // Generate a password in a specified length or use default password length
669 function generatePassword ($length = '0') {
670 // Auto-fix invalid length of zero
671 if ($length == '0') $length = getConfig('pass_len');
673 // Initialize array with all allowed chars
674 $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,-,+,_,/,.');
676 // Start creating password
678 for ($i = '0'; $i < $length; $i++) {
679 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
682 // When the size is below 40 we can also add additional security by scrambling
683 // it. Otherwise we may corrupt hashes
684 if (strlen($PASS) <= 40) {
685 // Also scramble the password
686 $PASS = scrambleString($PASS);
689 // Return the password
693 // Generates a human-readable timestamp from the Uni* stamp
694 function generateDateTime ($time, $mode = '0') {
695 // Filter out numbers
696 $time = bigintval($time);
698 // If the stamp is zero it mostly didn't "happen"
701 return getMessage('NEVER_HAPPENED');
704 switch (getLanguage()) {
705 case 'de': // German date / time format
707 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
708 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
709 case '2': $ret = date('d.m.Y|H:i', $time); break;
710 case '3': $ret = date('d.m.Y', $time); break;
712 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
717 default: // Default is the US date / time format!
719 case '0': $ret = date('r', $time); break;
720 case '1': $ret = date('Y-m-d - g:i A', $time); break;
721 case '2': $ret = date('y-m-d|H:i', $time); break;
722 case '3': $ret = date('y-m-d', $time); break;
724 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
733 // Translates Y/N to yes/no
734 function translateYesNo ($yn) {
736 $translated = '??? (' . $yn . ')';
738 case 'Y': $translated = getMessage('YES'); break;
739 case 'N': $translated = getMessage('NO'); break;
742 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
750 // Translates the "pool type" into human-readable
751 function translatePoolType ($type) {
752 // Default?type is unknown
753 $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
756 $constName = sprintf("POOL_TYPE_%s", $type);
759 if (isMessageIdValid($constName)) {
761 $translated = getMessage($constName);
764 // Return "translation"
768 // Translates the american decimal dot into a german comma
769 function translateComma ($dotted, $cut = true, $max = '0') {
770 // Default is 3 you can change this in admin area "Misc -> Misc Options"
771 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
773 // Use from config is default
774 $maxComma = getConfig('max_comma');
776 // Use from parameter?
777 if ($max > 0) $maxComma = $max;
780 if (($cut === true) && ($max == '0')) {
781 // Test for commata if in cut-mode
782 $com = explode('.', $dotted);
783 if (count($com) < 2) {
784 // Don't display commatas even if there are none... ;-)
790 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
793 switch (getLanguage()) {
794 case 'de': // German language
795 $dotted = number_format($dotted, $maxComma, ',', '.');
798 default: // All others
799 $dotted = number_format($dotted, $maxComma, '.', ',');
803 // Return translated value
807 // Translate Uni*-like gender to human-readable
808 function translateGender ($gender) {
810 $ret = '!' . $gender . '!';
812 // Male/female or company?
814 case 'M': $ret = getMessage('GENDER_M'); break;
815 case 'F': $ret = getMessage('GENDER_F'); break;
816 case 'C': $ret = getMessage('GENDER_C'); break;
818 // Log unknown gender
819 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
823 // Return translated gender
827 // "Translates" the user status
828 function translateUserStatus ($status) {
829 // Generate message depending on status
834 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
839 $ret = getMessage('ACCOUNT_DELETED');
843 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
844 $ret = getMaskedMessage('UNKNOWN_STATUS', $status);
852 // Generates an URL for the dereferer
853 function generateDerefererUrl ($URL) {
854 // Don't de-refer our own links!
855 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
856 // De-refer this link
857 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
864 // Generates an URL for the frametester
865 function generateFrametesterUrl ($URL) {
866 // Prepare frametester URL
867 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
868 encodeString(compileUriCode($URL))
871 // Return the new URL
872 return $frametesterUrl;
875 // Count entries from e.g. a selection box
876 function countSelection ($array) {
878 if (!is_array($array)) {
880 debug_report_bug(__FUNCTION__.': No array provided.');
887 foreach ($array as $key => $selected) {
889 if (!empty($selected)) $ret++;
892 // Return counted selections
896 // Generate XHTML code for the CAPTCHA
897 function generateCaptchaCode ($code, $type, $DATA, $userid) {
898 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
901 // Generates a timestamp (some wrapper for mktime())
902 function makeTime ($hours, $minutes, $seconds, $stamp) {
903 // Extract day, month and year from given timestamp
904 $days = date('d', $stamp);
905 $months = date('m', $stamp);
906 $years = date('Y', $stamp);
908 // Create timestamp for wished time which depends on extracted date
919 // Redirects to an URL and if neccessarry extends it with own base URL
920 function redirectToUrl ($URL) {
922 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
924 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
925 $rel = ' rel="external"';
927 // Do we have internal or external URL?
928 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
929 // Own (=internal) URL
933 // Three different ways to debug...
934 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
935 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
936 //* DEBUG: */ die($URL);
938 // Simple probe for bots/spiders from search engines
940 // Secure the URL against bad things such als HTML insertions and so on...
941 $URL = secureString($URL);
943 // Output new location link as anchor
944 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
945 } elseif (!headers_sent()) {
946 // Clear own output buffer
947 $GLOBALS['output'] = '';
949 // Load URL when headers are not sent
950 sendHeader('Location: '.str_replace('&', '&', $URL));
952 // Output error message
953 loadInclude('inc/header.php');
954 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
955 loadInclude('inc/footer.php');
958 // Shut the mailer down here
962 // Wrapper for redirectToUrl but URL comes from a configuration entry
963 function redirectToConfiguredUrl ($configEntry) {
965 $URL = getConfig($configEntry);
970 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
977 // Compiles the given HTML/mail code
978 function compileCode ($code, $simple = false, $constants = true, $full = true) {
979 // Is the code a string?
980 if (!is_string($code)) {
981 // Silently return it
986 $startCompile = microtime(true);
989 $code = compileRawCode($code, $simple, $constants, $full);
992 $compiled = microtime(true);
995 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
997 // Return compiled code
1001 // Compiles the code (use compileCode() only for HTML because of the comments)
1002 // @TODO $simple is deprecated
1003 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1004 // Is the code a string?
1005 if (!is_string($code)) {
1006 // Silently return it
1010 // Init replacement-array with smaller set of security characters
1011 $secChars = $GLOBALS['url_chars'];
1013 // Select full set of chars to replace when we e.g. want to compile URLs
1014 if ($full === true) $secChars = $GLOBALS['security_chars'];
1016 // Compile more through a filter
1017 $code = runFilterChain('compile_code', $code);
1019 // Compile constants
1020 if ($constants === true) {
1021 // BEFORE 0.2.1 : Language and data constants
1022 // WITH 0.2.1+ : Only language constants
1023 $code = str_replace('{--', "\" . getMessage('", str_replace('--}', "') . \"", $code));
1025 // BEFORE 0.2.1 : Not used
1026 // WITH 0.2.1+ : Data constants
1027 $code = str_replace('{!', "\" . constant('", str_replace('!}', "') . \"", $code));
1030 // Compile QUOT and other non-HTML codes
1031 foreach ($secChars['to'] as $k => $to) {
1032 // Do the reversed thing as in inc/libs/security_functions.php
1033 $code = str_replace($to, $secChars['from'][$k], $code);
1036 // Find $content[bla][blub] entries
1037 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1038 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1040 // Are some matches found?
1041 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1042 // Replace all matches
1043 $matchesFound = array();
1044 foreach ($matches[0] as $key => $match) {
1045 // Fuzzy look has failed by default
1046 $fuzzyFound = false;
1048 // Fuzzy look on match if already found
1049 foreach ($matchesFound as $found => $set) {
1051 $test = substr($found, 0, strlen($match));
1053 // Does this entry exist?
1054 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1055 if ($test == $match) {
1057 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1064 if ($fuzzyFound === true) continue;
1066 // Take all string elements
1067 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1068 // Replace it in the code
1069 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1070 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1071 $code = str_replace($match, '".' . $newMatch . '."', $code);
1072 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1073 $matchesFound[$match] = 1;
1074 } elseif (!isset($matchesFound[$match])) {
1075 // Not yet replaced!
1076 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1077 $code = str_replace($match, '".' . $match . '."', $code);
1078 $matchesFound[$match] = 1;
1087 /************************************************************************
1089 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1090 * $a_sort sortiert: *
1092 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1093 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1094 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1095 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1096 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1098 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1099 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1100 * Sie, dass es doch nicht so schwer ist! :-) *
1102 ************************************************************************/
1103 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1105 while ($primary_key < count($a_sort)) {
1106 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1107 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1109 if ($nums === false) {
1110 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1111 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1112 } elseif ($key != $key2) {
1113 // Sort numbers (E.g.: 9 < 10)
1114 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1115 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1119 // We have found two different values, so let's sort whole array
1120 foreach ($dummy as $sort_key => $sort_val) {
1121 $t = $dummy[$sort_key][$key];
1122 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1123 $dummy[$sort_key][$key2] = $t;
1134 // Write back sorted array
1139 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1142 if ($type == 'yn') {
1143 // This is a yes/no selection only!
1144 if ($id > 0) $prefix .= "[" . $id."]";
1145 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1147 // Begin with regular selection box here
1148 if (!empty($prefix)) $prefix .= "_";
1150 if ($id > 0) $type2 .= "[" . $id."]";
1151 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1156 for ($idx = 1; $idx < 32; $idx++) {
1157 $OUT .= "<option value=\"" . $idx."\"";
1158 if ($default == $idx) $OUT .= ' selected="selected"';
1159 $OUT .= ">" . $idx."</option>\n";
1163 case 'month': // Month
1164 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1165 $OUT .= "<option value=\"" . $month."\"";
1166 if ($default == $month) $OUT .= ' selected="selected"';
1167 $OUT .= ">" . $descr."</option>\n";
1171 case 'year': // Year
1173 $year = date('Y', time());
1175 // Use configured min age or fixed?
1176 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1178 $startYear = $year - getConfig('min_age');
1181 $startYear = $year - 16;
1184 // Calculate earliest year (100 years old people can still enter Internet???)
1185 $minYear = $year - 100;
1187 // Check if the default value is larger than minimum and bigger than actual year
1188 if (($default > $minYear) && ($default >= $year)) {
1189 for ($idx = $year; $idx < ($year + 11); $idx++) {
1190 $OUT .= "<option value=\"" . $idx."\"";
1191 if ($default == $idx) $OUT .= ' selected="selected"';
1192 $OUT .= ">" . $idx."</option>\n";
1194 } elseif ($default == -1) {
1195 // Current year minus 1
1196 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1198 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1201 // Get current year and subtract the configured minimum age
1202 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1203 // Calculate earliest year depending on extension version
1204 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1205 // Use configured minimum age
1206 $year = date('Y', time()) - getConfig('min_age');
1208 // Use fixed 16 years age
1209 $year = date('Y', time()) - 16;
1212 // Construct year selection list
1213 for ($idx = $minYear; $idx <= $year; $idx++) {
1214 $OUT .= "<option value=\"" . $idx."\"";
1215 if ($default == $idx) $OUT .= ' selected="selected"';
1216 $OUT .= ">" . $idx."</option>\n";
1223 for ($idx = '0'; $idx < 60; $idx+=5) {
1224 if (strlen($idx) == 1) $idx = '0' . $idx;
1225 $OUT .= "<option value=\"" . $idx."\"";
1226 if ($default == $idx) $OUT .= ' selected="selected"';
1227 $OUT .= ">" . $idx."</option>\n";
1232 for ($idx = '0'; $idx < 24; $idx++) {
1233 if (strlen($idx) == 1) $idx = '0' . $idx;
1234 $OUT .= "<option value=\"" . $idx."\"";
1235 if ($default == $idx) $OUT .= ' selected="selected"';
1236 $OUT .= ">" . $idx."</option>\n";
1241 $OUT .= "<option value=\"Y\"";
1242 if ($default == 'Y') $OUT .= ' selected="selected"';
1243 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1244 if ($default != 'Y') $OUT .= ' selected="selected"';
1245 $OUT .= ">{--NO--}</option>\n";
1248 $OUT .= " </select>\n";
1253 // Deprecated : $length
1256 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1257 // Build server string
1258 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1261 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1262 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1263 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1264 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1265 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1267 // Build string from misc data
1268 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1270 // Add more additional data
1271 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1273 // Add referal id, language, theme and userid
1274 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1275 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1276 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1277 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1279 // Calculate number for generating the code
1280 $a = $code + getConfig('_ADD') - 1;
1282 if (isConfigEntrySet('master_salt')) {
1283 // Generate hash with master salt from modula of number with the prime number and other data
1284 $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'));
1286 // Create number from hash
1287 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1289 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1290 $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')));
1292 // Create number from hash
1293 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1296 // At least 10 numbers shall be secure enought!
1297 $len = getConfig('code_length');
1298 if ($len == '0') $len = $length;
1299 if ($len == '0') $len = 10;
1301 // Cut off requested counts of number
1302 $return = substr(str_replace('.', '', $rcode), 0, $len);
1304 // Done building code
1308 // Does only allow numbers
1309 function bigintval ($num, $castValue = true) {
1310 // Filter all numbers out
1311 $ret = preg_replace('/[^0123456789]/', '', $num);
1314 if ($castValue === true) $ret = (double)$ret;
1316 // Has the whole value changed?
1317 if ('' . $ret . '' != '' . $num . '') {
1319 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1326 // Insert the code in $img_code into jpeg or PNG image
1327 function generateImageOrCode ($img_code, $headerSent = true) {
1328 // Is the code size oversized or shouldn't we display it?
1329 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1330 // Stop execution of function here because of over-sized code length
1331 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1332 } elseif ($headerSent === false) {
1333 // Return an HTML code here
1334 return "<img src=\"{%url=img.php?code=" . $img_code."%}\" alt=\"Image\" />\n";
1338 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1341 getConfig('img_type')
1345 if (isFileReadable($img)) {
1346 // Switch image type
1347 switch (getConfig('img_type'))
1350 // Okay, load image and hide all errors
1351 $image = imagecreatefromjpeg($img);
1355 // Okay, load image and hide all errors
1356 $image = imagecreatefrompng($img);
1360 // Exit function here
1361 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1365 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1366 $text_color = imagecolorallocate($image, 0, 0, 0);
1368 // Insert code into image
1369 imagestring($image, 5, 14, 2, $img_code, $text_color);
1371 // Return to browser
1372 sendHeader('Content-Type: image/' . getConfig('img_type'));
1374 // Output image with matching image factory
1375 switch (getConfig('img_type')) {
1376 case 'jpg': imagejpeg($image); break;
1377 case 'png': imagepng($image); break;
1380 // Remove image from memory
1381 imagedestroy($image);
1383 // Create selection box or array of splitted timestamp
1384 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1385 // Calculate 2-seconds timestamp
1386 $stamp = round($timestamp);
1387 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1389 // Do we have a leap year?
1391 $TEST = date('Y', time()) / 4;
1392 $M1 = date('m', time());
1393 $M2 = date('m', (time() + $timestamp));
1395 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1396 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1398 // First of all years...
1399 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1400 //* DEBUG: */ print("Y={$Y}<br />");
1402 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1403 //* DEBUG: */ print("M={$M}<br />");
1405 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1406 //* DEBUG: */ print("W={$W}<br />");
1408 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1409 //* DEBUG: */ print("D={$D}<br />");
1411 $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));
1412 //* DEBUG: */ print("h={$h}<br />");
1414 $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));
1415 //* DEBUG: */ print("m={$m}<br />");
1416 // And at last seconds...
1417 $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));
1418 //* DEBUG: */ print("s={$s}<br />");
1420 // Is seconds zero and time is < 60 seconds?
1421 if (($s == '0') && ($timestamp < 60)) {
1423 $s = round($timestamp);
1427 // Now we convert them in seconds...
1429 if ($return_array) {
1430 // Just put all data in an array for later use
1442 $OUT = "<div align=\"" . $align."\">\n";
1443 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"timebox_table dashed\">\n";
1446 if (ereg('Y', $display) || (empty($display))) {
1447 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1450 if (ereg('M', $display) || (empty($display))) {
1451 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1454 if (ereg('W', $display) || (empty($display))) {
1455 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1458 if (ereg('D', $display) || (empty($display))) {
1459 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1462 if (ereg('h', $display) || (empty($display))) {
1463 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1466 if (ereg('m', $display) || (empty($display))) {
1467 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1470 if (ereg('s', $display) || (empty($display))) {
1471 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1477 if (ereg('Y', $display) || (empty($display))) {
1478 // Generate year selection
1479 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ye\" size=\"1\">\n";
1480 for ($idx = '0'; $idx <= 10; $idx++) {
1481 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1482 if ($idx == $Y) $OUT .= ' selected="selected"';
1483 $OUT .= ">" . $idx."</option>\n";
1485 $OUT .= " </select></td>\n";
1487 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1490 if (ereg('M', $display) || (empty($display))) {
1491 // Generate month selection
1492 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mo\" size=\"1\">\n";
1493 for ($idx = '0'; $idx <= 11; $idx++)
1495 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1496 if ($idx == $M) $OUT .= ' selected="selected"';
1497 $OUT .= ">" . $idx."</option>\n";
1499 $OUT .= " </select></td>\n";
1501 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1504 if (ereg('W', $display) || (empty($display))) {
1505 // Generate week selection
1506 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_we\" size=\"1\">\n";
1507 for ($idx = '0'; $idx <= 4; $idx++) {
1508 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1509 if ($idx == $W) $OUT .= ' selected="selected"';
1510 $OUT .= ">" . $idx."</option>\n";
1512 $OUT .= " </select></td>\n";
1514 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1517 if (ereg('D', $display) || (empty($display))) {
1518 // Generate day selection
1519 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_da\" size=\"1\">\n";
1520 for ($idx = '0'; $idx <= 31; $idx++) {
1521 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1522 if ($idx == $D) $OUT .= ' selected="selected"';
1523 $OUT .= ">" . $idx."</option>\n";
1525 $OUT .= " </select></td>\n";
1527 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1530 if (ereg('h', $display) || (empty($display))) {
1531 // Generate hour selection
1532 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ho\" size=\"1\">\n";
1533 for ($idx = '0'; $idx <= 23; $idx++) {
1534 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1535 if ($idx == $h) $OUT .= ' selected="selected"';
1536 $OUT .= ">" . $idx."</option>\n";
1538 $OUT .= " </select></td>\n";
1540 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1543 if (ereg('m', $display) || (empty($display))) {
1544 // Generate minute selection
1545 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mi\" size=\"1\">\n";
1546 for ($idx = '0'; $idx <= 59; $idx++) {
1547 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1548 if ($idx == $m) $OUT .= ' selected="selected"';
1549 $OUT .= ">" . $idx."</option>\n";
1551 $OUT .= " </select></td>\n";
1553 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1556 if (ereg('s', $display) || (empty($display))) {
1557 // Generate second selection
1558 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_se\" size=\"1\">\n";
1559 for ($idx = '0'; $idx <= 59; $idx++) {
1560 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1561 if ($idx == $s) $OUT .= ' selected="selected"';
1562 $OUT .= ">" . $idx."</option>\n";
1564 $OUT .= " </select></td>\n";
1566 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1569 $OUT .= "</table>\n";
1571 // Return generated HTML code
1577 function createTimestampFromSelections ($prefix, $postData) {
1578 // Initial return value
1581 // Do we have a leap year?
1583 $TEST = date('Y', time()) / 4;
1584 $M1 = date('m', time());
1585 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1586 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
1587 // First add years...
1588 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1590 $ret += $postData[$prefix . '_mo'] * 2628000;
1592 $ret += $postData[$prefix . '_we'] * 604800;
1594 $ret += $postData[$prefix . '_da'] * 86400;
1596 $ret += $postData[$prefix . '_ho'] * 3600;
1598 $ret += $postData[$prefix . '_mi'] * 60;
1599 // And at last seconds...
1600 $ret += $postData[$prefix . '_se'];
1601 // Return calculated value
1605 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1606 function createFancyTime ($stamp) {
1607 // Get data array with years/months/weeks/days/...
1608 $data = createTimeSelections($stamp, '', '', '', true);
1610 foreach($data as $k => $v) {
1612 // Value is greater than 0 "eval" data to return string
1613 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1618 // Do we have something there?
1619 if (strlen($ret) > 0) {
1620 // Remove leading commata and space
1621 $ret = substr($ret, 2);
1624 $ret = "0 {--_SECONDS--}";
1627 // Return fancy time string
1631 // Generates a navigation row for listing emails
1632 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1633 $SEP = ''; $TOP = '';
1634 if ($show_form === false) {
1636 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1640 for ($page = 1; $page <= $PAGES; $page++) {
1641 // Is the page currently selected or shall we generate a link to it?
1642 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1643 // Is currently selected, so only highlight it
1644 $NAV .= '<strong>-';
1646 // Open anchor tag and add base URL
1647 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1649 // Add userid when we shall show all mails from a single member
1650 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1652 // Close open anchor tag
1656 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1657 // Is currently selected, so only highlight it
1658 $NAV .= '-</strong>';
1664 // Add seperator if we have not yet reached total pages
1665 if ($page < $PAGES) $NAV .= ' | ';
1668 // Define constants only once
1669 $content['nav'] = $NAV;
1670 $content['span'] = $colspan;
1671 $content['top'] = $TOP;
1672 $content['sep'] = $SEP;
1674 // Load navigation template
1675 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1677 if ($return === true) {
1678 // Return generated HTML-Code
1686 // Extract host from script name
1687 function extractHostnameFromUrl (&$script) {
1688 // Use default SERVER_URL by default... ;) So?
1689 $url = getConfig('SERVER_URL');
1691 // Is this URL valid?
1692 if (substr($script, 0, 7) == 'http://') {
1693 // Use the hostname from script URL as new hostname
1694 $url = substr($script, 7);
1695 $extract = explode('/', $url);
1697 // Done extracting the URL :)
1700 // Extract host name
1701 $host = str_replace('http://', '', $url);
1702 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1704 // Generate relative URL
1705 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1706 if (substr(strtolower($script), 0, 7) == 'http://') {
1707 // But only if http:// is in front!
1708 $script = substr($script, (strlen($url) + 7));
1709 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1711 $script = substr($script, (strlen($url) + 8));
1714 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1715 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1721 // Send a GET request
1722 function sendGetRequest ($script, $data = array()) {
1723 // Extract host name from script
1724 $host = extractHostnameFromUrl($script);
1727 $body = http_build_query($data, '', '&');
1729 // Do we have a question-mark in the script?
1730 if (strpos($script, '?') === false) {
1731 // No, so first char must be question mark
1732 $body = '?' . $body;
1735 $body = '&' . $body;
1741 // Generate GET request header
1742 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1743 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1744 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1745 if (isConfigEntrySet('FULL_VERSION')) {
1746 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1748 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1750 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1751 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1752 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1753 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1754 $request .= 'Content-Length: '.strlen($body) . getConfig('HTTP_EOL');
1755 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1757 // Send the raw request
1758 $response = sendRawRequest($host, $request);
1760 // Return the result to the caller function
1764 // Send a POST request
1765 function sendPostRequest ($script, $postData) {
1766 // Is postData an array?
1767 if (!is_array($postData)) {
1769 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1770 return array('', '', '');
1773 // Extract host name from script
1774 $host = extractHostnameFromUrl($script);
1776 // Construct request
1777 $body = http_build_query($postData, '', '&');
1779 // Generate POST request header
1780 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1781 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1782 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1783 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1784 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1785 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1786 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1789 // Send the raw request
1790 $response = sendRawRequest($host, $request);
1792 // Return the result to the caller function
1796 // Sends a raw request to another host
1797 function sendRawRequest ($host, $request) {
1798 // Init errno and errdesc with 'all fine' values
1799 $errno = '0'; $errdesc = '';
1802 $response = array('', '', '');
1804 // Default is not to use proxy
1807 // Are proxy settins set?
1808 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1814 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1815 if ($useProxy === true) {
1816 // Connect to host through proxy connection
1817 $fp = @fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1819 // Connect to host directly
1820 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1824 if (!is_resource($fp)) {
1830 if ($useProxy === true) {
1831 // Generate CONNECT request header
1832 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.1' . getConfig('HTTP_EOL');
1833 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1835 // Use login data to proxy? (username at least!)
1836 if (getConfig('proxy_username') != '') {
1838 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
1839 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1842 // Add last new-line
1843 $proxyTunnel .= getConfig('HTTP_EOL');
1844 //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1847 fputs($fp, $proxyTunnel);
1851 // No response received
1855 // Read the first line
1856 $resp = trim(fgets($fp, 10240));
1857 $respArray = explode(' ', $resp);
1858 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1859 // Invalid response!
1865 fputs($fp, $request);
1868 while (!feof($fp)) {
1869 $response[] = trim(fgets($fp, 1024));
1875 // Skip first empty lines
1877 foreach ($resp as $idx => $line) {
1879 $line = trim($line);
1881 // Is this line empty?
1884 array_shift($response);
1886 // Abort on first non-empty line
1891 //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1893 // Proxy agent found?
1894 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1895 // Proxy header detected, so remove two lines
1896 array_shift($response);
1897 array_shift($response);
1900 // Was the request successfull?
1901 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1902 // Not found / access forbidden
1903 $response = array('', '', '');
1910 // Taken from www.php.net eregi() user comments
1911 function isEmailValid ($email) {
1912 // Check first part of email address
1913 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1916 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1919 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1921 // Return check result
1922 return preg_match($regex, $email);
1925 // Function taken from user comments on www.php.net / function eregi()
1926 function isUrlValid ($URL, $compile=true) {
1927 // Trim URL a little
1928 $URL = trim(urldecode($URL));
1929 //* DEBUG: */ outputHtml($URL.'<br />');
1931 // Compile some chars out...
1932 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1933 //* DEBUG: */ outputHtml($URL.'<br />');
1935 // Check for the extension filter
1936 if (isExtensionActive('filter')) {
1937 // Use the extension's filter set
1938 return FILTER_VALIDATE_URL($URL, false);
1941 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1942 // https:// in front of the URLs
1943 return isUrlValidSimple($URL);
1946 // Generate a list of administrative links to a given userid
1947 function generateMemberAdminActionLinks ($userid, $status = '') {
1948 // Make sure userid is a number
1949 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1951 // Define all main targets
1952 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1954 // Begin of navigation links
1957 foreach ($targetArray as $tar) {
1958 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
1959 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
1960 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1961 // Locked accounts shall be unlocked
1962 $OUT .= 'UNLOCK_USER';
1964 // All other status is fine
1965 $OUT .= strtoupper($tar);
1967 $OUT .= '_TITLE--}">{--ADMIN_';
1968 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1969 // Locked accounts shall be unlocked
1970 $OUT .= 'UNLOCK_USER';
1972 // All other status is fine
1973 $OUT .= strtoupper($tar);
1975 $OUT .= '--}</a></span> | ';
1978 // Finish navigation link
1979 $OUT = substr($OUT, 0, -7) . ']';
1985 // Generate an email link
1986 function generateEmailLink ($email, $table = 'admins') {
1987 // Default email link (INSECURE! Spammer can read this by harvester programs)
1988 $EMAIL = 'mailto:' . $email;
1990 // Check for several extensions
1991 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1992 // Create email link for contacting admin in guest area
1993 $EMAIL = generateAdminEmailLink($email);
1994 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
1995 // Create email link for contacting a member within admin area (or later in other areas, too?)
1996 $EMAIL = generateUserEmailLink($email, 'admin');
1997 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1998 // Create email link to contact sponsor within admin area (or like the link above?)
1999 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2002 // Shall I close the link when there is no admin?
2003 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2005 // Return email link
2009 // Generate a hash for extra-security for all passwords
2010 function generateHash ($plainText, $salt = '') {
2011 // Is the required extension 'sql_patches' there and a salt is not given?
2012 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2013 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2014 return md5($plainText);
2017 // Do we miss an arry element here?
2018 if (!isConfigEntrySet('file_hash')) {
2020 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2023 // When the salt is empty build a new one, else use the first x configured characters as the salt
2025 // Build server string (inc/databases.php is no longer updated with every commit)
2026 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2029 $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');
2032 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2034 // Calculate number for generating the code
2035 $a = time() + getConfig('_ADD') - 1;
2037 // Generate SHA1 sum from modula of number and the prime number
2038 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2039 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2040 $sha1 = scrambleString($sha1);
2041 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2042 //* DEBUG: */ $sha1b = descrambleString($sha1);
2043 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2045 // Generate the password salt string
2046 $salt = substr($sha1, 0, getConfig('salt_length'));
2047 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2050 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2051 $salt = substr($salt, 0, getConfig('salt_length'));
2052 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2054 // Sanity check on salt
2055 if (strlen($salt) != getConfig('salt_length')) {
2057 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2062 return $salt.sha1($salt . $plainText);
2065 // Scramble a string
2066 function scrambleString($str) {
2070 // Final check, in case of failture it will return unscrambled string
2071 if (strlen($str) > 40) {
2072 // The string is to long
2074 } elseif (strlen($str) == 40) {
2076 $scrambleNums = explode(':', getConfig('pass_scramble'));
2078 // Generate new numbers
2079 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2082 // Scramble string here
2083 //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2084 for ($idx = '0'; $idx < strlen($str); $idx++) {
2085 // Get char on scrambled position
2086 $char = substr($str, $scrambleNums[$idx], 1);
2088 // Add it to final output string
2089 $scrambled .= $char;
2092 // Return scrambled string
2093 //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2097 // De-scramble a string scrambled by scrambleString()
2098 function descrambleString($str) {
2099 // Scramble only 40 chars long strings
2100 if (strlen($str) != 40) return $str;
2102 // Load numbers from config
2103 $scrambleNums = explode(':', getConfig('pass_scramble'));
2106 if (count($scrambleNums) != 40) return $str;
2108 // Begin descrambling
2109 $orig = str_repeat(' ', 40);
2110 //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2111 for ($idx = '0'; $idx < 40; $idx++) {
2112 $char = substr($str, $idx, 1);
2113 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2116 // Return scrambled string
2117 //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2121 // Generated a "string" for scrambling
2122 function genScrambleString ($len) {
2123 // Prepare array for the numbers
2124 $scrambleNumbers = array();
2126 // First we need to setup randomized numbers from 0 to 31
2127 for ($idx = '0'; $idx < $len; $idx++) {
2129 $rand = mt_rand(0, ($len -1));
2131 // Check for it by creating more numbers
2132 while (array_key_exists($rand, $scrambleNumbers)) {
2133 $rand = mt_rand(0, ($len -1));
2137 $scrambleNumbers[$rand] = $rand;
2140 // So let's create the string for storing it in database
2141 $scrambleString = implode(':', $scrambleNumbers);
2142 return $scrambleString;
2145 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2146 function generatePassString ($passHash) {
2147 // Return vanilla password hash
2150 // Is a secret key and master salt already initialized?
2151 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2152 // Only calculate when the secret key is generated
2153 $newHash = ''; $start = 9;
2154 for ($idx = '0'; $idx < 10; $idx++) {
2155 $part1 = hexdec(substr($passHash, $start, 4));
2156 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2157 $mod = dechex($idx);
2158 if ($part1 > $part2) {
2159 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2160 } elseif ($part2 > $part1) {
2161 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2163 $mod = substr($mod, 0, 4);
2164 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2165 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2166 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2171 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2172 $ret = generateHash($newHash, getConfig('master_salt'));
2173 //* DEBUG: */ print('ret='.$ret.'<br />');
2176 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2177 $ret = md5($passHash);
2178 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2185 // Fix "deleted" cookies
2186 function fixDeletedCookies ($cookies) {
2187 // Is this an array with entries?
2188 if ((is_array($cookies)) && (count($cookies) > 0)) {
2189 // Then check all cookies if they are marked as deleted!
2190 foreach ($cookies as $cookieName) {
2191 // Is the cookie set to "deleted"?
2192 if (getSession($cookieName) == 'deleted') {
2193 setSession($cookieName, '');
2199 // Output error messages in a fasioned way and die...
2200 function app_die ($F, $L, $message) {
2201 // Check if Script is already dieing and not let it kill itself another 1000 times
2202 if (!isset($GLOBALS['app_died'])) {
2203 // Make sure, that the script realy realy diese here and now
2204 $GLOBALS['app_died'] = true;
2207 loadIncludeOnce('inc/header.php');
2209 // Rewrite message for output
2210 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2212 // Better log this message away
2213 if ($F != 'debug_report_bug') logDebugMessage($F, $L, $message);
2215 // Load the message template
2216 loadTemplate('app_die_message', false, $message);
2219 loadIncludeOnce('inc/footer.php');
2221 // Script tried to kill itself twice
2222 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2226 // Display parsing time and number of SQL queries in footer
2227 function displayParsingTime() {
2228 // Is the timer started?
2229 if (!isset($GLOBALS['startTime'])) {
2235 $endTime = microtime(true);
2237 // "Explode" both times
2238 $start = explode(' ', $GLOBALS['startTime']);
2239 $end = explode(' ', $endTime);
2240 $runTime = $end[0] - $start[0];
2241 if ($runTime < 0) $runTime = '0';
2245 'runtime' => translateComma($runTime),
2246 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2249 // Load the template
2250 loadTemplate('show_timings', false, $content);
2253 // Check wether a boolean constant is set
2254 // Taken from user comments in PHP documentation for function constant()
2255 function isBooleanConstantAndTrue ($constName) { // : Boolean
2256 // Failed by default
2260 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2262 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2263 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2266 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2267 if (defined($constName)) {
2269 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2270 $res = (constant($constName) === true);
2274 $GLOBALS['cache_array']['const'][$constName] = $res;
2276 //* DEBUG: */ var_dump($res);
2282 // Checks if a given apache module is loaded
2283 function isApacheModuleLoaded ($apacheModule) {
2284 // Check it and return result
2285 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2288 // Get current theme name
2289 function getCurrentTheme () {
2290 // The default theme is 'default'... ;-)
2293 // Do we have ext-theme installed and active?
2294 if (isExtensionActive('theme')) {
2295 // Call inner method
2296 $ret = getActualTheme();
2299 // Return theme value
2303 // Generates an error code from given account status
2304 function generateErrorCodeFromUserStatus ($status='') {
2305 // If no status is provided, use the default, cached
2306 if ((empty($status)) && (isMember())) {
2308 $status = getUserData('status');
2311 // Default error code if unknown account status
2312 $errorCode = getCode('UNKNOWN_STATUS');
2314 // Generate constant name
2315 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2317 // Is the constant there?
2318 if (isCodeSet($codeName)) {
2320 $errorCode = getCode($codeName);
2323 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2326 // Return error code
2330 // Function to search for the last modifified file
2331 function searchDirsRecursive ($dir, &$last_changed) {
2333 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2334 // Does it match what we are looking for? (We skip a lot files already!)
2335 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2336 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2337 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2338 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2340 // Walk through all entries
2341 foreach ($ds as $d) {
2342 // Generate proper FQFN
2343 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2345 // Is it a file and readable?
2346 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2347 if (isDirectory($FQFN)) {
2348 // $FQFN is a directory so also crawl into this directory
2350 if (!empty($dir)) $newDir = $dir . '/'. $d;
2351 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2352 searchDirsRecursive($newDir, $last_changed);
2353 } elseif (isFileReadable($FQFN)) {
2354 // $FQFN is a filename and no directory
2355 $time = filemtime($FQFN);
2356 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2357 if ($last_changed['time'] < $time) {
2358 // This file is newer as the file before
2359 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2360 $last_changed['path_name'] = $FQFN;
2361 $last_changed['time'] = $time;
2367 // "Getter" for revision/version data
2368 function getActualVersion ($type = 'Revision') {
2369 // By default nothing is new... ;-)
2372 // Is the cache entry there?
2373 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2374 // Found so increase cache hit
2375 incrementStatsEntry('cache_hits');
2378 return $GLOBALS['cache_array']['revision'][$type][0];
2380 // FQFN of revision file
2381 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2383 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2384 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2385 // Forced rebuild of .revision file
2388 // Check for revision file
2389 if (!isFileReadable($FQFN)) {
2390 // Not found, so we need to create it
2393 // Revision file found
2394 $ins_vers = explode("\n", readFromFile($FQFN));
2396 // Get array for mapping information
2397 $mapper = array_flip(getSearchFor());
2398 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2400 // Is the content valid?
2401 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2402 // File needs update!
2405 // Generate fake cache entry
2406 foreach ($mapper as $map => $idx) {
2407 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2410 // Return found value
2411 return trim($ins_vers[$mapper[$type]]);
2416 // Has it been updated?
2417 if ($new === true) {
2419 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2421 // ... and call recursive
2422 return getActualVersion($type);
2427 // Repares an array we are looking for
2428 // 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
2429 function getSearchFor () {
2430 // Add Revision, Date, Tag and Author
2431 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2433 // Return the created array
2437 // @TODO Please describe this function
2438 function getArrayFromActualVersion () {
2442 // Directory to start with search
2443 $last_changed = array(
2448 // Init return array
2449 $akt_vers = array();
2451 // Init value for counting the founded keywords
2454 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2455 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2458 $last_file = readFromFile($last_changed['path_name']);
2460 // Get all the keywords to search for
2461 $searchFor = getSearchFor();
2463 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2464 foreach ($searchFor as $search) {
2465 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2466 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2467 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2468 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2471 // Save the last-changed filename for debugging
2472 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2474 // at least 3 keyword-Tags are needed for propper values
2475 if ($res && $res >= 3
2476 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2477 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2478 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2479 // Prepare content witch need special treadment
2481 // Prepare timestamp for date
2482 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2483 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2485 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2486 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2487 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2491 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2492 $version = sendGetRequest('check-updates3.php');
2495 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2496 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2497 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2498 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2499 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2500 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2503 // Return prepared array
2504 return $GLOBALS['cache_array']['revision'];
2507 // Back-ported from the new ship-simu engine. :-)
2508 function debug_get_printable_backtrace () {
2510 $backtrace = "<ol>\n";
2512 // Get and prepare backtrace for output
2513 $backtraceArray = debug_backtrace();
2514 foreach ($backtraceArray as $key => $trace) {
2515 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2516 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2517 if (!isset($trace['args'])) $trace['args'] = array();
2518 $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";
2522 $backtrace .= "</ol>\n";
2524 // Return the backtrace
2528 // A mail-able backtrace
2529 function debug_get_mailable_backtrace () {
2533 // Get and prepare backtrace for output
2534 $backtraceArray = debug_backtrace();
2535 foreach ($backtraceArray as $key => $trace) {
2536 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2537 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2538 if (!isset($trace['args'])) $trace['args'] = array();
2539 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2542 // Return the backtrace
2546 // Output a debug backtrace to the user
2547 function debug_report_bug ($message = '', $sendEmail = true) {
2548 // Is this already called?
2549 if (isset($GLOBALS[__FUNCTION__])) {
2551 print 'Message:'.$message.'<br />Backtrace:<pre>';
2552 debug_print_backtrace();
2556 // Set this function as called
2557 $GLOBALS[__FUNCTION__] = true;
2562 // Is the optional message set?
2563 if (!empty($message)) {
2565 $debug = sprintf("Note: %s<br />\n",
2569 // @TODO Add a little more infos here
2570 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2574 $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>";
2575 $debug .= debug_get_printable_backtrace();
2576 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2577 $debug .= "Thank you for finding bugs.";
2579 // Send an email? (e.g. not wanted for evaluation errors)
2580 if ($sendEmail === true) {
2583 'message' => trim($message),
2584 'backtrace' => trim(debug_get_mailable_backtrace())
2587 // Send email to webmaster
2588 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2592 app_die(__FUNCTION__, __LINE__, $debug);
2595 // Generates a ***weak*** seed
2596 function generateSeed () {
2597 return microtime(true) * 100000;
2600 // Converts a message code to a human-readable message
2601 function getMessageFromErrorCode ($code) {
2605 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2606 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2607 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2608 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2609 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2610 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2611 case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2612 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2613 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2614 case getCode('ACCOUNT_LOCKED') : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2615 case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2616 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2617 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2618 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2619 case getCode('MODULE_MEM_ONLY') : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestElement('mod')); break;
2620 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2621 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2622 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2623 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2624 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2625 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2626 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2627 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2628 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2629 case getCode('MORE_RECEIVERS3') : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
2630 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2631 case getCode('UNKNOWN_ERROR') : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
2632 case getCode('UNKNOWN_STATUS') : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
2634 case getCode('ERROR_MAILID'):
2635 if (isExtensionActive('mailid', true)) {
2636 $message = getMessage('ERROR_CONFIRMING_MAIL');
2638 $message = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'mailid');
2642 case getCode('EXTENSION_PROBLEM'):
2643 if (isGetRequestElementSet('ext')) {
2644 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2646 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2650 case getCode('URL_TLOCK'):
2651 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2652 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2653 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2655 // Load timestamp from last order
2656 list($timestamp) = SQL_FETCHROW($result);
2659 SQL_FREERESULT($result);
2661 // Translate it for templates
2662 $timestamp = generateDateTime($timestamp, 1);
2664 // Calculate hours...
2665 $STD = round(getConfig('url_tlock') / 60 / 60);
2668 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2671 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2673 // Finally contruct the message
2674 // @TODO Rewrite this old lost code to a template
2675 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2676 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2677 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2681 // Missing/invalid code
2682 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2685 logDebugMessage(__FUNCTION__, __LINE__, $message);
2689 // Return the message
2693 // Compile characters which are allowed in URLs
2694 function compileUriCode ($code, $simple = true) {
2695 // Compile constants
2696 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2698 // Compile QUOT and other non-HTML codes
2699 $code = str_replace('{DOT}', '.',
2700 str_replace('{SLASH}', '/',
2701 str_replace('{QUOT}', "'",
2702 str_replace('{DOLLAR}', '$',
2703 str_replace('{OPEN_ANCHOR}', '(',
2704 str_replace('{CLOSE_ANCHOR}', ')',
2705 str_replace('{OPEN_SQR}', '[',
2706 str_replace('{CLOSE_SQR}', ']',
2707 str_replace('{PER}', '%',
2711 // Return compiled code
2715 // Function taken from user comments on www.php.net / function eregi()
2716 function isUrlValidSimple ($url) {
2718 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2720 // Allows http and https
2721 $http = "(http|https)+(:\/\/)";
2723 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2724 // Test double-domains (e.g. .de.vu)
2725 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2727 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2729 $dir = "((/)+([-_\.[:alnum:]])+)*";
2731 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2732 // ... and the string after and including question character
2733 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2734 // Pattern for URLs like http://url/dir/doc.html?var=value
2735 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2736 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2737 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2738 // Pattern for URLs like http://url/dir/?var=value
2739 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2740 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2741 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2742 // Pattern for URLs like http://url/dir/page.ext
2743 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2744 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2745 $pattern['ipdp'] = $http . $ip . $dir . $page;
2746 // Pattern for URLs like http://url/dir
2747 $pattern['d1d'] = $http . $domain1 . $dir;
2748 $pattern['d2d'] = $http . $domain2 . $dir;
2749 $pattern['ipd'] = $http . $ip . $dir;
2750 // Pattern for URLs like http://url/?var=value
2751 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2752 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2753 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2754 // Pattern for URLs like http://url?var=value
2755 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2756 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2757 $pattern['ipg12'] = $http . $ip . $getstring1;
2758 // Test all patterns
2760 foreach ($pattern as $key => $pat) {
2762 if (isDebugRegExpressionEnabled()) {
2763 // @TODO Are these convertions still required?
2764 $pat = str_replace('.', "\.", $pat);
2765 $pat = str_replace('@', "\@", $pat);
2766 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2769 // Check if expression matches
2770 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2773 if ($reg === true) break;
2776 // Return true/false
2780 // Wtites data to a config.php-style file
2781 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2782 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2783 // Initialize some variables
2789 // Is the file there and read-/write-able?
2790 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2791 $search = 'CFG: ' . $comment;
2792 $tmp = $FQFN . '.tmp';
2794 // Open the source file
2795 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2797 // Is the resource valid?
2798 if (is_resource($fp)) {
2799 // Open temporary file
2800 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2802 // Is the resource again valid?
2803 if (is_resource($fp_tmp)) {
2804 // Mark temporary file as readable
2805 $GLOBALS['file_readable'][$tmp] = true;
2808 while (!feof($fp)) {
2809 // Read from source file
2810 $line = fgets ($fp, 1024);
2812 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2815 if ($next === $seek) {
2817 $line = $prefix . $DATA . $suffix . "\n";
2823 // Write to temp file
2824 fputs($fp_tmp, $line);
2830 // Finished writing tmp file
2834 // Close source file
2837 if (($done === true) && ($found === true)) {
2838 // Copy back tmp file and delete tmp :-)
2839 copyFileVerified($tmp, $FQFN, 0644);
2840 return removeFile($tmp);
2841 } elseif ($found === false) {
2842 outputHtml('<strong>CHANGE:</strong> 404!');
2844 outputHtml('<strong>TMP:</strong> UNDONE!');
2848 // File not found, not readable or writeable
2849 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2852 // An error was detected!
2855 // Send notification to admin
2856 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2857 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2859 sendAdminsEmails($subject, $templateName, $content, $userid);
2861 // Send out out-dated way
2862 $message = loadEmailTemplate($templateName, $content, $userid);
2863 sendAdminEmails($subject, $message);
2867 // Debug message logger
2868 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2869 // Is debug mode enabled?
2870 if ((isDebugModeEnabled()) || ($force === true)) {
2872 $message = str_replace("\r", '', str_replace("\n", '', $message));
2874 // Log this message away, we better don't call app_die() here to prevent an endless loop
2875 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2876 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2881 // Handle extra values
2882 function handleExtraValues ($filterFunction, $value, $extraValue) {
2883 // Default is the value itself
2886 // Do we have a special filter function?
2887 if (!empty($filterFunction)) {
2888 // Does the filter function exist?
2889 if (function_exists($filterFunction)) {
2890 // Do we have extra parameters here?
2891 if (!empty($extraValue)) {
2892 // Put both parameters in one new array by default
2893 $args = array($value, $extraValue);
2895 // If we have an array simply use it and pre-extend it with our value
2896 if (is_array($extraValue)) {
2897 // Make the new args array
2898 $args = merge_array(array($value), $extraValue);
2901 // Call the multi-parameter call-back
2902 $ret = call_user_func_array($filterFunction, $args);
2904 // One parameter call
2905 $ret = call_user_func($filterFunction, $value);
2914 // Converts timestamp selections into a timestamp
2915 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2916 // Init test variable
2920 // Get last three chars
2921 $test = substr($id, -3);
2923 // Improved way of checking! :-)
2924 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2925 // Found a multi-selection for timings?
2926 $test = substr($id, 0, -3);
2927 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)) {
2928 // Generate timestamp
2929 $postData[$test] = createTimestampFromSelections($test, $postData);
2930 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2931 $GLOBALS['skip_config'][$test] = true;
2933 // Remove data from array
2934 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2935 unset($postData[$test . '_' . $rem]);
2946 // Reverts the german decimal comma into Computer decimal dot
2947 function convertCommaToDot ($str) {
2948 // Default float is not a float... ;-)
2951 // Which language is selected?
2952 switch (getLanguage()) {
2953 case 'de': // German language
2954 // Remove german thousand dots first
2955 $str = str_replace('.', '', $str);
2957 // Replace german commata with decimal dot and cast it
2958 $float = (float)str_replace(',', '.', $str);
2961 default: // US and so on
2962 // Remove thousand dots first and cast
2963 $float = (float)str_replace(',', '', $str);
2971 // Handle menu-depending failed logins and return the rendered content
2972 function handleLoginFailtures ($accessLevel) {
2973 // Default output is empty ;-)
2976 // Is the session data set?
2977 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
2978 // Ignore zero values
2979 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
2980 // Non-guest has login failures found, get both data and prepare it for template
2981 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
2983 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
2984 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
2988 $OUT = loadTemplate('login_failures', true, $content);
2991 // Reset session data
2992 setSession('mxchange_' . $accessLevel.'_failures', '');
2993 setSession('mxchange_' . $accessLevel.'_last_fail', '');
2996 // Return rendered content
3001 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3003 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3005 // Shall I remove the cache file?
3006 if (isCacheInstanceValid()) {
3008 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3010 $GLOBALS['cache_instance']->removeCacheFile($force);
3013 // Include file given?
3016 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3018 // Is the include there?
3019 if (isIncludeReadable($inc)) {
3020 // And rebuild it from scratch
3021 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3024 // Include not found!
3025 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3031 // Determines the real remote address
3032 function determineRealRemoteAddress () {
3033 // Is a proxy in use?
3034 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3036 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3037 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3038 // Yet, another proxy
3039 $address = $_SERVER['HTTP_CLIENT_IP'];
3041 // The regular address when no proxy was used
3042 $address = $_SERVER['REMOTE_ADDR'];
3045 // This strips out the real address from proxy output
3046 if (strstr($address, ',')) {
3047 $addressArray = explode(',', $address);
3048 $address = $addressArray[0];
3051 // Return the result
3055 // Adds a bonus mail to the queue
3056 // This is a high-level function!
3057 function addNewBonusMail ($data, $mode = '', $output=true) {
3058 // Use mode from data if not set and availble ;-)
3059 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3061 // Generate receiver list
3062 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3065 if (!empty($receiver)) {
3066 // Add bonus mail to queue
3067 addBonusMailToQueue(
3079 // Mail inserted into bonus pool
3080 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3081 } elseif ($output) {
3082 // More entered than can be reached!
3083 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3086 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3090 // Determines referal id and sets it
3091 function determineReferalId () {
3092 // Skip this in non-html-mode and outside ref.php
3093 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3095 // Check if refid is set
3096 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3098 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3099 // The variable user comes from the click-counter script click.php and we only accept this here
3100 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3101 } elseif (isPostRequestElementSet('refid')) {
3102 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3103 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3104 } elseif (isGetRequestElementSet('refid')) {
3105 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3106 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3107 } elseif (isGetRequestElementSet('ref')) {
3108 // Set refid=ref (the referal link uses such variable)
3109 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3110 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3111 // Set session refid als global
3112 $GLOBALS['refid'] = bigintval(getSession('refid'));
3113 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3114 // Select a random user which has confirmed enougth mails
3115 $GLOBALS['refid'] = determineRandomReferalId();
3116 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3117 // Set default refid as refid in URL
3118 $GLOBALS['refid'] = getConfig('def_refid');
3120 // No default id when sql_patches is not installed or none set
3121 $GLOBALS['refid'] = '0';
3124 // Set cookie when default refid > 0
3125 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3126 // Default is not found
3129 // Do we have nickname or userid set?
3130 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3131 // Nickname in URL, so load the id
3132 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3133 } elseif ($GLOBALS['refid'] > 0) {
3134 // Direct userid entered
3135 $found = fetchUserData($GLOBALS['refid']);
3138 // Is the record valid?
3139 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3140 // No, then reset referal id
3141 $GLOBALS['refid'] = getConfig('def_refid');
3145 setSession('refid', $GLOBALS['refid']);
3148 // Return determined refid
3149 return $GLOBALS['refid'];
3152 // Enables the reset mode and runs it
3153 function doReset () {
3154 // Enable the reset mode
3155 $GLOBALS['reset_enabled'] = true;
3158 runFilterChain('reset');
3161 // Our shutdown-function
3162 function shutdown () {
3163 // Call the filter chain 'shutdown'
3164 runFilterChain('shutdown', null);
3166 if (SQL_IS_LINK_UP()) {
3168 SQL_CLOSE(__FILE__, __LINE__);
3169 } elseif (!isInstallationPhase()) {
3171 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3174 // Stop executing here
3179 function initMemberId () {
3180 $GLOBALS['member_id'] = '0';
3183 // Setter for member id
3184 function setMemberId ($memberid) {
3185 // We should not set member id to zero
3186 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3189 $GLOBALS['member_id'] = bigintval($memberid);
3192 // Getter for member id or returns zero
3193 function getMemberId () {
3194 // Default member id
3197 // Is the member id set?
3198 if (isMemberIdSet()) {
3200 $memberid = $GLOBALS['member_id'];
3207 // Checks ether the member id is set
3208 function isMemberIdSet () {
3209 return (isset($GLOBALS['member_id']));
3212 // Handle message codes from URL
3213 function handleCodeMessage () {
3214 if (isGetRequestElementSet('code')) {
3215 // Default extension is 'unknown'
3218 // Is extension given?
3219 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3221 // Convert the 'code' parameter from URL to a human-readable message
3222 $message = getMessageFromErrorCode(getRequestElement('code'));
3224 // Load message template
3225 loadTemplate('message', false, $message);
3229 // Setter for extra title
3230 function setExtraTitle ($extraTitle) {
3231 $GLOBALS['extra_title'] = $extraTitle;
3234 // Getter for extra title
3235 function getExtraTitle () {
3236 // Is the extra title set?
3237 if (!isExtraTitleSet()) {
3238 // No, then abort here
3239 debug_report_bug('extra_title is not set!');
3243 return $GLOBALS['extra_title'];
3246 // Checks if the extra title is set
3247 function isExtraTitleSet () {
3248 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3251 // Generates a 'extension foo inactive' message
3252 function generateExtensionInactiveMessage ($ext_name) {
3253 // Is the extension empty?
3254 if (empty($ext_name)) {
3255 // This should not happen
3256 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3260 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3262 // Is an admin logged in?
3264 // Then output admin message
3265 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3268 // Return prepared message
3272 // Generates a 'extension foo not installed' message
3273 function generateExtensionNotInstalledMessage ($ext_name) {
3274 // Is the extension empty?
3275 if (empty($ext_name)) {
3276 // This should not happen
3277 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3281 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3283 // Is an admin logged in?
3285 // Then output admin message
3286 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3289 // Return prepared message
3293 // Generates a message depending on if the extension is not installed or not
3295 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3299 // Is the extension not installed or just deactivated?
3300 switch (isExtensionInstalled($ext_name)) {
3301 case true; // Deactivated!
3302 $message = generateExtensionInactiveMessage($ext_name);
3305 case false; // Not installed!
3306 $message = generateExtensionNotInstalledMessage($ext_name);
3309 default: // Should not happen!
3310 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3311 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3315 // Return the message
3319 // Reads a directory recursively by default and searches for files not matching
3320 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3321 // a whole directory.
3322 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3323 // Add default entries we should exclude
3324 $excludeArray[] = '.';
3325 $excludeArray[] = '..';
3326 $excludeArray[] = '.svn';
3327 $excludeArray[] = '.htaccess';
3329 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3334 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3337 while ($baseFile = readdir($dirPointer)) {
3338 // Exclude '.', '..' and entries in $excludeArray automatically
3339 if (in_array($baseFile, $excludeArray, true)) {
3341 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3345 // Construct include filename and FQFN
3346 $fileName = $baseDir . $baseFile;
3347 $FQFN = getConfig('PATH') . $fileName;
3349 // Remove double slashes
3350 $FQFN = str_replace('//', '/', $FQFN);
3352 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3353 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3354 // These Lines are only for debugging!!
3355 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3356 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3357 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3363 // Skip also files with non-matching prefix genericly
3364 if (($recursive === true) && (isDirectory($FQFN))) {
3365 // Is a redirectory so read it as well
3366 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3368 // And skip further processing
3370 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3372 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3374 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3375 // Skip wrong suffix as well
3376 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3378 } elseif (!isFileReadable($FQFN)) {
3379 // Not readable so skip it
3380 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3384 // Is the file a PHP script or other?
3385 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3386 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3387 // Is this a valid include file?
3388 if ($extension == '.php') {
3389 // Remove both for extension name
3390 $extName = substr($baseFile, strlen($prefix), -4);
3392 // Is the extension valid and active?
3393 if (isExtensionNameValid($extName)) {
3394 // Then add this file
3395 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3396 $files[] = $fileName;
3398 // Add non-extension files as well
3399 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3400 if ($addBaseDir === true) {
3401 $files[] = $fileName;
3403 $files[] = $baseFile;
3407 // We found .php file but should not search for them, why?
3408 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3410 } elseif (substr($baseFile, -4, 4) == $extension) {
3411 // Other, generic file found
3412 $files[] = $fileName;
3417 closedir($dirPointer);
3422 // Return array with include files
3423 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3427 // Maps a module name into a database table name
3428 function mapModuleToTable ($moduleName) {
3429 // Map only these, still lame code...
3430 switch ($moduleName) {
3431 // 'index' is the guest's menu
3432 case 'index': $moduleName = 'guest'; break;
3433 // ... and 'login' the member's menu
3434 case 'login': $moduleName = 'member'; break;
3435 // Anything else will not be mapped, silently.
3442 // Add SQL debug data to array for later output
3443 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3444 // Already executed?
3445 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3446 // Then abort here, we don't need to profile a query twice
3450 // Remeber this as profiled (or not, but we don't care here)
3451 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3453 // Do we have cache?
3454 if (!isset($GLOBALS['debug_sql_available'])) {
3455 // Check it and cache it in $GLOBALS
3456 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3459 // Don't execute anything here if we don't need or ext-other is missing
3460 if ($GLOBALS['debug_sql_available'] === false) {
3466 'num_rows' => SQL_NUMROWS($result),
3467 'affected' => SQL_AFFECTEDROWS(),
3468 'sql_str' => $sqlString,
3469 'timing' => $timing,
3470 'file' => basename($F),
3475 $GLOBALS['debug_sqls'][] = $record;
3478 // Initializes the cache instance
3479 function initCacheInstance () {
3480 // Load include for CacheSystem class
3481 loadIncludeOnce('inc/classes/cachesystem.class.php');
3483 // Initialize cache system only when it's needed
3484 $GLOBALS['cache_instance'] = new CacheSystem();
3485 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3486 // Failed to initialize cache sustem
3487 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3491 // Getter for message from array or raw message
3492 function getMessageFromIndexedArray ($message, $pos, $array) {
3493 // Check if the requested message was found in array
3494 if (isset($array[$pos])) {
3495 // ... if yes then use it!
3496 $ret = $array[$pos];
3498 // ... else use default message
3506 // Print code with line numbers
3507 function linenumberCode ($code) {
3508 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3509 $count_lines = count($codeE);
3511 $r = 'Line | Code:<br />';
3512 foreach($codeE as $line => $c) {
3513 $r .= '<div class="line"><span class="linenum">';
3514 if ($count_lines == 1) {
3517 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3522 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3525 return '<div class="code">' . $r . '</div>';
3528 // Convert ';' to ', ' for e.g. receiver list
3529 function convertReceivers ($old) {
3530 return str_replace(';', ', ', $old);
3533 // Determines the right page title
3534 function determinePageTitle () {
3535 // Config and database connection valid?
3536 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3540 // Title decoration enabled?
3541 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3543 // Do we have some extra title?
3544 if (isExtraTitleSet()) {
3546 $TITLE .= getExtraTitle() . ' by ';
3550 $TITLE .= getConfig('MAIN_TITLE');
3552 // Add title of module? (middle decoration will also be added!)
3553 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3554 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3557 // Add title from what file
3559 if (getModule() == 'login') $mode = 'member';
3560 elseif (getModule() == 'index') $mode = 'guest';
3561 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3563 // Add title decorations? (right)
3564 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3566 // Remember title in constant for the template
3567 $pageTitle = $TITLE;
3568 } elseif ((isInstalled()) && (isAdminRegistered())) {
3569 // Installed, admin registered but no ext-sql_patches
3570 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3571 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3572 // Installed but no admin registered
3573 $pageTitle = getMessage('SETUP_OF_MXCHANGE');
3574 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3575 // Installation mode
3576 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3578 // Configuration not found!
3579 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3581 // Do not add the fatal message in installation mode
3582 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3586 return decodeEntities($pageTitle);
3589 // Checks wethere there is a cache file there. This function is cached.
3590 function isTemplateCached ($template) {
3591 // Do we have cached this result?
3592 if (!isset($GLOBALS['template_cache'][$template])) {
3594 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3597 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3601 return $GLOBALS['template_cache'][$template];
3604 // Flushes non-flushed template cache to disk
3605 function flushTemplateCache ($template, $eval) {
3606 // Is this cache flushed?
3607 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3609 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3611 // Replace username with a call
3612 $eval = str_replace('$username', '".getUsername()."', $eval);
3615 writeToFile($FQFN, $eval, true);
3619 // Reads a template cache
3620 function readTemplateCache ($template) {
3622 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3624 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3627 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3631 return $GLOBALS['template_eval'][$template];
3634 // Escapes quotes (default is only double-quotes)
3635 function escapeQuotes ($str, $single = false) {
3636 // Should we escape all?
3637 if ($single === true) {
3638 // Escape all (including null)
3639 $str = addslashes($str);
3641 // Escape only double-quotes but prevent double-quoting
3642 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3645 // Return the escaped string
3649 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3650 function escapeJavaScriptQuotes ($str) {
3651 // Replace all double-quotes and secure back-ticks
3652 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3658 // Send out mails depending on the 'mod/modes' combination
3659 // @TODO Lame description for this function
3660 function sendModeMails ($mod, $modes) {
3662 if (fetchUserData(getMemberId())) {
3663 // Extract salt from cookie
3664 $salt = substr(getSession('u_hash'), 0, -40);
3666 // Now let's compare passwords
3667 $hash = generatePassString(getUserData('password'));
3669 // Does the hash match or should we change it?
3670 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
3672 $content = getUserDataArray();
3675 $content['gender'] = translateGender($content['gender']);
3677 // Clear/init the content variable
3678 $content['message'] = '';
3681 // @TODO Move this in a filter
3684 foreach ($modes as $mode) {
3686 case 'normal': break; // Do not add any special lines
3687 case 'email': // Email was changed!
3688 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestElement('old_email')."\n";
3691 case 'pass': // Password was changed
3692 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3696 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3697 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3702 if (isExtensionActive('country')) {
3703 // Replace code with description
3704 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
3707 // Merge content with data from POST
3708 $content = merge_array($content, postRequestArray());
3711 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3713 if (getConfig('admin_notify') == 'Y') {
3714 // The admin needs to be notified about a profile change
3715 $message_admin = 'admin_mydata_notify';
3716 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3719 $message_admin = '';
3723 // Set subject lines
3724 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3726 // Output success message
3727 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3730 default: // Unsupported module!
3731 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3732 $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
3736 // Passwords mismatch
3737 $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
3740 // Could not load profile
3741 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
3744 // Send email to user if required
3745 if ((!empty($sub_mem)) && (!empty($message))) {
3747 sendEmail($content['email'], $sub_mem, $message);
3750 // Send only if no other error has occured
3751 if (empty($content)) {
3752 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3754 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3755 } elseif (getConfig('admin_notify') == 'Y') {
3756 // Cannot send mails to admin!
3757 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3760 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3765 loadTemplate('admin_settings_saved', false, $content);
3768 // Generates a 'selection box' from given array
3769 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent) {
3771 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3772 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3774 // Walk through all options
3775 foreach ($options as $option) {
3776 // Add the <option> entry
3777 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3780 // Finish selection box
3781 $OUT .= '</select>';
3785 'selection_box' => $OUT,
3786 'module' => getModule(),
3790 // Load template and return it
3791 return loadTemplate('select_' . $name . '_box', true, $content);
3794 // Get a module from filename and access level
3795 function getModuleFromFileName ($file, $accessLevel) {
3796 // Default is 'invalid';
3797 $modCheck = 'invalid';
3799 // @TODO This is still very static, rewrite it somehow
3800 switch ($accessLevel) {
3802 $modCheck = 'admin';
3808 $modCheck = getModule();
3811 default: // Unsupported file name / access level
3812 debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3820 // Encodes an URL for adding session id, etc.
3821 function encodeUrl ($url, $outputMode = '0') {
3822 // Do we have already have a PHPSESSID inside? Then it is already converted...
3823 if (strpos($url, session_name()) !== false) return $url;
3825 // Do we have a valid session?
3826 if ((($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3828 // Determine right seperator
3829 $seperator = '&';
3830 if (strpos($url, '?') === false) {
3833 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3839 if (session_id() != '') {
3840 $url .= $seperator . session_name() . '=' . session_id();
3845 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3847 $url = '{?URL?}/' . $url;
3854 // Simple check for spider
3855 function isSpider () {
3857 $userAgent = strtolower(detectUserAgent(true));
3859 // It should not be empty, if so it is better a spider/bot
3860 if (empty($userAgent)) return true;
3863 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false));
3866 //////////////////////////////////////////////////
3867 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3868 //////////////////////////////////////////////////
3870 if (!function_exists('html_entity_decode')) {
3871 // Taken from documentation on www.php.net
3872 function html_entity_decode ($string) {
3873 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3874 $trans_tbl = array_flip($trans_tbl);
3875 return strtr($string, $trans_tbl);
3879 if (!function_exists('http_build_query')) {
3880 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3881 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
3883 foreach ((array)$data as $k => $v) {
3884 if (is_int($k) && $prefix != null) {
3885 $k = urlencode($prefix . $k);
3888 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3890 if (is_array($v) || is_object($v)) {
3891 array_push($ret, http_build_query($v, '', $sep, $k));
3893 array_push($ret, $k.'='.urlencode($v));
3897 if (empty($sep)) $sep = ini_get('arg_separator.output');
3899 return implode($sep, $ret);