2 /************************************************************************
3 * MXChange v0.2.1 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) print("\n");
84 // Huh, something goes wrong or maybe you have edited config.php ???
85 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
88 } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
89 // Headers already sent?
92 logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
94 // Trigger an user error
95 debug_report_bug('Headers are already sent!');
98 // Output cached HTML code
99 $GLOBALS['output'] = ob_get_contents();
101 // Clear output buffer for later output if output is found
102 if (!empty($GLOBALS['output'])) {
106 // Extension 'rewrite' installed?
107 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
108 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
111 // Compile and run finished rendered HTML code
112 compileFinalOutput();
114 // Send all HTTP headers
117 // Output code here, DO NOT REMOVE! ;-)
118 outputRawCode($GLOBALS['output']);
119 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
120 // Rewrite links when rewrite extension is active
121 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
122 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
125 // Compile and run finished rendered HTML code
126 compileFinalOutput();
128 // Send all HTTP headers
131 // Output code here, DO NOT REMOVE! ;-)
132 outputRawCode($GLOBALS['output']);
136 // Sends out all headers required for HTTP/1.1 reply
137 function sendHttpHeaders () {
139 $now = gmdate('D, d M Y H:i:s') . ' GMT';
142 sendHeader('HTTP/1.1 200');
144 // General headers for no caching
145 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
146 sendHeader('Last-Modified: ' . $now);
147 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
148 sendHeader('Pragma: no-cache'); // HTTP/1.0
149 sendHeader('Connection: Close');
150 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
151 sendHeader('Content-Language: ' . getLanguage());
154 // Compiles the final output
155 function compileFinalOutput () {
160 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
161 // Init common variables
166 $eval = "\$newContent = \"".compileCode(addslashes($GLOBALS['output']))."\";";
169 // Was that eval okay?
170 if (empty($newContent)) {
171 // Something went wrong!
172 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>');
174 $GLOBALS['output'] = $newContent;
181 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
184 // Output the raw HTML code
185 function outputRawCode ($htmlCode) {
186 // Output stripped HTML code to avoid broken JavaScript code, etc.
189 // Flush the output if only getPhpCaching() is not 'on'
190 if (getPhpCaching() != 'on') {
196 // Init fatal message array
197 function initFatalMessages () {
198 $GLOBALS['fatal_messages'] = array();
201 // Getter for whole fatal error messages
202 function getFatalArray () {
203 return $GLOBALS['fatal_messages'];
206 // Add a fatal error message to the queue array
207 function addFatalMessage ($F, $L, $message, $extra='') {
208 if (is_array($extra)) {
209 // Multiple extras for a message with masks
210 $message = call_user_func_array('sprintf', $extra);
211 } elseif (!empty($extra)) {
212 // $message is text with a mask plus extras to insert into the text
213 $message = sprintf($message, $extra);
216 // Add message to $GLOBALS['fatal_messages']
217 $GLOBALS['fatal_messages'][] = $message;
219 // Log fatal messages away
220 debug_report_bug($message);
221 logDebugMessage($F, $L, " message={$message}");
224 // Getter for total fatal message count
225 function getTotalFatalErrors () {
229 // Do we have at least the first entry?
230 if (!empty($GLOBALS['fatal_messages'][0])) {
232 $count = count($GLOBALS['fatal_messages']);
239 // Load a template file and return it's content (only it's name; do not use ' or ")
240 function loadTemplate ($template, $return=false, $content=array()) {
241 // @TODO Remove this sanity-check if all is fine
242 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
244 // @TODO Try to rewrite all $DATA to $content
248 if (isTemplateCached($template)) {
249 // Evaluate the cache
250 eval(readTemplateCache($template));
251 } elseif (!isset($GLOBALS['template_eval'][$template])) {
252 // Add more variables which you want to use in your template files
253 $username = getUsername();
255 // Make all template names lowercase
256 $template = strtolower($template);
258 // Count the template load
259 incrementConfigEntry('num_templates');
263 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
266 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
269 // Check for admin/guest/member templates
270 if (substr($template, 0, 6) == 'admin_') {
271 // Admin template found
273 } elseif (substr($template, 0, 6) == 'guest_') {
274 // Guest template found
276 } elseif (substr($template, 0, 7) == 'member_') {
277 // Member template found
279 } elseif (substr($template, 0, 8) == 'install_') {
280 // Installation template found
282 } elseif (substr($template, 0, 4) == 'ext_') {
283 // Extension template found
285 } elseif (substr($template, 0, 3) == 'la_') {
286 // 'Logical-area' template found
288 } elseif (substr($template, 0, 3) == 'js_') {
289 // JavaScript template found
291 } elseif (substr($template, 0, 5) == 'menu_') {
292 // Menu template found
295 // Test for extension
296 $test = substr($template, 0, strpos($template, '_'));
298 // Probe for valid extension name
299 if (isExtensionNameValid($test)) {
300 // Set extra path to extension's name
305 ////////////////////////
306 // Generate file name //
307 ////////////////////////
308 $FQFN = $basePath . $mode . $template . '.tpl';
310 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
311 // Select what depended header/footer template file for admin/guest/member area
312 $file2 = sprintf("%s%s%s_%s.tpl",
320 if (isFileReadable($file2)) $FQFN = $file2;
322 // Remove variable from memory
326 // Does the special template exists?
327 if (!isFileReadable($FQFN)) {
328 // Reset to default template
329 $FQFN = $basePath . $template . '.tpl';
332 // Now does the final template exists?
333 if (isFileReadable($FQFN)) {
334 // The local file does exists so we load it. :)
335 $GLOBALS['tpl_content'] = readFromFile($FQFN);
337 // Do we have to compile the code?
339 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
340 // Normal HTML output?
341 if (getOutputMode() == '0') {
342 // Add surrounding HTML comments to help finding bugs faster
343 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
345 // Prepare eval() command
346 $eval = '$ret = "' . compileCode(addslashes($ret)) . '";';
347 } elseif (substr($template, 0, 3) == 'js_') {
348 // JavaScripts don't like entities and timings
349 $eval = '$ret = decodeEntities("' . compileRawCode(addslashes($GLOBALS['tpl_content'])) . '");';
351 // Prepare eval() command
352 $eval = '$ret = "' . compileCode(addslashes($GLOBALS['tpl_content'])) . '";';
355 // Add surrounding HTML comments to help finding bugs faster
356 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
357 $eval = '$ret = "' . addslashes($ret) . '";';
360 // Cache the eval() command here
361 $GLOBALS['template_eval'][$template] = $eval;
364 eval($GLOBALS['template_eval'][$template]);
365 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
366 // Only admins shall see this warning or when installation mode is active
367 $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
368 (' . $template . ')<br />
370 {--TEMPLATE_CONTENT--}
371 <pre>' . print_r($content, true) . '</pre>
373 <pre>' . print_r($DATA, true) . '</pre>
377 $GLOBALS['template_eval'][$template] = '404';
381 eval($GLOBALS['template_eval'][$template]);
384 // Do we have some content to output or return?
386 // Not empty so let's put it out! ;)
387 if ($return === true) {
388 // Return the HTML code
394 } elseif (isDebugModeEnabled()) {
395 // Warning, empty output!
396 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
400 // Loads an email template and compiles it
401 function loadEmailTemplate ($template, $content = array(), $UID = '0') {
404 // Make sure all template names are lowercase!
405 $template = strtolower($template);
407 // Default 'nickname' if extension is not installed
410 // Prepare IP number and User Agent
411 $REMOTE_ADDR = detectRemoteAddr();
412 $HTTP_USER_AGENT = detectUserAgent();
415 $ADMIN = getConfig('MAIN_TITLE');
417 // Is the admin logged in?
420 $adminId = getCurrentAdminId();
423 $ADMIN = getAdminEmail($adminId);
426 // Neutral email address is default
427 $email = getConfig('WEBMASTER');
429 // Expiration in a nice output format
430 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
431 if (getConfig('auto_purge') == '0') {
432 // Will never expire!
433 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
435 // Create nice date string
436 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
439 // Is content an array?
440 if (is_array($content)) {
441 // Add expiration to array, $EXPIRATION is now deprecated!
442 $content['expiration'] = $EXPIRATION;
446 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content).'<br />');
447 if (($UID > 0) && (is_array($content))) {
448 // If nickname extension is installed, fetch nickname as well
449 if (isNicknameUsed($UID)) {
450 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
452 fetchUserData($UID, 'nickname');
454 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
459 // Merge data if valid
460 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
461 if (isUserDataValid()) {
462 $content = merge_array($content, getUserDataArray());
464 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
467 // Translate M to male or F to female if present
468 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
470 // Overwrite email from data if present
471 if (isset($content['email'])) $email = $content['email'];
473 // Store email for some functions in global data array
474 $DATA['email'] = $email;
477 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
479 // Check for admin/guest/member templates
480 if (substr($template, 0, 6) == 'admin_') {
481 // Admin template found
482 $FQFN = $basePath.'admin/' . $template.'.tpl';
483 } elseif (substr($template, 0, 6) == 'guest_') {
484 // Guest template found
485 $FQFN = $basePath.'guest/' . $template.'.tpl';
486 } elseif (substr($template, 0, 7) == 'member_') {
487 // Member template found
488 $FQFN = $basePath.'member/' . $template.'.tpl';
490 // Test for extension
491 $test = substr($template, 0, strpos($template, '_'));
492 if (isExtensionNameValid($test)) {
493 // Set extra path to extension's name
494 $FQFN = $basePath . $test.'/' . $template.'.tpl';
496 // No special filename
497 $FQFN = $basePath . $template.'.tpl';
501 // Does the special template exists?
502 if (!isFileReadable($FQFN)) {
503 // Reset to default template
504 $FQFN = $basePath . $template.'.tpl';
507 // Now does the final template exists?
509 if (isFileReadable($FQFN)) {
510 // The local file does exists so we load it. :)
511 $GLOBALS['tpl_content'] = readFromFile($FQFN);
514 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileRawCode(addslashes($GLOBALS['tpl_content']))."\");";
515 eval($GLOBALS['tpl_content']);
516 } elseif (!empty($template)) {
517 // Template file not found!
518 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
519 {--TEMPLATE_CONTENT--}
520 <pre>".print_r($content, true)."</pre>
522 <pre>".print_r($DATA, true)."</pre>
525 // Debug mode not active? Then remove the HTML tags
526 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
528 // No template name supplied!
529 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
532 // Is there some content?
533 if (empty($newContent)) {
535 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
536 // Add last error if the required function exists
537 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
540 // Remove content and data
544 // Compile the code and eval it
545 $eval = '$newContent = "' . compileRawCode(addslashes($newContent)) . '";';
552 // Send mail out to an email address
553 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
554 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
556 // Compile subject line (for POINTS constant etc.)
557 eval("\$subject = decodeEntities(\"".compileRawCode(addslashes($subject))."\");");
560 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
561 // Value detected, is the message extension installed?
562 // @TODO Extension 'msg' does not exist
563 if (isExtensionActive('msg')) {
564 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
567 // Does the user exist?
568 if (fetchUserData($toEmail)) {
570 $toEmail = getUserData('email');
573 $toEmail = getConfig('WEBMASTER');
576 } elseif ($toEmail == '0') {
578 $toEmail = getConfig('WEBMASTER');
580 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
582 // Check for PHPMailer or debug-mode
583 if (!checkPhpMailerUsage()) {
584 // Not in PHPMailer-Mode
585 if (empty($mailHeader)) {
586 // Load email header template
587 $mailHeader = loadEmailTemplate('header');
590 $mailHeader .= loadEmailTemplate('header');
592 } elseif (isDebugModeEnabled()) {
593 if (empty($mailHeader)) {
594 // Load email header template
595 $mailHeader = loadEmailTemplate('header');
598 $mailHeader .= loadEmailTemplate('header');
603 eval("\$toEmail = \"".compileRawCode(addslashes($toEmail))."\";");
606 eval("\$message = \"".compileRawCode(addslashes($message))."\";");
608 // Fix HTML parameter (default is no!)
609 if (empty($isHtml)) $isHtml = 'N';
610 if (isDebugModeEnabled()) {
611 // In debug mode we want to display the mail instead of sending it away so we can debug this part
613 Headers : ' . str_replace('<', '<', str_replace('>', '>', htmlentities(trim($mailHeader)))) . '
614 To : ' . $toEmail . '
615 Subject : ' . $subject . '
616 Message : ' . $message . '
618 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
619 // Send mail as HTML away
620 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
621 } elseif (!empty($toEmail)) {
623 sendRawEmail($toEmail, $subject, $message, $mailHeader);
624 } elseif ($isHtml != 'Y') {
626 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
630 // Check if legacy or PHPMailer command
631 // @TODO Rewrite this to an extension 'smtp'
633 function checkPhpMailerUsage() {
634 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
637 // Send out a raw email with PHPMailer class or legacy mail() command
638 function sendRawEmail ($toEmail, $subject, $message, $from) {
639 // Shall we use PHPMailer class or legacy mode?
640 if (checkPhpMailerUsage()) {
641 // Use PHPMailer class with SMTP enabled
642 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
643 loadIncludeOnce('inc/phpmailer/class.smtp.php');
646 $mail = new PHPMailer();
648 // Set charset to UTF-8
649 $mail->CharSet('UTF-8');
651 // Path for PHPMailer
652 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
655 $mail->SMTPAuth = true;
656 $mail->Host = getConfig('SMTP_HOSTNAME');
658 $mail->Username = getConfig('SMTP_USER');
659 $mail->Password = getConfig('SMTP_PASSWORD');
661 $mail->From = getConfig('WEBMASTER');
665 $mail->FromName = getConfig('MAIN_TITLE');
666 $mail->Subject = $subject;
667 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
668 $mail->Body = $message;
669 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
670 $mail->WordWrap = 70;
673 $mail->Body = decodeEntities($message);
675 $mail->AddAddress($toEmail, '');
676 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
677 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
678 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
681 // Use legacy mail() command
682 mail($toEmail, $subject, decodeEntities($message), $from);
686 // Generate a password in a specified length or use default password length
687 function generatePassword ($length = '0') {
688 // Auto-fix invalid length of zero
689 if ($length == '0') $length = getConfig('pass_len');
691 // Initialize array with all allowed chars
692 $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,-,+,_,/,.');
694 // Start creating password
696 for ($i = '0'; $i < $length; $i++) {
697 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
700 // When the size is below 40 we can also add additional security by scrambling
701 // it. Otherwise we may corrupt hashes
702 if (strlen($PASS) <= 40) {
703 // Also scramble the password
704 $PASS = scrambleString($PASS);
707 // Return the password
711 // Generates a human-readable timestamp from the Uni* stamp
712 function generateDateTime ($time, $mode = '0') {
713 // Filter out numbers
714 $time = bigintval($time);
716 // If the stamp is zero it mostly didn't "happen"
719 return getMessage('NEVER_HAPPENED');
722 switch (getLanguage()) {
723 case 'de': // German date / time format
725 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
726 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
727 case '2': $ret = date('d.m.Y|H:i', $time); break;
728 case '3': $ret = date('d.m.Y', $time); break;
730 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
735 default: // Default is the US date / time format!
737 case '0': $ret = date('r', $time); break;
738 case '1': $ret = date('Y-m-d - g:i A', $time); break;
739 case '2': $ret = date('y-m-d|H:i', $time); break;
740 case '3': $ret = date('y-m-d', $time); break;
742 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
751 // Translates Y/N to yes/no
752 function translateYesNo ($yn) {
754 $translated = '??? (' . $yn . ')';
756 case 'Y': $translated = getMessage('YES'); break;
757 case 'N': $translated = getMessage('NO'); break;
760 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
768 // Translates the "pool type" into human-readable
769 function translatePoolType ($type) {
770 // Default?type is unknown
771 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
774 $constName = sprintf("POOL_TYPE_%s", $type);
777 if (isMessageIdValid($constName)) {
779 $translated = getMessage($constName);
782 // Return "translation"
786 // Translates the american decimal dot into a german comma
787 function translateComma ($dotted, $cut = true, $max = '0') {
788 // Default is 3 you can change this in admin area "Misc -> Misc Options"
789 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
791 // Use from config is default
792 $maxComma = getConfig('max_comma');
794 // Use from parameter?
795 if ($max > 0) $maxComma = $max;
798 if (($cut === true) && ($max == '0')) {
799 // Test for commata if in cut-mode
800 $com = explode('.', $dotted);
801 if (count($com) < 2) {
802 // Don't display commatas even if there are none... ;-)
808 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
811 switch (getLanguage()) {
812 case 'de': // German language
813 $dotted = number_format($dotted, $maxComma, ',', '.');
816 default: // All others
817 $dotted = number_format($dotted, $maxComma, '.', ',');
821 // Return translated value
825 // Translate Uni*-like gender to human-readable
826 function translateGender ($gender) {
828 $ret = '!' . $gender . '!';
830 // Male/female or company?
832 case 'M': $ret = getMessage('GENDER_M'); break;
833 case 'F': $ret = getMessage('GENDER_F'); break;
834 case 'C': $ret = getMessage('GENDER_C'); break;
836 // Log unknown gender
837 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
841 // Return translated gender
845 // "Translates" the user status
846 function translateUserStatus ($status) {
847 // Generate message depending on status
852 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
857 $ret = getMessage('ACCOUNT_DELETED');
861 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
862 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
870 // Generates an URL for the dereferer
871 function generateDerefererUrl ($URL) {
872 // Don't de-refer our own links!
873 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
874 // De-refer this link
875 $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
882 // Generates an URL for the frametester
883 function generateFrametesterUrl ($URL) {
884 // Prepare frametester URL
885 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
886 encodeString(compileUriCode($URL))
889 // Return the new URL
890 return $frametesterUrl;
893 // Count entries from e.g. a selection box
894 function countSelection ($array) {
896 if (!is_array($array)) {
898 debug_report_bug(__FUNCTION__.': No array provided.');
905 foreach ($array as $key => $selected) {
907 if (!empty($selected)) $ret++;
910 // Return counted selections
914 // Generate XHTML code for the CAPTCHA
915 function generateCaptchaCode ($code, $type, $DATA, $userid) {
916 return '<img border="0" alt="Code ' . $code . '" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
919 // Generates a timestamp (some wrapper for mktime())
920 function makeTime ($hours, $minutes, $seconds, $stamp) {
921 // Extract day, month and year from given timestamp
922 $days = date('d', $stamp);
923 $months = date('m', $stamp);
924 $years = date('Y', $stamp);
926 // Create timestamp for wished time which depends on extracted date
937 // Redirects to an URL and if neccessarry extends it with own base URL
938 function redirectToUrl ($URL) {
940 eval('$URL = "' . compileRawCode($URL) . '";');
942 // Check if http(s):// is there
943 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
944 // Make all URLs full-qualified
945 $URL = getConfig('URL') . '/' . $URL;
948 // Three different debug ways...
949 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
950 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
951 //* DEBUG: */ die($URL);
953 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
954 $rel = ' rel="external"';
956 // Do we have internal or external URL?
957 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
958 // Own (=internal) URL
963 $GLOBALS['output'] = ob_get_contents();
965 // Clear it only if there is content
966 if (!empty($GLOBALS['output'])) {
970 // Simple probe for bots/spiders from search engines
971 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
972 // Secure the URL against bad things such als HTML insertions and so on...
973 $URL = secureString($URL);
975 // Output new location link as anchor
976 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
977 } elseif (!headers_sent()) {
978 //* DEBUG: */ debug_report_bug("URL={$URL}");
979 // Clear own output buffer
980 $GLOBALS['output'] = '';
982 // Load URL when headers are not sent
983 sendHeader('Location: '.str_replace('&', '&', $URL));
985 // Output error message
986 loadInclude('inc/header.php');
987 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
988 loadInclude('inc/footer.php');
991 // Shut the mailer down here
995 // Wrapper for redirectToUrl but URL comes from a configuration entry
996 function redirectToConfiguredUrl ($configEntry) {
998 $URL = getConfig($configEntry);
1001 if (is_null($URL)) {
1003 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1007 redirectToUrl($URL);
1010 // Compiles the given HTML/mail code
1011 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1012 // Is the code a string?
1013 if (!is_string($code)) {
1014 // Silently return it
1019 $startCompile = explode(' ', microtime());
1022 $code = compileRawCode($code, $simple, $constants, $full);
1025 $compiled = explode(' ', microtime());
1028 $code .= '<!-- Compilation time: ' . ((($compiled[1] + $compiled[0]) - ($startCompile[1] + $startCompile[0])) * 1000). 'ms //-->';
1030 // Return compiled code
1034 // Compiles the code (use compileCode() only for HTML because of the comments)
1035 // @TODO $simple is deprecated
1036 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1037 // Is the code a string?
1038 if (!is_string($code)) {
1039 // Silently return it
1043 // Init replacement-array with full security characters
1044 $secChars = $GLOBALS['security_chars'];
1046 // Select smaller set of chars to replace when we e.g. want to compile URLs
1047 if ($full === false) $secChars = $GLOBALS['url_chars'];
1049 // Compile more through a filter
1050 $code = runFilterChain('compile_code', $code);
1052 // Compile constants
1053 if ($constants === true) {
1054 // BEFORE 0.2.1 : Language and data constants
1055 // WITH 0.2.1+ : Only language constants
1056 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1058 // BEFORE 0.2.1 : Not used
1059 // WITH 0.2.1+ : Data constants
1060 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1063 // Compile QUOT and other non-HTML codes
1064 foreach ($secChars['to'] as $k => $to) {
1065 // Do the reversed thing as in inc/libs/security_functions.php
1066 $code = str_replace($to, $secChars['from'][$k], $code);
1069 // Find $content[bla][blub] entries
1070 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1072 // Are some matches found?
1073 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1074 // Replace all matches
1075 $matchesFound = array();
1076 foreach ($matches[0] as $key => $match) {
1077 // Fuzzy look has failed by default
1078 $fuzzyFound = false;
1080 // Fuzzy look on match if already found
1081 foreach ($matchesFound as $found => $set) {
1083 $test = substr($found, 0, strlen($match));
1085 // Does this entry exist?
1086 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1087 if ($test == $match) {
1089 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1096 if ($fuzzyFound === true) continue;
1098 // Take all string elements
1099 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1100 // Replace it in the code
1101 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1102 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1103 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1104 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1105 $matchesFound[$match] = 1;
1106 } elseif (!isset($matchesFound[$match])) {
1107 // Not yet replaced!
1108 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1109 $code = str_replace($match, "\"." . $match.".\"", $code);
1110 $matchesFound[$match] = 1;
1119 /************************************************************************
1121 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1122 * $a_sort sortiert: *
1124 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1125 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1126 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1127 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1128 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1130 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1131 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1132 * Sie, dass es doch nicht so schwer ist! :-) *
1134 ************************************************************************/
1135 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1137 while ($primary_key < count($a_sort)) {
1138 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1139 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1141 if ($nums === false) {
1142 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1143 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1144 } elseif ($key != $key2) {
1145 // Sort numbers (E.g.: 9 < 10)
1146 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1147 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1151 // We have found two different values, so let's sort whole array
1152 foreach ($dummy as $sort_key => $sort_val) {
1153 $t = $dummy[$sort_key][$key];
1154 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1155 $dummy[$sort_key][$key2] = $t;
1166 // Write back sorted array
1171 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1174 if ($type == 'yn') {
1175 // This is a yes/no selection only!
1176 if ($id > 0) $prefix .= "[" . $id."]";
1177 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1179 // Begin with regular selection box here
1180 if (!empty($prefix)) $prefix .= "_";
1182 if ($id > 0) $type2 .= "[" . $id."]";
1183 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1188 for ($idx = 1; $idx < 32; $idx++) {
1189 $OUT .= "<option value=\"" . $idx."\"";
1190 if ($default == $idx) $OUT .= ' selected="selected"';
1191 $OUT .= ">" . $idx."</option>\n";
1195 case 'month': // Month
1196 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1197 $OUT .= "<option value=\"" . $month."\"";
1198 if ($default == $month) $OUT .= ' selected="selected"';
1199 $OUT .= ">" . $descr."</option>\n";
1203 case 'year': // Year
1205 $year = date('Y', time());
1207 // Use configured min age or fixed?
1208 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1210 $startYear = $year - getConfig('min_age');
1213 $startYear = $year - 16;
1216 // Calculate earliest year (100 years old people can still enter Internet???)
1217 $minYear = $year - 100;
1219 // Check if the default value is larger than minimum and bigger than actual year
1220 if (($default > $minYear) && ($default >= $year)) {
1221 for ($idx = $year; $idx < ($year + 11); $idx++) {
1222 $OUT .= "<option value=\"" . $idx."\"";
1223 if ($default == $idx) $OUT .= ' selected="selected"';
1224 $OUT .= ">" . $idx."</option>\n";
1226 } elseif ($default == -1) {
1227 // Current year minus 1
1228 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1230 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1233 // Get current year and subtract the configured minimum age
1234 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1235 // Calculate earliest year depending on extension version
1236 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1237 // Use configured minimum age
1238 $year = date('Y', time()) - getConfig('min_age');
1240 // Use fixed 16 years age
1241 $year = date('Y', time()) - 16;
1244 // Construct year selection list
1245 for ($idx = $minYear; $idx <= $year; $idx++) {
1246 $OUT .= "<option value=\"" . $idx."\"";
1247 if ($default == $idx) $OUT .= ' selected="selected"';
1248 $OUT .= ">" . $idx."</option>\n";
1255 for ($idx = '0'; $idx < 60; $idx+=5) {
1256 if (strlen($idx) == 1) $idx = '0' . $idx;
1257 $OUT .= "<option value=\"" . $idx."\"";
1258 if ($default == $idx) $OUT .= ' selected="selected"';
1259 $OUT .= ">" . $idx."</option>\n";
1264 for ($idx = '0'; $idx < 24; $idx++) {
1265 if (strlen($idx) == 1) $idx = '0' . $idx;
1266 $OUT .= "<option value=\"" . $idx."\"";
1267 if ($default == $idx) $OUT .= ' selected="selected"';
1268 $OUT .= ">" . $idx."</option>\n";
1273 $OUT .= "<option value=\"Y\"";
1274 if ($default == 'Y') $OUT .= ' selected="selected"';
1275 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1276 if ($default != 'Y') $OUT .= ' selected="selected"';
1277 $OUT .= ">{--NO--}</option>\n";
1280 $OUT .= " </select>\n";
1285 // Deprecated : $length
1288 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1289 // Build server string
1290 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1293 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1294 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1295 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1296 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1297 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1299 // Build string from misc data
1300 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1302 // Add more additional data
1303 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1305 // Add referal id, language, theme and userid
1306 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1307 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1308 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1309 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1311 // Calculate number for generating the code
1312 $a = $code + getConfig('_ADD') - 1;
1314 if (isConfigEntrySet('master_salt')) {
1315 // Generate hash with master salt from modula of number with the prime number and other data
1316 $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'));
1318 // Create number from hash
1319 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1321 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1322 $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')));
1324 // Create number from hash
1325 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1328 // At least 10 numbers shall be secure enought!
1329 $len = getConfig('code_length');
1330 if ($len == '0') $len = $length;
1331 if ($len == '0') $len = 10;
1333 // Cut off requested counts of number
1334 $return = substr(str_replace('.', '', $rcode), 0, $len);
1336 // Done building code
1340 // Does only allow numbers
1341 function bigintval ($num, $castValue = true) {
1342 // Filter all numbers out
1343 $ret = preg_replace('/[^0123456789]/', '', $num);
1346 if ($castValue === true) $ret = (double)$ret;
1348 // Has the whole value changed?
1349 if ('' . $ret . '' != '' . $num . '') {
1351 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1358 // Insert the code in $img_code into jpeg or PNG image
1359 function generateImageOrCode ($img_code, $headerSent = true) {
1360 // Is the code size oversized or shouldn't we display it?
1361 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1362 // Stop execution of function here because of over-sized code length
1363 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1364 } elseif ($headerSent === false) {
1365 // Return an HTML code here
1366 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1370 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1373 getConfig('img_type')
1377 if (isFileReadable($img)) {
1378 // Switch image type
1379 switch (getConfig('img_type'))
1382 // Okay, load image and hide all errors
1383 $image = imagecreatefromjpeg($img);
1387 // Okay, load image and hide all errors
1388 $image = imagecreatefrompng($img);
1392 // Exit function here
1393 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1397 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1398 $text_color = imagecolorallocate($image, 0, 0, 0);
1400 // Insert code into image
1401 imagestring($image, 5, 14, 2, $img_code, $text_color);
1403 // Return to browser
1404 sendHeader('Content-Type: image/' . getConfig('img_type'));
1406 // Output image with matching image factory
1407 switch (getConfig('img_type')) {
1408 case 'jpg': imagejpeg($image); break;
1409 case 'png': imagepng($image); break;
1412 // Remove image from memory
1413 imagedestroy($image);
1415 // Create selection box or array of splitted timestamp
1416 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1417 // Calculate 2-seconds timestamp
1418 $stamp = round($timestamp);
1419 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1421 // Do we have a leap year?
1423 $TEST = date('Y', time()) / 4;
1424 $M1 = date('m', time());
1425 $M2 = date('m', (time() + $timestamp));
1427 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1428 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1430 // First of all years...
1431 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1432 //* DEBUG: */ print("Y={$Y}<br />");
1434 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1435 //* DEBUG: */ print("M={$M}<br />");
1437 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1438 //* DEBUG: */ print("W={$W}<br />");
1440 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1441 //* DEBUG: */ print("D={$D}<br />");
1443 $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));
1444 //* DEBUG: */ print("h={$h}<br />");
1446 $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));
1447 //* DEBUG: */ print("m={$m}<br />");
1448 // And at last seconds...
1449 $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));
1450 //* DEBUG: */ print("s={$s}<br />");
1452 // Is seconds zero and time is < 60 seconds?
1453 if (($s == '0') && ($timestamp < 60)) {
1455 $s = round($timestamp);
1459 // Now we convert them in seconds...
1461 if ($return_array) {
1462 // Just put all data in an array for later use
1474 $OUT = "<div align=\"" . $align."\">\n";
1475 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1478 if (ereg('Y', $display) || (empty($display))) {
1479 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1482 if (ereg('M', $display) || (empty($display))) {
1483 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1486 if (ereg("W", $display) || (empty($display))) {
1487 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1490 if (ereg("D", $display) || (empty($display))) {
1491 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1494 if (ereg("h", $display) || (empty($display))) {
1495 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1498 if (ereg('m', $display) || (empty($display))) {
1499 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1502 if (ereg("s", $display) || (empty($display))) {
1503 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1509 if (ereg('Y', $display) || (empty($display))) {
1510 // Generate year selection
1511 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1512 for ($idx = '0'; $idx <= 10; $idx++) {
1513 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1514 if ($idx == $Y) $OUT .= ' selected="selected"';
1515 $OUT .= ">" . $idx."</option>\n";
1517 $OUT .= " </select></td>\n";
1519 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1522 if (ereg('M', $display) || (empty($display))) {
1523 // Generate month selection
1524 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1525 for ($idx = '0'; $idx <= 11; $idx++)
1527 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1528 if ($idx == $M) $OUT .= ' selected="selected"';
1529 $OUT .= ">" . $idx."</option>\n";
1531 $OUT .= " </select></td>\n";
1533 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1536 if (ereg("W", $display) || (empty($display))) {
1537 // Generate week selection
1538 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1539 for ($idx = '0'; $idx <= 4; $idx++) {
1540 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1541 if ($idx == $W) $OUT .= ' selected="selected"';
1542 $OUT .= ">" . $idx."</option>\n";
1544 $OUT .= " </select></td>\n";
1546 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1549 if (ereg("D", $display) || (empty($display))) {
1550 // Generate day selection
1551 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1552 for ($idx = '0'; $idx <= 31; $idx++) {
1553 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1554 if ($idx == $D) $OUT .= ' selected="selected"';
1555 $OUT .= ">" . $idx."</option>\n";
1557 $OUT .= " </select></td>\n";
1559 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1562 if (ereg("h", $display) || (empty($display))) {
1563 // Generate hour selection
1564 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1565 for ($idx = '0'; $idx <= 23; $idx++) {
1566 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1567 if ($idx == $h) $OUT .= ' selected="selected"';
1568 $OUT .= ">" . $idx."</option>\n";
1570 $OUT .= " </select></td>\n";
1572 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1575 if (ereg('m', $display) || (empty($display))) {
1576 // Generate minute selection
1577 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1578 for ($idx = '0'; $idx <= 59; $idx++) {
1579 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1580 if ($idx == $m) $OUT .= ' selected="selected"';
1581 $OUT .= ">" . $idx."</option>\n";
1583 $OUT .= " </select></td>\n";
1585 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1588 if (ereg("s", $display) || (empty($display))) {
1589 // Generate second selection
1590 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1591 for ($idx = '0'; $idx <= 59; $idx++) {
1592 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1593 if ($idx == $s) $OUT .= ' selected="selected"';
1594 $OUT .= ">" . $idx."</option>\n";
1596 $OUT .= " </select></td>\n";
1598 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1601 $OUT .= "</table>\n";
1603 // Return generated HTML code
1609 function createTimestampFromSelections ($prefix, $postData) {
1610 // Initial return value
1613 // Do we have a leap year?
1615 $TEST = date('Y', time()) / 4;
1616 $M1 = date('m', time());
1617 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1618 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1619 // First add years...
1620 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1622 $ret += $postData[$prefix."_mo"] * 2628000;
1624 $ret += $postData[$prefix."_we"] * 604800;
1626 $ret += $postData[$prefix."_da"] * 86400;
1628 $ret += $postData[$prefix."_ho"] * 3600;
1630 $ret += $postData[$prefix."_mi"] * 60;
1631 // And at last seconds...
1632 $ret += $postData[$prefix."_se"];
1633 // Return calculated value
1637 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1638 function createFancyTime ($stamp) {
1639 // Get data array with years/months/weeks/days/...
1640 $data = createTimeSelections($stamp, '', '', '', true);
1642 foreach($data as $k => $v) {
1644 // Value is greater than 0 "eval" data to return string
1645 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1650 // Do we have something there?
1651 if (strlen($ret) > 0) {
1652 // Remove leading commata and space
1653 $ret = substr($ret, 2);
1656 $ret = "0 {--_SECONDS--}";
1659 // Return fancy time string
1663 // Generates a navigation row for listing emails
1664 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1665 $SEP = ''; $TOP = '';
1666 if ($show_form === false) {
1668 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1672 for ($page = 1; $page <= $PAGES; $page++) {
1673 // Is the page currently selected or shall we generate a link to it?
1674 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1675 // Is currently selected, so only highlight it
1676 $NAV .= '<strong>-';
1678 // Open anchor tag and add base URL
1679 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1681 // Add userid when we shall show all mails from a single member
1682 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1684 // Close open anchor tag
1688 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1689 // Is currently selected, so only highlight it
1690 $NAV .= '-</strong>';
1696 // Add seperator if we have not yet reached total pages
1697 if ($page < $PAGES) $NAV .= ' | ';
1700 // Define constants only once
1701 $content['nav'] = $NAV;
1702 $content['span'] = $colspan;
1703 $content['top'] = $TOP;
1704 $content['sep'] = $SEP;
1706 // Load navigation template
1707 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1709 if ($return === true) {
1710 // Return generated HTML-Code
1718 // Extract host from script name
1719 function extractHostnameFromUrl (&$script) {
1720 // Use default SERVER_URL by default... ;) So?
1721 $url = getConfig('SERVER_URL');
1723 // Is this URL valid?
1724 if (substr($script, 0, 7) == 'http://') {
1725 // Use the hostname from script URL as new hostname
1726 $url = substr($script, 7);
1727 $extract = explode('/', $url);
1729 // Done extracting the URL :)
1732 // Extract host name
1733 $host = str_replace('http://', '', $url);
1734 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1736 // Generate relative URL
1737 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1738 if (substr(strtolower($script), 0, 7) == 'http://') {
1739 // But only if http:// is in front!
1740 $script = substr($script, (strlen($url) + 7));
1741 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1743 $script = substr($script, (strlen($url) + 8));
1746 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1747 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1753 // Send a GET request
1754 function sendGetRequest ($script, $data = array()) {
1755 // Extract host name from script
1756 $host = extractHostnameFromUrl($script);
1759 $scriptData = http_build_query($data, '', '&');
1761 // Do we have a question-mark in the script?
1762 if (strpos($script, '?') === false) {
1763 // No, so first char must be question mark
1764 $scriptData = '?' . $scriptData;
1767 $scriptData = '&' . $scriptData;
1771 $script .= $scriptData;
1773 // Generate GET request header
1774 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1775 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1776 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1777 if (isConfigEntrySet('FULL_VERSION')) {
1778 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1780 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1782 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1783 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1784 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1786 // Send the raw request
1787 $response = sendRawRequest($host, $request);
1789 // Return the result to the caller function
1793 // Send a POST request
1794 function sendPostRequest ($script, $postData) {
1795 // Is postData an array?
1796 if (!is_array($postData)) {
1798 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1799 return array('', '', '');
1802 // Extract host name from script
1803 $host = extractHostnameFromUrl($script);
1805 // Construct request
1806 $data = http_build_query($postData, '', '&');
1808 // Generate POST request header
1809 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1810 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1811 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1812 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1813 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1814 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1815 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1816 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1819 // Send the raw request
1820 $response = sendRawRequest($host, $request);
1822 // Return the result to the caller function
1826 // Sends a raw request to another host
1827 function sendRawRequest ($host, $request) {
1828 // Init errno and errdesc with 'all fine' values
1829 $errno = '0'; $errdesc = '';
1832 $response = array('', '', '');
1834 // Default is not to use proxy
1837 // Are proxy settins set?
1838 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1844 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1845 if ($useProxy === true) {
1846 // Connect to host through proxy connection
1847 $fp = @fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1849 // Connect to host directly
1850 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1854 if (!is_resource($fp)) {
1860 if ($useProxy === true) {
1861 // Generate CONNECT request header
1862 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1863 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1865 // Use login data to proxy? (username at least!)
1866 if (getConfig('proxy_username') != '') {
1868 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
1869 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1872 // Add last new-line
1873 $proxyTunnel .= getConfig('HTTP_EOL');
1874 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1877 fputs($fp, $proxyTunnel);
1881 // No response received
1885 // Read the first line
1886 $resp = trim(fgets($fp, 10240));
1887 $respArray = explode(' ', $resp);
1888 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1889 // Invalid response!
1895 fputs($fp, $request);
1898 while (!feof($fp)) {
1899 $response[] = trim(fgets($fp, 1024));
1905 // Skip first empty lines
1907 foreach ($resp as $idx => $line) {
1909 $line = trim($line);
1911 // Is this line empty?
1914 array_shift($response);
1916 // Abort on first non-empty line
1921 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1923 // Proxy agent found?
1924 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1925 // Proxy header detected, so remove two lines
1926 array_shift($response);
1927 array_shift($response);
1930 // Was the request successfull?
1931 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1932 // Not found / access forbidden
1933 $response = array('', '', '');
1940 // Taken from www.php.net eregi() user comments
1941 function isEmailValid ($email) {
1942 // Check first part of email address
1943 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1946 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1949 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1951 // Return check result
1952 return preg_match($regex, $email);
1955 // Function taken from user comments on www.php.net / function eregi()
1956 function isUrlValid ($URL, $compile=true) {
1957 // Trim URL a little
1958 $URL = trim(urldecode($URL));
1959 //* DEBUG: */ outputHtml($URL.'<br />');
1961 // Compile some chars out...
1962 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1963 //* DEBUG: */ outputHtml($URL.'<br />');
1965 // Check for the extension filter
1966 if (isExtensionActive('filter')) {
1967 // Use the extension's filter set
1968 return FILTER_VALIDATE_URL($URL, false);
1971 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1972 // https:// in front of the URLs
1973 return isUrlValidSimple($URL);
1976 // Generate a list of administrative links to a given userid
1977 function generateMemberAdminActionLinks ($userid, $status = '') {
1978 // Make sure userid is a number
1979 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1981 // Define all main targets
1982 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1984 // Begin of navigation links
1987 foreach ($targetArray as $tar) {
1988 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1989 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1990 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1991 // Locked accounts shall be unlocked
1992 $OUT .= 'UNLOCK_USER';
1994 // All other status is fine
1995 $OUT .= strtoupper($tar);
1997 $OUT .= "_TITLE--}\">{--ADMIN_";
1998 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1999 // Locked accounts shall be unlocked
2000 $OUT .= 'UNLOCK_USER';
2002 // All other status is fine
2003 $OUT .= strtoupper($tar);
2005 $OUT .= "--}</a></span> | ";
2008 // Finish navigation link
2009 $OUT = substr($OUT, 0, -7) . ']';
2015 // Generate an email link
2016 function generateEmailLink ($email, $table = 'admins') {
2017 // Default email link (INSECURE! Spammer can read this by harvester programs)
2018 $EMAIL = 'mailto:' . $email;
2020 // Check for several extensions
2021 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2022 // Create email link for contacting admin in guest area
2023 $EMAIL = generateAdminEmailLink($email);
2024 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2025 // Create email link for contacting a member within admin area (or later in other areas, too?)
2026 $EMAIL = generateUserEmailLink($email, 'admin');
2027 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2028 // Create email link to contact sponsor within admin area (or like the link above?)
2029 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2032 // Shall I close the link when there is no admin?
2033 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2035 // Return email link
2039 // Generate a hash for extra-security for all passwords
2040 function generateHash ($plainText, $salt = '') {
2041 // Is the required extension 'sql_patches' there and a salt is not given?
2042 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2043 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2044 return md5($plainText);
2047 // Do we miss an arry element here?
2048 if (!isConfigEntrySet('file_hash')) {
2050 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2053 // When the salt is empty build a new one, else use the first x configured characters as the salt
2055 // Build server string (inc/databases.php is no longer updated with every commit)
2056 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2059 $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');
2062 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2064 // Calculate number for generating the code
2065 $a = time() + getConfig('_ADD') - 1;
2067 // Generate SHA1 sum from modula of number and the prime number
2068 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2069 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2070 $sha1 = scrambleString($sha1);
2071 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2072 //* DEBUG: */ $sha1b = descrambleString($sha1);
2073 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2075 // Generate the password salt string
2076 $salt = substr($sha1, 0, getConfig('salt_length'));
2077 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2080 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2081 $salt = substr($salt, 0, getConfig('salt_length'));
2082 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2084 // Sanity check on salt
2085 if (strlen($salt) != getConfig('salt_length')) {
2087 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2092 return $salt.sha1($salt . $plainText);
2095 // Scramble a string
2096 function scrambleString($str) {
2100 // Final check, in case of failture it will return unscrambled string
2101 if (strlen($str) > 40) {
2102 // The string is to long
2104 } elseif (strlen($str) == 40) {
2106 $scrambleNums = explode(':', getConfig('pass_scramble'));
2108 // Generate new numbers
2109 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2112 // Scramble string here
2113 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2114 for ($idx = '0'; $idx < strlen($str); $idx++) {
2115 // Get char on scrambled position
2116 $char = substr($str, $scrambleNums[$idx], 1);
2118 // Add it to final output string
2119 $scrambled .= $char;
2122 // Return scrambled string
2123 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2127 // De-scramble a string scrambled by scrambleString()
2128 function descrambleString($str) {
2129 // Scramble only 40 chars long strings
2130 if (strlen($str) != 40) return $str;
2132 // Load numbers from config
2133 $scrambleNums = explode(':', getConfig('pass_scramble'));
2136 if (count($scrambleNums) != 40) return $str;
2138 // Begin descrambling
2139 $orig = str_repeat(' ', 40);
2140 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2141 for ($idx = '0'; $idx < 40; $idx++) {
2142 $char = substr($str, $idx, 1);
2143 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2146 // Return scrambled string
2147 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2151 // Generated a "string" for scrambling
2152 function genScrambleString ($len) {
2153 // Prepare array for the numbers
2154 $scrambleNumbers = array();
2156 // First we need to setup randomized numbers from 0 to 31
2157 for ($idx = '0'; $idx < $len; $idx++) {
2159 $rand = mt_rand(0, ($len -1));
2161 // Check for it by creating more numbers
2162 while (array_key_exists($rand, $scrambleNumbers)) {
2163 $rand = mt_rand(0, ($len -1));
2167 $scrambleNumbers[$rand] = $rand;
2170 // So let's create the string for storing it in database
2171 $scrambleString = implode(':', $scrambleNumbers);
2172 return $scrambleString;
2175 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2176 function generatePassString ($passHash) {
2177 // Return vanilla password hash
2180 // Is a secret key and master salt already initialized?
2181 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2182 // Only calculate when the secret key is generated
2183 $newHash = ''; $start = 9;
2184 for ($idx = '0'; $idx < 10; $idx++) {
2185 $part1 = hexdec(substr($passHash, $start, 4));
2186 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2187 $mod = dechex($idx);
2188 if ($part1 > $part2) {
2189 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2190 } elseif ($part2 > $part1) {
2191 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2193 $mod = substr($mod, 0, 4);
2194 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2195 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2196 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2201 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2202 $ret = generateHash($newHash, getConfig('master_salt'));
2203 //* DEBUG: */ print('ret='.$ret.'<br />');
2206 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2207 $ret = md5($passHash);
2208 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2215 // Fix "deleted" cookies
2216 function fixDeletedCookies ($cookies) {
2217 // Is this an array with entries?
2218 if ((is_array($cookies)) && (count($cookies) > 0)) {
2219 // Then check all cookies if they are marked as deleted!
2220 foreach ($cookies as $cookieName) {
2221 // Is the cookie set to "deleted"?
2222 if (getSession($cookieName) == 'deleted') {
2223 setSession($cookieName, '');
2229 // Output error messages in a fasioned way and die...
2230 function app_die ($F, $L, $message) {
2231 // Check if Script is already dieing and not let it kill itself another 1000 times
2232 if (!isset($GLOBALS['app_died'])) {
2233 // Make sure, that the script realy realy diese here and now
2234 $GLOBALS['app_died'] = true;
2237 loadIncludeOnce('inc/header.php');
2239 // Rewrite message for output
2240 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2242 // Better log this message away
2243 logDebugMessage($F, $L, $message);
2245 // Load the message template
2246 loadTemplate('admin_settings_saved', false, $message);
2249 loadIncludeOnce('inc/footer.php');
2251 // Script tried to kill itself twice
2252 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2256 // Display parsing time and number of SQL queries in footer
2257 function displayParsingTime() {
2258 // Is the timer started?
2259 if (!isset($GLOBALS['startTime'])) {
2265 $endTime = microtime(true);
2267 // "Explode" both times
2268 $start = explode(' ', $GLOBALS['startTime']);
2269 $end = explode(' ', $endTime);
2270 $runTime = $end[0] - $start[0];
2271 if ($runTime < 0) $runTime = '0';
2275 'runtime' => translateComma($runTime),
2276 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2279 // Load the template
2280 loadTemplate('show_timings', false, $content);
2283 // Check wether a boolean constant is set
2284 // Taken from user comments in PHP documentation for function constant()
2285 function isBooleanConstantAndTrue ($constName) { // : Boolean
2286 // Failed by default
2290 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2292 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2293 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2296 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2297 if (defined($constName)) {
2299 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2300 $res = (constant($constName) === true);
2304 $GLOBALS['cache_array']['const'][$constName] = $res;
2306 //* DEBUG: */ var_dump($res);
2312 // Checks if a given apache module is loaded
2313 function isApacheModuleLoaded ($apacheModule) {
2314 // Check it and return result
2315 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2318 // Get current theme name
2319 function getCurrentTheme () {
2320 // The default theme is 'default'... ;-)
2323 // Load default theme if not empty from configuration
2324 if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
2326 if (!isSessionVariableSet('mxchange_theme')) {
2327 // Set default theme
2329 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2330 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2331 // Get theme from cookie
2332 $ret = getSession('mxchange_theme');
2335 if (getThemeId($ret) == '0') {
2336 // Fix it to default
2339 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2340 // Prepare FQFN for checking
2341 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2343 // Installation mode active
2344 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2345 // Set cookie from URL data
2346 setTheme(getRequestElement('theme'));
2347 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2348 // Set cookie from posted data
2349 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2353 $ret = getSession('mxchange_theme');
2355 // Invalid design, reset cookie
2359 // Return theme value
2363 // Setter for theme in session
2364 function setTheme ($newTheme) {
2365 setSession('mxchange_theme', $newTheme);
2368 // Get id from theme
2369 // @TODO Try to move this to inc/libs/theme_functions.php
2370 function getThemeId ($name) {
2371 // Is the extension 'theme' installed?
2372 if (!isExtensionActive('theme')) {
2380 // Is the cache entry there?
2381 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2382 // Get the version from cache
2383 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2386 incrementStatsEntry('cache_hits');
2387 } elseif (getExtensionVersion('cache') != '0.1.8') {
2388 // Check if current theme is already imported or not
2389 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2390 array($name), __FUNCTION__, __LINE__);
2393 if (SQL_NUMROWS($result) == 1) {
2395 list($id) = SQL_FETCHROW($result);
2399 SQL_FREERESULT($result);
2406 // Generates an error code from given account status
2407 function generateErrorCodeFromUserStatus ($status='') {
2408 // If no status is provided, use the default, cached
2409 if ((empty($status)) && (isMember())) {
2411 $status = getUserData('status');
2414 // Default error code if unknown account status
2415 $errorCode = getCode('UNKNOWN_STATUS');
2417 // Generate constant name
2418 $codeName = sprintf("ID_%s", $status);
2420 // Is the constant there?
2421 if (isCodeSet($codeName)) {
2423 $errorCode = getCode($codeName);
2426 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2429 // Return error code
2433 // Function to search for the last modifified file
2434 function searchDirsRecursive ($dir, &$last_changed) {
2436 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2437 // Does it match what we are looking for? (We skip a lot files already!)
2438 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2439 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2440 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2441 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2443 // Walk through all entries
2444 foreach ($ds as $d) {
2445 // Generate proper FQFN
2446 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2448 // Is it a file and readable?
2449 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2450 if (isDirectory($FQFN)) {
2451 // $FQFN is a directory so also crawl into this directory
2453 if (!empty($dir)) $newDir = $dir . '/'. $d;
2454 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2455 searchDirsRecursive($newDir, $last_changed);
2456 } elseif (isFileReadable($FQFN)) {
2457 // $FQFN is a filename and no directory
2458 $time = filemtime($FQFN);
2459 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2460 if ($last_changed['time'] < $time) {
2461 // This file is newer as the file before
2462 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2463 $last_changed['path_name'] = $FQFN;
2464 $last_changed['time'] = $time;
2470 // "Getter" for revision/version data
2471 function getActualVersion ($type = 'Revision') {
2472 // By default nothing is new... ;-)
2475 // Is the cache entry there?
2476 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2477 // Found so increase cache hit
2478 incrementStatsEntry('cache_hits');
2481 return $GLOBALS['cache_array']['revision'][$type][0];
2483 // FQFN of revision file
2484 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2486 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2487 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2488 // Forced rebuild of .revision file
2491 // Check for revision file
2492 if (!isFileReadable($FQFN)) {
2493 // Not found, so we need to create it
2496 // Revision file found
2497 $ins_vers = explode("\n", readFromFile($FQFN));
2499 // Get array for mapping information
2500 $mapper = array_flip(getSearchFor());
2501 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2503 // Is the content valid?
2504 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2505 // File needs update!
2508 // Generate fake cache entry
2509 foreach ($mapper as $map=>$idx) {
2510 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2513 // Return found value
2514 return trim($ins_vers[$mapper[$type]]);
2519 // Has it been updated?
2520 if ($new === true) {
2522 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2524 // ... and call recursive
2525 return getActualVersion($type);
2530 // Repares an array we are looking for
2531 // 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
2532 function getSearchFor () {
2533 // Add Revision, Date, Tag and Author
2534 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2536 // Return the created array
2540 // @TODO Please describe this function
2541 function getArrayFromActualVersion () {
2545 // Directory to start with search
2546 $last_changed = array(
2551 // Init return array
2552 $akt_vers = array();
2554 // Init value for counting the founded keywords
2557 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2558 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2561 $last_file = readFromFile($last_changed['path_name']);
2563 // Get all the keywords to search for
2564 $searchFor = getSearchFor();
2566 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2567 foreach ($searchFor as $search) {
2568 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2569 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2570 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2571 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2574 // Save the last-changed filename for debugging
2575 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2577 // at least 3 keyword-Tags are needed for propper values
2578 if ($res && $res >= 3
2579 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2580 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2581 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2582 // Prepare content witch need special treadment
2584 // Prepare timestamp for date
2585 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2586 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2588 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2589 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2590 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2594 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2595 $version = sendGetRequest('check-updates3.php');
2598 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2599 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2600 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2601 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2602 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2603 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2606 // Return prepared array
2607 return $GLOBALS['cache_array']['revision'];
2610 // Back-ported from the new ship-simu engine. :-)
2611 function debug_get_printable_backtrace () {
2613 $backtrace = "<ol>\n";
2615 // Get and prepare backtrace for output
2616 $backtraceArray = debug_backtrace();
2617 foreach ($backtraceArray as $key => $trace) {
2618 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2619 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2620 if (!isset($trace['args'])) $trace['args'] = array();
2621 $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";
2625 $backtrace .= "</ol>\n";
2627 // Return the backtrace
2631 // Output a debug backtrace to the user
2632 function debug_report_bug ($message = '') {
2633 // Is this already called?
2634 if (isset($GLOBALS[__FUNCTION__])) {
2636 print 'Message:'.$message.'<br />Backtrace:<pre>';
2637 debug_print_backtrace();
2641 // Set this function as called
2642 $GLOBALS[__FUNCTION__] = true;
2647 // Is the optional message set?
2648 if (!empty($message)) {
2650 $debug = sprintf("Note: %s<br />\n",
2654 // @TODO Add a little more infos here
2655 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2659 $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a> and include the logfile from <strong>" . getConfig('CACHE_PATH') . "debug.log</strong> in your report (you can now attach files):<pre>";
2660 $debug .= debug_get_printable_backtrace();
2661 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2662 $debug .= "Thank you for finding bugs.";
2665 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2669 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2670 function generateSeed () {
2671 list($usec, $sec) = explode(' ', microtime());
2672 $microTime = (((float)$sec + (float)$usec)) * 100000;
2676 // Converts a message code to a human-readable message
2677 function getMessageFromErrorCode ($code) {
2681 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2682 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2683 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2684 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2685 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2686 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2687 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2688 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2689 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2690 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2691 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2692 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2693 case getCode('ID_GUEST') : $message = getMessage('LOGIN_ID_GUEST'); break;
2694 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2695 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2696 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2697 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2698 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2699 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2700 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2701 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2702 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2703 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2704 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2705 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2706 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2707 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2708 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2709 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2711 case getCode('ERROR_MAILID'):
2712 if (isExtensionActive('mailid', true)) {
2713 $message = getMessage('ERROR_CONFIRMING_MAIL');
2715 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2719 case getCode('EXTENSION_PROBLEM'):
2720 if (isGetRequestElementSet('ext')) {
2721 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2723 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2727 case getCode('URL_TLOCK'):
2728 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2729 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2731 // Load timestamp from last order
2732 list($timestamp) = SQL_FETCHROW($result);
2733 $timestamp = generateDateTime($timestamp, 1);
2736 SQL_FREERESULT($result);
2738 // Calculate hours...
2739 $STD = round(getConfig('url_tlock') / 60 / 60);
2742 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2745 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2747 // Finally contruct the message
2748 // @TODO Rewrite this old lost code to a template
2749 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2750 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2751 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2755 // Missing/invalid code
2756 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2759 logDebugMessage(__FUNCTION__, __LINE__, $message);
2763 // Return the message
2767 // Compile characters which are allowed in URLs
2768 function compileUriCode ($code, $simple = true) {
2769 // Compile constants
2770 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2772 // Compile QUOT and other non-HTML codes
2773 $code = str_replace('{DOT}', '.',
2774 str_replace('{SLASH}', '/',
2775 str_replace('{QUOT}', "'",
2776 str_replace('{DOLLAR}', '$',
2777 str_replace('{OPEN_ANCHOR}', '(',
2778 str_replace('{CLOSE_ANCHOR}', ')',
2779 str_replace('{OPEN_SQR}', '[',
2780 str_replace('{CLOSE_SQR}', ']',
2781 str_replace('{PER}', '%',
2785 // Return compiled code
2789 // Function taken from user comments on www.php.net / function eregi()
2790 function isUrlValidSimple ($url) {
2792 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2794 // Allows http and https
2795 $http = "(http|https)+(:\/\/)";
2797 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2798 // Test double-domains (e.g. .de.vu)
2799 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2801 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2803 $dir = "((/)+([-_\.[:alnum:]])+)*";
2805 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2806 // ... and the string after and including question character
2807 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2808 // Pattern for URLs like http://url/dir/doc.html?var=value
2809 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2810 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2811 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2812 // Pattern for URLs like http://url/dir/?var=value
2813 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2814 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2815 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2816 // Pattern for URLs like http://url/dir/page.ext
2817 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2818 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2819 $pattern['ipdp'] = $http . $ip . $dir . $page;
2820 // Pattern for URLs like http://url/dir
2821 $pattern['d1d'] = $http . $domain1 . $dir;
2822 $pattern['d2d'] = $http . $domain2 . $dir;
2823 $pattern['ipd'] = $http . $ip . $dir;
2824 // Pattern for URLs like http://url/?var=value
2825 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2826 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2827 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2828 // Pattern for URLs like http://url?var=value
2829 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2830 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2831 $pattern['ipg12'] = $http . $ip . $getstring1;
2832 // Test all patterns
2834 foreach ($pattern as $key => $pat) {
2836 if (isDebugRegExpressionEnabled()) {
2837 // @TODO Are these convertions still required?
2838 $pat = str_replace('.', "\.", $pat);
2839 $pat = str_replace('@', "\@", $pat);
2840 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2843 // Check if expression matches
2844 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2847 if ($reg === true) break;
2850 // Return true/false
2854 // Wtites data to a config.php-style file
2855 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2856 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2857 // Initialize some variables
2863 // Is the file there and read-/write-able?
2864 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2865 $search = 'CFG: ' . $comment;
2866 $tmp = $FQFN . '.tmp';
2868 // Open the source file
2869 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2871 // Is the resource valid?
2872 if (is_resource($fp)) {
2873 // Open temporary file
2874 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2876 // Is the resource again valid?
2877 if (is_resource($fp_tmp)) {
2878 // Mark temporary file as readable
2879 $GLOBALS['file_readable'][$tmp] = true;
2882 while (!feof($fp)) {
2883 // Read from source file
2884 $line = fgets ($fp, 1024);
2886 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2889 if ($next === $seek) {
2891 $line = $prefix . $DATA . $suffix . "\n";
2897 // Write to temp file
2898 fputs($fp_tmp, $line);
2904 // Finished writing tmp file
2908 // Close source file
2911 if (($done === true) && ($found === true)) {
2912 // Copy back tmp file and delete tmp :-)
2913 copyFileVerified($tmp, $FQFN, 0644);
2914 return removeFile($tmp);
2915 } elseif ($found === false) {
2916 outputHtml('<strong>CHANGE:</strong> 404!');
2918 outputHtml('<strong>TMP:</strong> UNDONE!');
2922 // File not found, not readable or writeable
2923 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2926 // An error was detected!
2929 // Send notification to admin
2930 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2931 if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
2933 sendAdminsEmails($subject, $templateName, $content, $userid);
2935 // Send out out-dated way
2936 $message = loadEmailTemplate($templateName, $content, $userid);
2937 sendAdminEmails($subject, $message);
2941 // Debug message logger
2942 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2943 // Is debug mode enabled?
2944 if ((isDebugModeEnabled()) || ($force === true)) {
2946 $message = str_replace("\r", '', str_replace("\n", '', $message));
2948 // Log this message away, we better don't call app_die() here to prevent an endless loop
2949 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2950 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2955 // Handle extra values
2956 function handleExtraValues ($filterFunction, $value, $extraValue) {
2957 // Default is the value itself
2960 // Do we have a special filter function?
2961 if (!empty($filterFunction)) {
2962 // Does the filter function exist?
2963 if (function_exists($filterFunction)) {
2964 // Do we have extra parameters here?
2965 if (!empty($extraValue)) {
2966 // Put both parameters in one new array by default
2967 $args = array($value, $extraValue);
2969 // If we have an array simply use it and pre-extend it with our value
2970 if (is_array($extraValue)) {
2971 // Make the new args array
2972 $args = merge_array(array($value), $extraValue);
2975 // Call the multi-parameter call-back
2976 $ret = call_user_func_array($filterFunction, $args);
2978 // One parameter call
2979 $ret = call_user_func($filterFunction, $value);
2988 // Converts timestamp selections into a timestamp
2989 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2990 // Init test variable
2994 // Get last three chars
2995 $test = substr($id, -3);
2997 // Improved way of checking! :-)
2998 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2999 // Found a multi-selection for timings?
3000 $test = substr($id, 0, -3);
3001 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)) {
3002 // Generate timestamp
3003 $postData[$test] = createTimestampFromSelections($test, $postData);
3004 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
3005 $GLOBALS['skip_config'][$test] = true;
3007 // Remove data from array
3008 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3009 unset($postData[$test . '_' . $rem]);
3020 // Reverts the german decimal comma into Computer decimal dot
3021 function convertCommaToDot ($str) {
3022 // Default float is not a float... ;-)
3025 // Which language is selected?
3026 switch (getLanguage()) {
3027 case 'de': // German language
3028 // Remove german thousand dots first
3029 $str = str_replace('.', '', $str);
3031 // Replace german commata with decimal dot and cast it
3032 $float = (float)str_replace(',', '.', $str);
3035 default: // US and so on
3036 // Remove thousand dots first and cast
3037 $float = (float)str_replace(',', '', $str);
3045 // Handle menu-depending failed logins and return the rendered content
3046 function handleLoginFailtures ($accessLevel) {
3047 // Default output is empty ;-)
3050 // Is the session data set?
3051 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3052 // Ignore zero values
3053 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3054 // Non-guest has login failures found, get both data and prepare it for template
3055 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3057 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3058 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3062 $OUT = loadTemplate('login_failures', true, $content);
3065 // Reset session data
3066 setSession('mxchange_' . $accessLevel.'_failures', '');
3067 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3070 // Return rendered content
3075 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3077 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3079 // Shall I remove the cache file?
3080 if (isCacheInstanceValid()) {
3082 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3084 $GLOBALS['cache_instance']->removeCacheFile($force);
3087 // Include file given?
3090 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3092 // Is the include there?
3093 if (isIncludeReadable($inc)) {
3094 // And rebuild it from scratch
3095 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3098 // Include not found!
3099 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3105 // Determines the real remote address
3106 function determineRealRemoteAddress () {
3107 // Is a proxy in use?
3108 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3110 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3111 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3112 // Yet, another proxy
3113 $address = $_SERVER['HTTP_CLIENT_IP'];
3115 // The regular address when no proxy was used
3116 $address = $_SERVER['REMOTE_ADDR'];
3119 // This strips out the real address from proxy output
3120 if (strstr($address, ',')) {
3121 $addressArray = explode(',', $address);
3122 $address = $addressArray[0];
3125 // Return the result
3129 // Adds a bonus mail to the queue
3130 // This is a high-level function!
3131 function addNewBonusMail ($data, $mode = '', $output=true) {
3132 // Use mode from data if not set and availble ;-)
3133 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3135 // Generate receiver list
3136 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3139 if (!empty($RECEIVER)) {
3140 // Add bonus mail to queue
3141 addBonusMailToQueue(
3153 // Mail inserted into bonus pool
3154 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3155 } elseif ($output) {
3156 // More entered than can be reached!
3157 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3160 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3164 // Determines referal id and sets it
3165 function determineReferalId () {
3166 // Skip this in non-html-mode and outside ref.php
3167 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3169 // Check if refid is set
3170 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3172 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3173 // The variable user comes from the click-counter script click.php and we only accept this here
3174 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3175 } elseif (isPostRequestElementSet('refid')) {
3176 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3177 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3178 } elseif (isGetRequestElementSet('refid')) {
3179 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3180 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3181 } elseif (isGetRequestElementSet('ref')) {
3182 // Set refid=ref (the referal link uses such variable)
3183 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3184 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3185 // Set session refid als global
3186 $GLOBALS['refid'] = bigintval(getSession('refid'));
3187 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3188 // Select a random user which has confirmed enougth mails
3189 $GLOBALS['refid'] = determineRandomReferalId();
3190 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3191 // Set default refid as refid in URL
3192 $GLOBALS['refid'] = getConfig('def_refid');
3194 // No default id when sql_patches is not installed or none set
3195 $GLOBALS['refid'] = '0';
3198 // Set cookie when default refid > 0
3199 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3200 // Default is not found
3203 // Do we have nickname or userid set?
3204 if (isNicknameUsed($GLOBALS['refid'])) {
3205 // Nickname in URL, so load the id
3206 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3207 } elseif ($GLOBALS['refid'] > 0) {
3208 // Direct userid entered
3209 $found = fetchUserData($GLOBALS['refid']);
3212 // Is the record valid?
3213 if (($found === false) || (!isUserDataValid())) {
3214 // No, then reset referal id
3215 $GLOBALS['refid'] = getConfig('def_refid');
3219 setSession('refid', $GLOBALS['refid']);
3222 // Return determined refid
3223 return $GLOBALS['refid'];
3226 // Enables the reset mode and runs it
3227 function doReset () {
3228 // Enable the reset mode
3229 $GLOBALS['reset_enabled'] = true;
3232 runFilterChain('reset');
3235 // Our shutdown-function
3236 function shutdown () {
3237 // Call the filter chain 'shutdown'
3238 runFilterChain('shutdown', null);
3240 if (SQL_IS_LINK_UP()) {
3242 SQL_CLOSE(__FILE__, __LINE__);
3243 } elseif (!isInstallationPhase()) {
3245 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3248 // Stop executing here
3253 function initMemberId () {
3254 $GLOBALS['member_id'] = '0';
3257 // Setter for member id
3258 function setMemberId ($memberid) {
3259 // We should not set member id to zero
3260 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3263 $GLOBALS['member_id'] = bigintval($memberid);
3266 // Getter for member id or returns zero
3267 function getMemberId () {
3268 // Default member id
3271 // Is the member id set?
3272 if (isMemberIdSet()) {
3274 $memberid = $GLOBALS['member_id'];
3281 // Checks ether the member id is set
3282 function isMemberIdSet () {
3283 return (isset($GLOBALS['member_id']));
3286 // Handle message codes from URL
3287 function handleCodeMessage () {
3288 if (isGetRequestElementSet('code')) {
3289 // Default extension is 'unknown'
3292 // Is extension given?
3293 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3295 // Convert the 'code' parameter from URL to a human-readable message
3296 $message = getMessageFromErrorCode(getRequestElement('code'));
3298 // Load message template
3299 loadTemplate('message', false, $message);
3303 // Setter for extra title
3304 function setExtraTitle ($extraTitle) {
3305 $GLOBALS['extra_title'] = $extraTitle;
3308 // Getter for extra title
3309 function getExtraTitle () {
3310 // Is the extra title set?
3311 if (!isExtraTitleSet()) {
3312 // No, then abort here
3313 debug_report_bug('extra_title is not set!');
3317 return $GLOBALS['extra_title'];
3320 // Checks if the extra title is set
3321 function isExtraTitleSet () {
3322 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3325 // Generates a 'extension foo inactive' message
3326 function generateExtensionInactiveMessage ($ext_name) {
3327 // Is the extension empty?
3328 if (empty($ext_name)) {
3329 // This should not happen
3330 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3334 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3336 // Is an admin logged in?
3338 // Then output admin message
3339 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3342 // Return prepared message
3346 // Generates a 'extension foo not installed' message
3347 function generateExtensionNotInstalledMessage ($ext_name) {
3348 // Is the extension empty?
3349 if (empty($ext_name)) {
3350 // This should not happen
3351 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3355 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3357 // Is an admin logged in?
3359 // Then output admin message
3360 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3363 // Return prepared message
3367 // Generates a message depending on if the extension is not installed or not
3369 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3373 // Is the extension not installed or just deactivated?
3374 switch (isExtensionInstalled($ext_name)) {
3375 case true; // Deactivated!
3376 $message = generateExtensionInactiveMessage($ext_name);
3379 case false; // Not installed!
3380 $message = generateExtensionNotInstalledMessage($ext_name);
3383 default: // Should not happen!
3384 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3385 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3389 // Return the message
3393 // Reads a directory recursively by default and searches for files not matching
3394 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3395 // a whole directory.
3396 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3397 // Add default entries we should exclude
3398 $excludeArray[] = '.';
3399 $excludeArray[] = '..';
3400 $excludeArray[] = '.svn';
3401 $excludeArray[] = '.htaccess';
3403 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3408 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3411 while ($baseFile = readdir($dirPointer)) {
3412 // Exclude '.', '..' and entries in $excludeArray automatically
3413 if (in_array($baseFile, $excludeArray, true)) {
3415 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3419 // Construct include filename and FQFN
3420 $fileName = $baseDir . $baseFile;
3421 $FQFN = getConfig('PATH') . $fileName;
3423 // Remove double slashes
3424 $FQFN = str_replace('//', '/', $FQFN);
3426 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3427 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3428 // These Lines are only for debugging!!
3429 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3430 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3431 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3437 // Skip also files with non-matching prefix genericly
3438 if (($recursive === true) && (isDirectory($FQFN))) {
3439 // Is a redirectory so read it as well
3440 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3442 // And skip further processing
3444 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3446 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3448 } elseif (!isFileReadable($FQFN)) {
3449 // Not readable so skip it
3450 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3454 // Is the file a PHP script or other?
3455 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3456 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3457 // Is this a valid include file?
3458 if ($extension == '.php') {
3459 // Remove both for extension name
3460 $extName = substr($baseFile, strlen($prefix), -4);
3462 // Is the extension valid and active?
3463 if (isExtensionNameValid($extName)) {
3464 // Then add this file
3465 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3466 $files[] = $fileName;
3468 // Add non-extension files as well
3469 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3470 if ($addBaseDir === true) {
3471 $files[] = $fileName;
3473 $files[] = $baseFile;
3477 // We found .php file but should not search for them, why?
3478 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3480 } elseif (substr($baseFile, -4, 4) == $extension) {
3481 // Other, generic file found
3482 $files[] = $fileName;
3487 closedir($dirPointer);
3492 // Return array with include files
3493 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3497 // Maps a module name into a database table name
3498 function mapModuleToTable ($moduleName) {
3499 // Map only these, still lame code...
3500 switch ($moduleName) {
3501 // 'index' is the guest's menu
3502 case 'index': $moduleName = 'guest'; break;
3503 // ... and 'login' the member's menu
3504 case 'login': $moduleName = 'member'; break;
3505 // Anything else will not be mapped, silently.
3512 // Add SQL debug data to array for later output
3513 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3514 // Already executed?
3515 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3516 // Then abort here, we don't need to profile a query twice
3520 // Remeber this as profiled (or not, but we don't care here)
3521 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3523 // Do we have cache?
3524 if (!isset($GLOBALS['debug_sql_available'])) {
3525 // Check it and cache it in $GLOBALS
3526 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3529 // Don't execute anything here if we don't need or ext-other is missing
3530 if ($GLOBALS['debug_sql_available'] === false) {
3536 'num_rows' => SQL_NUMROWS($result),
3537 'affected' => SQL_AFFECTEDROWS(),
3538 'sql_str' => $sqlString,
3539 'timing' => $timing,
3540 'file' => basename($F),
3545 $GLOBALS['debug_sqls'][] = $record;
3548 // Initializes the cache instance
3549 function initCacheInstance () {
3550 // Load include for CacheSystem class
3551 loadIncludeOnce('inc/classes/cachesystem.class.php');
3553 // Initialize cache system only when it's needed
3554 $GLOBALS['cache_instance'] = new CacheSystem();
3555 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3556 // Failed to initialize cache sustem
3557 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3561 // Getter for message from array or raw message
3562 function getMessageFromIndexedArray ($message, $pos, $array) {
3563 // Check if the requested message was found in array
3564 if (isset($array[$pos])) {
3565 // ... if yes then use it!
3566 $ret = $array[$pos];
3568 // ... else use default message
3576 // Print code with line numbers
3577 function linenumberCode ($code) {
3578 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3579 $count_lines = count($codeE);
3581 $r = 'Line | Code:<br />';
3582 foreach($codeE as $line => $c) {
3583 $r .= '<div class="line"><span class="linenum">';
3584 if ($count_lines == 1) {
3587 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3592 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3595 return '<div class="code">' . $r . '</div>';
3598 // Convert ';' to ', ' for e.g. receiver list
3599 function convertReceivers ($old) {
3600 return str_replace(';', ', ', $old);
3603 // Determines the right page title
3604 function determinePageTitle () {
3605 // Config and database connection valid?
3606 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3610 // Title decoration enabled?
3611 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
3613 // Do we have some extra title?
3614 if (isExtraTitleSet()) {
3616 $TITLE .= getExtraTitle() . ' by ';
3620 $TITLE .= getConfig('MAIN_TITLE');
3622 // Add title of module? (middle decoration will also be added!)
3623 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3624 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3627 // Add title from what file
3629 if (getModule() == 'login') $mode = 'member';
3630 elseif (getModule() == 'index') $mode = 'guest';
3631 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= " ".trim(getConfig('title_middle'))." ".getModuleDescription($mode, getWhat());
3633 // Add title decorations? (right)
3634 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= " ".trim(getConfig('title_right'));
3636 // Remember title in constant for the template
3637 $pageTitle = $TITLE;
3638 } elseif ((isInstalled()) && (isAdminRegistered())) {
3639 // Installed, admin registered but no ext-sql_patches
3640 $pageTitle = '[-- ' . getConfig('MAIN_TITLE').' - '.getModuleTitle(getModule()) . ' --]';
3641 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3642 // Installed but no admin registered
3643 $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
3644 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3645 // Installation mode
3646 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3648 // Configuration not found!
3649 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3651 // Do not add the fatal message in installation mode
3652 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3659 // Checks wethere there is a cache file there. This function is cached.
3660 function isTemplateCached ($template) {
3661 // Do we have cached this result?
3662 if (!isset($GLOBALS['template_cache'][$template])) {
3664 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3667 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3671 return $GLOBALS['template_cache'][$template];
3674 // Flushes non-flushed template cache to disk
3675 function flushTemplateCache ($template, $eval) {
3676 // Is this cache flushed?
3677 if ((!isTemplateCached($template)) && ($eval != '404')) {
3679 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3681 // Replace username with a call
3682 $eval = str_replace('$username', '".getUsername()."', $eval);
3685 writeToFile($FQFN, $eval, true);
3689 // Reads a template cache
3690 function readTemplateCache ($template) {
3692 if (isTemplateCached($template)) {
3694 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3697 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3701 return $GLOBALS['template_eval'][$template];
3704 //////////////////////////////////////////////////
3705 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3706 //////////////////////////////////////////////////
3708 if (!function_exists('html_entity_decode')) {
3709 // Taken from documentation on www.php.net
3710 function html_entity_decode ($string) {
3711 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3712 $trans_tbl = array_flip($trans_tbl);
3713 return strtr($string, $trans_tbl);
3717 if (!function_exists('http_build_query')) {
3718 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3719 function http_build_query($data, $prefix='', $sep='', $key='') {
3721 foreach ((array)$data as $k => $v) {
3722 if (is_int($k) && $prefix != null) {
3723 $k = urlencode($prefix . $k);
3726 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3728 if (is_array($v) || is_object($v)) {
3729 array_push($ret, http_build_query($v, '', $sep, $k));
3731 array_push($ret, $k.'='.urlencode($v));
3735 if (empty($sep)) $sep = ini_get('arg_separator.output');
3737 return implode($sep, $ret);