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 $username = getMessage('USERNAME_UNKNOWN');
48 if (isset($GLOBALS['username'])) $username = getUsername();
50 // Do we have HTML-Code here?
51 if (!empty($htmlCode)) {
52 // Yes, so we handle it as you have configured
53 switch (getConfig('OUTPUT_MODE')) {
55 // That's why you don't need any \n at the end of your HTML code... :-)
56 if (getPhpCaching() == 'on') {
57 // Output into PHP's internal buffer
58 outputRawCode($htmlCode);
60 // That's why you don't need any \n at the end of your HTML code... :-)
61 if ($newLine === true) print("\n");
63 // Render mode for old or lame servers...
64 $GLOBALS['output'] .= $htmlCode;
66 // That's why you don't need any \n at the end of your HTML code... :-)
67 if ($newLine === true) $GLOBALS['output'] .= "\n";
72 // If we are switching from render to direct output rendered code
73 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
75 // The same as above... ^
76 outputRawCode($htmlCode);
77 if ($newLine) print("\n");
81 // Huh, something goes wrong or maybe you have edited config.php ???
82 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
85 } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
86 // Headers already sent?
89 logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
91 // Trigger an user error
92 debug_report_bug('Headers are already sent!');
95 // Output cached HTML code
96 $GLOBALS['output'] = ob_get_contents();
98 // Clear output buffer for later output if output is found
99 if (!empty($GLOBALS['output'])) {
104 sendHeader('HTTP/1.1 200');
107 $now = gmdate('D, d M Y H:i:s') . ' GMT';
109 // General headers for no caching
110 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
111 sendHeader('Last-Modified: ' . $now);
112 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
113 sendHeader('Pragma: no-cache'); // HTTP/1.0
114 sendHeader('Connection: Close');
115 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
116 sendHeader('Content-language: ' . getLanguage());
118 // Extension 'rewrite' installed?
119 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
120 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
126 // Compile and run finished rendered HTML code
127 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
128 // Prepare the content and eval() it...
133 $eval = "\$newContent = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";";
136 // Was that eval okay?
137 if (empty($newContent)) {
138 // Something went wrong!
139 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>');
141 $GLOBALS['output'] = $newContent;
147 // Output code here, DO NOT REMOVE! ;-)
148 outputRawCode($GLOBALS['output']);
149 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
150 // Rewrite links when rewrite extension is active
151 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
152 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
155 // Compile and run finished rendered HTML code
156 while (strpos($GLOBALS['output'], '{!') > 0) {
157 eval("\$GLOBALS['output'] = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";");
160 // Output code here, DO NOT REMOVE! ;-)
161 outputRawCode($GLOBALS['output']);
165 // Output the raw HTML code
166 function outputRawCode ($htmlCode) {
167 // Output stripped HTML code to avoid broken JavaScript code, etc.
168 print(stripslashes(stripslashes($htmlCode)));
170 // Flush the output if only getPhpCaching() is not 'on'
171 if (getPhpCaching() != 'on') {
177 // Init fatal message array
178 function initFatalMessages () {
179 $GLOBALS['fatal_messages'] = array();
182 // Getter for whole fatal error messages
183 function getFatalArray () {
184 return $GLOBALS['fatal_messages'];
187 // Add a fatal error message to the queue array
188 function addFatalMessage ($F, $L, $message, $extra='') {
189 if (is_array($extra)) {
190 // Multiple extras for a message with masks
191 $message = call_user_func_array('sprintf', $extra);
192 } elseif (!empty($extra)) {
193 // $message is text with a mask plus extras to insert into the text
194 $message = sprintf($message, $extra);
197 // Add message to $GLOBALS['fatal_messages']
198 $GLOBALS['fatal_messages'][] = $message;
200 // Log fatal messages away
201 debug_report_bug($message);
202 logDebugMessage($F, $L, " message={$message}");
205 // Getter for total fatal message count
206 function getTotalFatalErrors () {
210 // Do we have at least the first entry?
211 if (!empty($GLOBALS['fatal_messages'][0])) {
213 $count = count($GLOBALS['fatal_messages']);
220 // Load a template file and return it's content (only it's name; do not use ' or ")
221 function loadTemplate ($template, $return=false, $content=array()) {
222 // @TODO Remove this sanity-check if all is fine
223 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
225 // @TODO Try to rewrite all $DATA to $content
229 if (isTemplateCached($template)) {
230 // Evaluate the cache
231 eval(readTemplateCache($template));
232 } elseif (!isset($GLOBALS['template_eval'][$template])) {
233 // Add more variables which you want to use in your template files
234 $username = getUsername();
236 // Make all template names lowercase
237 $template = strtolower($template);
239 // Count the template load
240 incrementConfigEntry('num_templates');
244 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
247 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
250 // Check for admin/guest/member templates
251 if (substr($template, 0, 6) == 'admin_') {
252 // Admin template found
254 } elseif (substr($template, 0, 6) == 'guest_') {
255 // Guest template found
257 } elseif (substr($template, 0, 7) == 'member_') {
258 // Member template found
260 } elseif (substr($template, 0, 8) == 'install_') {
261 // Installation template found
263 } elseif (substr($template, 0, 4) == 'ext_') {
264 // Extension template found
266 } elseif (substr($template, 0, 3) == 'la_') {
267 // 'Logical-area' template found
269 } elseif (substr($template, 0, 3) == 'js_') {
270 // JavaScript template found
272 } elseif (substr($template, 0, 5) == 'menu_') {
273 // Menu template found
276 // Test for extension
277 $test = substr($template, 0, strpos($template, '_'));
279 // Probe for valid extension name
280 if (isExtensionNameValid($test)) {
281 // Set extra path to extension's name
286 ////////////////////////
287 // Generate file name //
288 ////////////////////////
289 $FQFN = $basePath . $mode . $template . '.tpl';
291 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
292 // Select what depended header/footer template file for admin/guest/member area
293 $file2 = sprintf("%s%s%s_%s.tpl",
301 if (isFileReadable($file2)) $FQFN = $file2;
303 // Remove variable from memory
307 // Does the special template exists?
308 if (!isFileReadable($FQFN)) {
309 // Reset to default template
310 $FQFN = $basePath . $template . '.tpl';
313 // Now does the final template exists?
314 if (isFileReadable($FQFN)) {
315 // The local file does exists so we load it. :)
316 $GLOBALS['tpl_content'] = readFromFile($FQFN);
318 // Replace ' to our own chars to preventing them being quoted
319 while (strpos($GLOBALS['tpl_content'], "'") !== false) { $GLOBALS['tpl_content'] = str_replace("'", '{QUOT}', $GLOBALS['tpl_content']); }
321 // Do we have to compile the code?
323 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
324 // Normal HTML output?
325 if (getOutputMode() == 0) {
326 // Add surrounding HTML comments to help finding bugs faster
327 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
329 // Prepare eval() command
330 $eval = '$ret = "' . compileCode(smartAddSlashes($ret)) . '";';
332 // Prepare eval() command
333 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
336 // Add surrounding HTML comments to help finding bugs faster
337 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
338 $eval = '$ret = "' . smartAddSlashes($ret) . '";';
341 // Cache the eval() command here
342 $GLOBALS['template_eval'][$template] = $eval;
345 eval($GLOBALS['template_eval'][$template]);
348 $GLOBALS['template_eval'][$template] = '404';
350 } elseif (((isAdmin()) || ((isInstalling()) && (!isInstalled()))) && ($GLOBALS['template_eval'][$template] == '404')) {
351 // Only admins shall see this warning or when installation mode is active
352 $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
353 (' . $template . ')<br />
355 {--TEMPLATE_CONTENT--}
356 <pre>' . print_r($content, true) . '</pre>
358 <pre>' . print_r($DATA, true) . '</pre>
362 eval($GLOBALS['template_eval'][$template]);
365 // Do we have some content to output or return?
367 // Not empty so let's put it out! ;)
368 if ($return === true) {
369 // Return the HTML code
375 } elseif (isDebugModeEnabled()) {
376 // Warning, empty output!
377 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
381 // Loads an email template and compiles it
382 function loadEmailTemplate ($template, $content = array(), $UID = 0) {
385 // Our configuration is kept non-global here
386 $_CONFIG = getConfigArray();
388 // Make sure all template names are lowercase!
389 $template = strtolower($template);
391 // Default 'nickname' if extension is not installed
394 // Prepare IP number and User Agent
395 $REMOTE_ADDR = detectRemoteAddr();
396 $HTTP_USER_AGENT = detectUserAgent();
399 $ADMIN = getConfig('MAIN_TITLE');
401 // Is the admin logged in?
404 $adminId = getCurrentAdminId();
407 $ADMIN = getAdminEmail($adminId);
410 // Neutral email address is default
411 $email = getConfig('WEBMASTER');
413 // Expiration in a nice output format
414 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
415 if (getConfig('auto_purge') == 0) {
416 // Will never expire!
417 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
419 // Create nice date string
420 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
423 // Is content an array?
424 if (is_array($content)) {
425 // Add expiration to array, $EXPIRATION is now deprecated!
426 $content['expiration'] = $EXPIRATION;
430 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content).'<br />');
431 if (($UID > 0) && (is_array($content))) {
432 // If nickname extension is installed, fetch nickname as well
433 if (isNicknameUsed($UID)) {
434 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
436 fetchUserData($UID, 'nickname');
438 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
443 // Merge data if valid
444 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
445 if (isUserDataValid()) {
446 $content = merge_array($content, getUserDataArray());
448 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
451 // Translate M to male or F to female if present
452 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
454 // Overwrite email from data if present
455 if (isset($content['email'])) $email = $content['email'];
457 // Store email for some functions in global data array
458 $DATA['email'] = $email;
461 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
463 // Check for admin/guest/member templates
464 if (substr($template, 0, 6) == 'admin_') {
465 // Admin template found
466 $FQFN = $basePath.'admin/' . $template.'.tpl';
467 } elseif (substr($template, 0, 6) == 'guest_') {
468 // Guest template found
469 $FQFN = $basePath.'guest/' . $template.'.tpl';
470 } elseif (substr($template, 0, 7) == 'member_') {
471 // Member template found
472 $FQFN = $basePath.'member/' . $template.'.tpl';
474 // Test for extension
475 $test = substr($template, 0, strpos($template, '_'));
476 if (isExtensionNameValid($test)) {
477 // Set extra path to extension's name
478 $FQFN = $basePath . $test.'/' . $template.'.tpl';
480 // No special filename
481 $FQFN = $basePath . $template.'.tpl';
485 // Does the special template exists?
486 if (!isFileReadable($FQFN)) {
487 // Reset to default template
488 $FQFN = $basePath . $template.'.tpl';
491 // Now does the final template exists?
493 if (isFileReadable($FQFN)) {
494 // The local file does exists so we load it. :)
495 $GLOBALS['tpl_content'] = readFromFile($FQFN);
498 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode(smartAddSlashes($GLOBALS['tpl_content']))."\");";
499 eval($GLOBALS['tpl_content']);
500 } elseif (!empty($template)) {
501 // Template file not found!
502 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
503 {--TEMPLATE_CONTENT--}
504 <pre>".print_r($content, true)."</pre>
506 <pre>".print_r($DATA, true)."</pre>
509 // Debug mode not active? Then remove the HTML tags
510 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
512 // No template name supplied!
513 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
516 // Is there some content?
517 if (empty($newContent)) {
519 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
520 // Add last error if the required function exists
521 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
524 // Remove content and data
528 // Compile the code and eval it
529 $eval = '$newContent = "' . compileCode(smartAddSlashes($newContent)) . '";';
536 // Send mail out to an email address
537 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
538 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
540 // Compile subject line (for POINTS constant etc.)
541 eval("\$subject = decodeEntities(\"".compileCode(smartAddSlashes($subject))."\");");
544 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
545 // Value detected, is the message extension installed?
546 // @TODO Extension 'msg' does not exist
547 if (isExtensionActive('msg')) {
548 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
551 // Does the user exist?
552 if (fetchUserData($toEmail)) {
554 $toEmail = getUserData('email');
557 $toEmail = getConfig('WEBMASTER');
560 } elseif ($toEmail == '0') {
562 $toEmail = getConfig('WEBMASTER');
564 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
566 // Check for PHPMailer or debug-mode
567 if (!checkPhpMailerUsage()) {
568 // Not in PHPMailer-Mode
569 if (empty($mailHeader)) {
570 // Load email header template
571 $mailHeader = loadEmailTemplate('header');
574 $mailHeader .= loadEmailTemplate('header');
576 } elseif (isDebugModeEnabled()) {
577 if (empty($mailHeader)) {
578 // Load email header template
579 $mailHeader = loadEmailTemplate('header');
582 $mailHeader .= loadEmailTemplate('header');
587 eval("\$toEmail = \"".compileCode(smartAddSlashes($toEmail))."\";");
590 eval("\$message = \"".compileCode(smartAddSlashes($message))."\";");
592 // Fix HTML parameter (default is no!)
593 if (empty($isHtml)) $isHtml = 'N';
594 if (isDebugModeEnabled()) {
595 // In debug mode we want to display the mail instead of sending it away so we can debug this part
597 Headers : ' . str_replace('<', '<', str_replace('>', '>', htmlentities(trim($mailHeader)))) . '
598 To : ' . $toEmail . '
599 Subject : ' . $subject . '
600 Message : ' . $message . '
602 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
603 // Send mail as HTML away
604 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
605 } elseif (!empty($toEmail)) {
607 sendRawEmail($toEmail, $subject, $message, $mailHeader);
608 } elseif ($isHtml != 'Y') {
610 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
614 // Check if legacy or PHPMailer command
615 // @TODO Rewrite this to an extension 'smtp'
617 function checkPhpMailerUsage() {
618 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
621 // Send out a raw email with PHPMailer class or legacy mail() command
622 function sendRawEmail ($toEmail, $subject, $message, $from) {
623 // Shall we use PHPMailer class or legacy mode?
624 if (checkPhpMailerUsage()) {
625 // Use PHPMailer class with SMTP enabled
626 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
627 loadIncludeOnce('inc/phpmailer/class.smtp.php');
630 $mail = new PHPMailer();
632 // Set charset to UTF-8
633 $mail->CharSet('UTF-8');
635 // Path for PHPMailer
636 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
639 $mail->SMTPAuth = true;
640 $mail->Host = getConfig('SMTP_HOSTNAME');
642 $mail->Username = getConfig('SMTP_USER');
643 $mail->Password = getConfig('SMTP_PASSWORD');
645 $mail->From = getConfig('WEBMASTER');
649 $mail->FromName = getConfig('MAIN_TITLE');
650 $mail->Subject = $subject;
651 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
652 $mail->Body = $message;
653 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
654 $mail->WordWrap = 70;
657 $mail->Body = decodeEntities($message);
659 $mail->AddAddress($toEmail, '');
660 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
661 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
662 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
665 // Use legacy mail() command
666 mail($toEmail, $subject, decodeEntities($message), $from);
670 // Generate a password in a specified length or use default password length
671 function generatePassword ($length = 0) {
672 // Auto-fix invalid length of zero
673 if ($length == 0) $length = getConfig('pass_len');
675 // Initialize array with all allowed chars
676 $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,-,+,_,/,.');
678 // Start creating password
680 for ($i = 0; $i < $length; $i++) {
681 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
684 // When the size is below 40 we can also add additional security by scrambling
685 // it. Otherwise we may corrupt hashes
686 if (strlen($PASS) <= 40) {
687 // Also scramble the password
688 $PASS = scrambleString($PASS);
691 // Return the password
695 // Generates a human-readable timestamp from the Uni* stamp
696 function generateDateTime ($time, $mode = 0) {
697 // Filter out numbers
698 $time = bigintval($time);
700 // If the stamp is zero it mostly didn't "happen"
703 return getMessage('NEVER_HAPPENED');
706 switch (getLanguage()) {
707 case 'de': // German date / time format
709 case 0: $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
710 case 1: $ret = strtolower(date('d.m.Y - H:i', $time)); break;
711 case 2: $ret = date('d.m.Y|H:i', $time); break;
712 case 3: $ret = date('d.m.Y', $time); break;
714 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
719 default: // Default is the US date / time format!
721 case 0: $ret = date('r', $time); break;
722 case 1: $ret = date('Y-m-d - g:i A', $time); break;
723 case 2: $ret = date('y-m-d|H:i', $time); break;
724 case 3: $ret = date('y-m-d', $time); break;
726 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
735 // Translates Y/N to yes/no
736 function translateYesNo ($yn) {
738 $translated = '??? (' . $yn . ')';
740 case 'Y': $translated = getMessage('YES'); break;
741 case 'N': $translated = getMessage('NO'); break;
744 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
752 // Translates the "pool type" into human-readable
753 function translatePoolType ($type) {
754 // Default?type is unknown
755 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
758 $constName = sprintf("POOL_TYPE_%s", $type);
761 if (isMessageIdValid($constName)) {
763 $translated = getMessage($constName);
766 // Return "translation"
770 // Translates the american decimal dot into a german comma
771 function translateComma ($dotted, $cut = true, $max = 0) {
772 // Default is 3 you can change this in admin area "Misc -> Misc Options"
773 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
775 // Use from config is default
776 $maxComma = getConfig('max_comma');
778 // Use from parameter?
779 if ($max > 0) $maxComma = $max;
782 if (($cut === true) && ($max == 0)) {
783 // Test for commata if in cut-mode
784 $com = explode('.', $dotted);
785 if (count($com) < 2) {
786 // Don't display commatas even if there are none... ;-)
792 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
795 switch (getLanguage()) {
796 case 'de': // German language
797 $dotted = number_format($dotted, $maxComma, ',', '.');
800 default: // All others
801 $dotted = number_format($dotted, $maxComma, '.', ',');
805 // Return translated value
809 // Translate Uni*-like gender to human-readable
810 function translateGender ($gender) {
812 $ret = '!' . $gender . '!';
814 // Male/female or company?
816 case 'M': $ret = getMessage('GENDER_M'); break;
817 case 'F': $ret = getMessage('GENDER_F'); break;
818 case 'C': $ret = getMessage('GENDER_C'); break;
820 // Log unknown gender
821 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
825 // Return translated gender
829 // "Translates" the user status
830 function translateUserStatus ($status) {
831 // Generate message depending on status
836 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
841 $ret = getMessage('ACCOUNT_DELETED');
845 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
846 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
854 // Generates an URL for the dereferer
855 function generateDerefererUrl ($URL) {
856 // Don't de-refer our own links!
857 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
858 // De-refer this link
859 $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
866 // Generates an URL for the frametester
867 function generateFrametesterUrl ($URL) {
868 // Prepare frametester URL
869 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
870 encodeString(compileUriCode($URL))
873 // Return the new URL
874 return $frametesterUrl;
877 // Count entries from e.g. a selection box
878 function countSelection ($array) {
880 if (!is_array($array)) {
882 debug_report_bug(__FUNCTION__.': No array provided.');
889 foreach ($array as $key => $selected) {
891 if (!empty($selected)) $ret++;
894 // Return counted selections
898 // Generate XHTML code for the CAPTCHA
899 function generateCaptchaCode ($code, $type, $DATA, $userid) {
900 return '<img border="0" alt="Code ' . $code . '" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
903 // Generates a timestamp (some wrapper for mktime())
904 function makeTime ($hours, $minutes, $seconds, $stamp) {
905 // Extract day, month and year from given timestamp
906 $days = date('d', $stamp);
907 $months = date('m', $stamp);
908 $years = date('Y', $stamp);
910 // Create timestamp for wished time which depends on extracted date
921 // Redirects to an URL and if neccessarry extends it with own base URL
922 function redirectToUrl ($URL) {
924 eval('$URL = "' . compileCode($URL) . '";');
926 // Check if http(s):// is there
927 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
928 // Make all URLs full-qualified
929 $URL = getConfig('URL') . '/' . $URL;
932 // Three different debug ways...
933 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
934 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
935 //* DEBUG: */ die($URL);
937 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
938 $rel = ' rel="external"';
940 // Do we have internal or external URL?
941 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
942 // Own (=internal) URL
947 $GLOBALS['output'] = ob_get_contents();
949 // Clear it only if there is content
950 if (!empty($GLOBALS['output'])) {
954 // Simple probe for bots/spiders from search engines
955 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
956 // Secure the URL against bad things such als HTML insertions and so on...
957 $URL = secureString($URL);
959 // Output new location link as anchor
960 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
961 } elseif (!headers_sent()) {
962 // Load URL when headers are not sent
963 //* DEBUG: */ debug_report_bug("URL={$URL}");
964 sendHeader('Location: '.str_replace('&', '&', $URL));
966 // Output error message
967 loadInclude('inc/header.php');
968 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
969 loadInclude('inc/footer.php');
972 // Shut the mailer down here
976 // Wrapper for redirectToUrl but URL comes from a configuration entry
977 function redirectToConfiguredUrl ($configEntry) {
979 $URL = getConfig($configEntry);
984 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
991 // Compiles the given HTML/mail code
992 function compileCode ($code, $simple = false, $constants = true, $full = true) {
993 // Is the code a string?
994 if (!is_string($code)) {
995 // Silently return it
1000 $startCompile = explode(' ', microtime());
1002 // Init replacement-array with full security characters
1003 $secChars = $GLOBALS['security_chars'];
1005 // Select smaller set of chars to replace when we e.g. want to compile URLs
1006 if ($full === false) $secChars = $GLOBALS['url_chars'];
1008 // Compile more through a filter
1009 $code = runFilterChain('compile_code', $code);
1011 // Compile constants
1012 if ($constants === true) {
1013 // BEFORE 0.2.1 : Language and data constants
1014 // WITH 0.2.1+ : Only language constants
1015 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1017 // BEFORE 0.2.1 : Not used
1018 // WITH 0.2.1+ : Data constants
1019 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1022 // Compile QUOT and other non-HTML codes
1023 foreach ($secChars['to'] as $k => $to) {
1024 // Do the reversed thing as in inc/libs/security_functions.php
1025 $code = str_replace($to, $secChars['from'][$k], $code);
1028 // But shall I keep simple quotes for later use?
1029 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1031 // Find $content[bla][blub] entries
1032 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1034 // Are some matches found?
1035 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1036 // Replace all matches
1037 $matchesFound = array();
1038 foreach ($matches[0] as $key => $match) {
1039 // Fuzzy look has failed by default
1040 $fuzzyFound = false;
1042 // Fuzzy look on match if already found
1043 foreach ($matchesFound as $found => $set) {
1045 $test = substr($found, 0, strlen($match));
1047 // Does this entry exist?
1048 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1049 if ($test == $match) {
1051 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1058 if ($fuzzyFound === true) continue;
1060 // Take all string elements
1061 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1062 // Replace it in the code
1063 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1064 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1065 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1066 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1067 $matchesFound[$match] = 1;
1068 } elseif (!isset($matchesFound[$match])) {
1069 // Not yet replaced!
1070 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1071 $code = str_replace($match, "\"." . $match.".\"", $code);
1072 $matchesFound[$match] = 1;
1078 $compiled = explode(' ', microtime());
1081 $code .= '<!-- Compilation time: ' . ((($compiled[1] + $compiled[0]) - ($startCompile[1] + $startCompile[0])) * 1000). 'ms //-->';
1083 // Return compiled code
1087 /************************************************************************
1089 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1090 * $a_sort sortiert: *
1092 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1093 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1094 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1095 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1096 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1098 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1099 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1100 * Sie, dass es doch nicht so schwer ist! :-) *
1102 ************************************************************************/
1103 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1105 while ($primary_key < count($a_sort)) {
1106 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1107 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1109 if ($nums === false) {
1110 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1111 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1112 } elseif ($key != $key2) {
1113 // Sort numbers (E.g.: 9 < 10)
1114 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1115 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1119 // We have found two different values, so let's sort whole array
1120 foreach ($dummy as $sort_key => $sort_val) {
1121 $t = $dummy[$sort_key][$key];
1122 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1123 $dummy[$sort_key][$key2] = $t;
1134 // Write back sorted array
1139 function addSelectionBox ($type, $default, $prefix = '', $id = 0) {
1142 if ($type == 'yn') {
1143 // This is a yes/no selection only!
1144 if ($id > 0) $prefix .= "[" . $id."]";
1145 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1147 // Begin with regular selection box here
1148 if (!empty($prefix)) $prefix .= "_";
1150 if ($id > 0) $type2 .= "[" . $id."]";
1151 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1156 for ($idx = 1; $idx < 32; $idx++) {
1157 $OUT .= "<option value=\"" . $idx."\"";
1158 if ($default == $idx) $OUT .= ' selected="selected"';
1159 $OUT .= ">" . $idx."</option>\n";
1163 case 'month': // Month
1164 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1165 $OUT .= "<option value=\"" . $month."\"";
1166 if ($default == $month) $OUT .= ' selected="selected"';
1167 $OUT .= ">" . $descr."</option>\n";
1171 case 'year': // Year
1173 $year = date('Y', time());
1175 // Use configured min age or fixed?
1176 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1178 $startYear = $year - getConfig('min_age');
1181 $startYear = $year - 16;
1184 // Calculate earliest year (100 years old people can still enter Internet???)
1185 $minYear = $year - 100;
1187 // Check if the default value is larger than minimum and bigger than actual year
1188 if (($default > $minYear) && ($default >= $year)) {
1189 for ($idx = $year; $idx < ($year + 11); $idx++) {
1190 $OUT .= "<option value=\"" . $idx."\"";
1191 if ($default == $idx) $OUT .= ' selected="selected"';
1192 $OUT .= ">" . $idx."</option>\n";
1194 } elseif ($default == -1) {
1195 // Current year minus 1
1196 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1198 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1201 // Get current year and subtract the configured minimum age
1202 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1203 // Calculate earliest year depending on extension version
1204 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1205 // Use configured minimum age
1206 $year = date('Y', time()) - getConfig('min_age');
1208 // Use fixed 16 years age
1209 $year = date('Y', time()) - 16;
1212 // Construct year selection list
1213 for ($idx = $minYear; $idx <= $year; $idx++) {
1214 $OUT .= "<option value=\"" . $idx."\"";
1215 if ($default == $idx) $OUT .= ' selected="selected"';
1216 $OUT .= ">" . $idx."</option>\n";
1223 for ($idx = 0; $idx < 60; $idx+=5) {
1224 if (strlen($idx) == 1) $idx = 0 . $idx;
1225 $OUT .= "<option value=\"" . $idx."\"";
1226 if ($default == $idx) $OUT .= ' selected="selected"';
1227 $OUT .= ">" . $idx."</option>\n";
1232 for ($idx = 0; $idx < 24; $idx++) {
1233 if (strlen($idx) == 1) $idx = 0 . $idx;
1234 $OUT .= "<option value=\"" . $idx."\"";
1235 if ($default == $idx) $OUT .= ' selected="selected"';
1236 $OUT .= ">" . $idx."</option>\n";
1241 $OUT .= "<option value=\"Y\"";
1242 if ($default == 'Y') $OUT .= ' selected="selected"';
1243 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1244 if ($default != 'Y') $OUT .= ' selected="selected"';
1245 $OUT .= ">{--NO--}</option>\n";
1248 $OUT .= " </select>\n";
1253 // Deprecated : $length
1256 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1257 // Build server string
1258 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1261 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1262 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1263 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1264 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1265 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1267 // Build string from misc data
1268 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1270 // Add more additional data
1271 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1273 // Add referal id, language, theme and userid
1274 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1275 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1276 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1277 $data .= getConfig('ENCRYPT_SEPERATOR') . getUserId();
1279 // Calculate number for generating the code
1280 $a = $code + getConfig('_ADD') - 1;
1282 if (isConfigEntrySet('master_salt')) {
1283 // Generate hash with master salt from modula of number with the prime number and other data
1284 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, getConfig('master_salt'));
1286 // Create number from hash
1287 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1289 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1290 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, getConfig('salt_length')));
1292 // Create number from hash
1293 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1296 // At least 10 numbers shall be secure enought!
1297 $len = getConfig('code_length');
1298 if ($len == 0) $len = $length;
1299 if ($len == 0) $len = 10;
1301 // Cut off requested counts of number
1302 $return = substr(str_replace('.', '', $rcode), 0, $len);
1304 // Done building code
1308 // Does only allow numbers
1309 function bigintval ($num, $castValue = true) {
1310 // Filter all numbers out
1311 $ret = preg_replace('/[^0123456789]/', '', $num);
1314 if ($castValue) $ret = (double)$ret;
1316 // Has the whole value changed?
1317 // @TODO Remove this if() block if all is working fine
1318 if ('' . $ret . '' != '' . $num . '') {
1320 //debug_report_bug("{$ret}<>{$num}");
1327 // Insert the code in $img_code into jpeg or PNG image
1328 function generateImageOrCode ($img_code, $headerSent=true) {
1329 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1330 // Stop execution of function here because of over-sized code length
1332 } elseif ($headerSent === false) {
1333 // Return in an HTML code code
1334 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1338 $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
1339 if (isFileReadable($img)) {
1340 // Switch image type
1341 switch (getConfig('img_type'))
1344 // Okay, load image and hide all errors
1345 $image = imagecreatefromjpeg($img);
1349 // Okay, load image and hide all errors
1350 $image = imagecreatefrompng($img);
1354 // Exit function here
1355 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1359 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1360 $text_color = imagecolorallocate($image, 0, 0, 0);
1362 // Insert code into image
1363 imagestring($image, 5, 14, 2, $img_code, $text_color);
1365 // Return to browser
1366 sendHeader('Content-Type: image/' . getConfig('img_type'));
1368 // Output image with matching image factory
1369 switch (getConfig('img_type')) {
1370 case 'jpg': imagejpeg($image); break;
1371 case 'png': imagepng($image); break;
1374 // Remove image from memory
1375 imagedestroy($image);
1377 // Create selection box or array of splitted timestamp
1378 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1379 // Calculate 2-seconds timestamp
1380 $stamp = round($timestamp);
1381 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1383 // Do we have a leap year?
1385 $TEST = date('Y', time()) / 4;
1386 $M1 = date('m', time());
1387 $M2 = date('m', (time() + $timestamp));
1389 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1390 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1392 // First of all years...
1393 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1394 //* DEBUG: */ print("Y={$Y}<br />");
1396 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1397 //* DEBUG: */ print("M={$M}<br />");
1399 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1400 //* DEBUG: */ print("W={$W}<br />");
1402 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1403 //* DEBUG: */ print("D={$D}<br />");
1405 $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));
1406 //* DEBUG: */ print("h={$h}<br />");
1408 $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));
1409 //* DEBUG: */ print("m={$m}<br />");
1410 // And at last seconds...
1411 $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));
1412 //* DEBUG: */ print("s={$s}<br />");
1414 // Is seconds zero and time is < 60 seconds?
1415 if (($s == 0) && ($timestamp < 60)) {
1417 $s = round($timestamp);
1421 // Now we convert them in seconds...
1423 if ($return_array) {
1424 // Just put all data in an array for later use
1436 $OUT = "<div align=\"" . $align."\">\n";
1437 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1440 if (ereg('Y', $display) || (empty($display))) {
1441 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1444 if (ereg('M', $display) || (empty($display))) {
1445 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1448 if (ereg("W", $display) || (empty($display))) {
1449 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1452 if (ereg("D", $display) || (empty($display))) {
1453 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1456 if (ereg("h", $display) || (empty($display))) {
1457 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1460 if (ereg('m', $display) || (empty($display))) {
1461 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1464 if (ereg("s", $display) || (empty($display))) {
1465 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1471 if (ereg('Y', $display) || (empty($display))) {
1472 // Generate year selection
1473 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1474 for ($idx = 0; $idx <= 10; $idx++) {
1475 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1476 if ($idx == $Y) $OUT .= ' selected="selected"';
1477 $OUT .= ">" . $idx."</option>\n";
1479 $OUT .= " </select></td>\n";
1481 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1484 if (ereg('M', $display) || (empty($display))) {
1485 // Generate month selection
1486 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1487 for ($idx = 0; $idx <= 11; $idx++)
1489 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1490 if ($idx == $M) $OUT .= ' selected="selected"';
1491 $OUT .= ">" . $idx."</option>\n";
1493 $OUT .= " </select></td>\n";
1495 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1498 if (ereg("W", $display) || (empty($display))) {
1499 // Generate week selection
1500 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1501 for ($idx = 0; $idx <= 4; $idx++) {
1502 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1503 if ($idx == $W) $OUT .= ' selected="selected"';
1504 $OUT .= ">" . $idx."</option>\n";
1506 $OUT .= " </select></td>\n";
1508 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1511 if (ereg("D", $display) || (empty($display))) {
1512 // Generate day selection
1513 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1514 for ($idx = 0; $idx <= 31; $idx++) {
1515 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1516 if ($idx == $D) $OUT .= ' selected="selected"';
1517 $OUT .= ">" . $idx."</option>\n";
1519 $OUT .= " </select></td>\n";
1521 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1524 if (ereg("h", $display) || (empty($display))) {
1525 // Generate hour selection
1526 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1527 for ($idx = 0; $idx <= 23; $idx++) {
1528 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1529 if ($idx == $h) $OUT .= ' selected="selected"';
1530 $OUT .= ">" . $idx."</option>\n";
1532 $OUT .= " </select></td>\n";
1534 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1537 if (ereg('m', $display) || (empty($display))) {
1538 // Generate minute selection
1539 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1540 for ($idx = 0; $idx <= 59; $idx++) {
1541 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1542 if ($idx == $m) $OUT .= ' selected="selected"';
1543 $OUT .= ">" . $idx."</option>\n";
1545 $OUT .= " </select></td>\n";
1547 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1550 if (ereg("s", $display) || (empty($display))) {
1551 // Generate second selection
1552 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1553 for ($idx = 0; $idx <= 59; $idx++) {
1554 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1555 if ($idx == $s) $OUT .= ' selected="selected"';
1556 $OUT .= ">" . $idx."</option>\n";
1558 $OUT .= " </select></td>\n";
1560 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1563 $OUT .= "</table>\n";
1565 // Return generated HTML code
1571 function createTimestampFromSelections ($prefix, $postData) {
1572 // Initial return value
1575 // Do we have a leap year?
1577 $TEST = date('Y', time()) / 4;
1578 $M1 = date('m', time());
1579 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1580 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1581 // First add years...
1582 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1584 $ret += $postData[$prefix."_mo"] * 2628000;
1586 $ret += $postData[$prefix."_we"] * 604800;
1588 $ret += $postData[$prefix."_da"] * 86400;
1590 $ret += $postData[$prefix."_ho"] * 3600;
1592 $ret += $postData[$prefix."_mi"] * 60;
1593 // And at last seconds...
1594 $ret += $postData[$prefix."_se"];
1595 // Return calculated value
1599 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1600 function createFancyTime ($stamp) {
1601 // Get data array with years/months/weeks/days/...
1602 $data = createTimeSelections($stamp, '', '', '', true);
1604 foreach($data as $k => $v) {
1606 // Value is greater than 0 "eval" data to return string
1607 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1612 // Do we have something there?
1613 if (strlen($ret) > 0) {
1614 // Remove leading commata and space
1615 $ret = substr($ret, 2);
1618 $ret = "0 {--_SECONDS--}";
1621 // Return fancy time string
1625 // Generates a navigation row for listing emails
1626 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1627 $SEP = ''; $TOP = '';
1628 if ($show_form === false) {
1630 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1634 for ($page = 1; $page <= $PAGES; $page++) {
1635 // Is the page currently selected or shall we generate a link to it?
1636 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1637 // Is currently selected, so only highlight it
1638 $NAV .= '<strong>-';
1640 // Open anchor tag and add base URL
1641 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1643 // Add userid when we shall show all mails from a single member
1644 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1646 // Close open anchor tag
1650 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1651 // Is currently selected, so only highlight it
1652 $NAV .= '-</strong>';
1658 // Add seperator if we have not yet reached total pages
1659 if ($page < $PAGES) $NAV .= ' | ';
1662 // Define constants only once
1663 $content['nav'] = $NAV;
1664 $content['span'] = $colspan;
1665 $content['top'] = $TOP;
1666 $content['sep'] = $SEP;
1668 // Load navigation template
1669 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1671 if ($return === true) {
1672 // Return generated HTML-Code
1680 // Extract host from script name
1681 function extractHostnameFromUrl (&$script) {
1682 // Use default SERVER_URL by default... ;) So?
1683 $url = getConfig('SERVER_URL');
1685 // Is this URL valid?
1686 if (substr($script, 0, 7) == 'http://') {
1687 // Use the hostname from script URL as new hostname
1688 $url = substr($script, 7);
1689 $extract = explode('/', $url);
1691 // Done extracting the URL :)
1694 // Extract host name
1695 $host = str_replace('http://', '', $url);
1696 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1698 // Generate relative URL
1699 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1700 if (substr(strtolower($script), 0, 7) == 'http://') {
1701 // But only if http:// is in front!
1702 $script = substr($script, (strlen($url) + 7));
1703 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1705 $script = substr($script, (strlen($url) + 8));
1708 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1709 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1715 // Send a GET request
1716 function sendGetRequest ($script, $data = array()) {
1717 // Extract host name from script
1718 $host = extractHostnameFromUrl($script);
1721 $scriptData = http_build_query($data, '', '&');
1723 // Do we have a question-mark in the script?
1724 if (strpos($script, '?') === false) {
1725 // No, so first char must be question mark
1726 $scriptData = '?' . $scriptData;
1729 $scriptData = '&' . $scriptData;
1733 $script .= $scriptData;
1735 // Generate GET request header
1736 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1737 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1738 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1739 if (isConfigEntrySet('FULL_VERSION')) {
1740 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1742 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1744 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1745 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1746 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1748 // Send the raw request
1749 $response = sendRawRequest($host, $request);
1751 // Return the result to the caller function
1755 // Send a POST request
1756 function sendPostRequest ($script, $postData) {
1757 // Is postData an array?
1758 if (!is_array($postData)) {
1760 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1761 return array('', '', '');
1764 // Extract host name from script
1765 $host = extractHostnameFromUrl($script);
1767 // Construct request
1768 $data = http_build_query($postData, '', '&');
1770 // Generate POST request header
1771 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1772 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1773 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1774 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1775 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1776 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1777 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1778 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1781 // Send the raw request
1782 $response = sendRawRequest($host, $request);
1784 // Return the result to the caller function
1788 // Sends a raw request to another host
1789 function sendRawRequest ($host, $request) {
1790 // Init errno and errdesc with 'all fine' values
1791 $errno = 0; $errdesc = '';
1794 $response = array('', '', '');
1796 // Default is not to use proxy
1799 // Are proxy settins set?
1800 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1806 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1807 if ($useProxy === true) {
1808 // Connect to host through proxy connection
1809 $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1811 // Connect to host directly
1812 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1816 if (!is_resource($fp)) {
1822 if ($useProxy === true) {
1823 // Generate CONNECT request header
1824 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1825 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1827 // Use login data to proxy? (username at least!)
1828 if (getConfig('proxy_username') != '') {
1830 $encodedAuth = base64_encode(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
1831 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1834 // Add last new-line
1835 $proxyTunnel .= getConfig('HTTP_EOL');
1836 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1839 fputs($fp, $proxyTunnel);
1843 // No response received
1847 // Read the first line
1848 $resp = trim(fgets($fp, 10240));
1849 $respArray = explode(' ', $resp);
1850 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1851 // Invalid response!
1857 fputs($fp, $request);
1860 while (!feof($fp)) {
1861 $response[] = trim(fgets($fp, 1024));
1867 // Skip first empty lines
1869 foreach ($resp as $idx => $line) {
1871 $line = trim($line);
1873 // Is this line empty?
1876 array_shift($response);
1878 // Abort on first non-empty line
1883 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1885 // Proxy agent found?
1886 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1887 // Proxy header detected, so remove two lines
1888 array_shift($response);
1889 array_shift($response);
1892 // Was the request successfull?
1893 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1894 // Not found / access forbidden
1895 $response = array('', '', '');
1902 // Taken from www.php.net eregi() user comments
1903 function isEmailValid ($email) {
1904 // Check first part of email address
1905 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1908 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1911 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1913 // Return check result
1914 return preg_match($regex, $email);
1917 // Function taken from user comments on www.php.net / function eregi()
1918 function isUrlValid ($URL, $compile=true) {
1919 // Trim URL a little
1920 $URL = trim(urldecode($URL));
1921 //* DEBUG: */ outputHtml($URL.'<br />');
1923 // Compile some chars out...
1924 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1925 //* DEBUG: */ outputHtml($URL.'<br />');
1927 // Check for the extension filter
1928 if (isExtensionActive('filter')) {
1929 // Use the extension's filter set
1930 return FILTER_VALIDATE_URL($URL, false);
1933 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1934 // https:// in front of the URLs
1935 return isUrlValidSimple($URL);
1938 // Generate a list of administrative links to a given userid
1939 function generateMemberAdminActionLinks ($userid, $status = '') {
1940 // Make sure userid is a number
1941 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1943 // Define all main targets
1944 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1946 // Begin of navigation links
1949 foreach ($targetArray as $tar) {
1950 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1951 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1952 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1953 // Locked accounts shall be unlocked
1954 $OUT .= 'UNLOCK_USER';
1956 // All other status is fine
1957 $OUT .= strtoupper($tar);
1959 $OUT .= "_TITLE--}\">{--ADMIN_";
1960 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1961 // Locked accounts shall be unlocked
1962 $OUT .= 'UNLOCK_USER';
1964 // All other status is fine
1965 $OUT .= strtoupper($tar);
1967 $OUT .= "--}</a></span> | ";
1970 // Finish navigation link
1971 $OUT = substr($OUT, 0, -7) . ']';
1977 // Generate an email link
1978 function generateEmailLink ($email, $table = 'admins') {
1979 // Default email link (INSECURE! Spammer can read this by harvester programs)
1980 $EMAIL = 'mailto:' . $email;
1982 // Check for several extensions
1983 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1984 // Create email link for contacting admin in guest area
1985 $EMAIL = generateAdminEmailLink($email);
1986 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
1987 // Create email link for contacting a member within admin area (or later in other areas, too?)
1988 $EMAIL = generateUserEmailLink($email, 'admin');
1989 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1990 // Create email link to contact sponsor within admin area (or like the link above?)
1991 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
1994 // Shall I close the link when there is no admin?
1995 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1997 // Return email link
2001 // Generate a hash for extra-security for all passwords
2002 function generateHash ($plainText, $salt = '') {
2003 // Is the required extension 'sql_patches' there and a salt is not given?
2004 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2005 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2006 return md5($plainText);
2009 // Do we miss an arry element here?
2010 if (!isConfigEntrySet('file_hash')) {
2012 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2015 // When the salt is empty build a new one, else use the first x configured characters as the salt
2017 // Build server string (inc/databases.php is no longer updated with every commit)
2018 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2021 $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');
2024 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2026 // Calculate number for generating the code
2027 $a = time() + getConfig('_ADD') - 1;
2029 // Generate SHA1 sum from modula of number and the prime number
2030 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2031 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2032 $sha1 = scrambleString($sha1);
2033 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2034 //* DEBUG: */ $sha1b = descrambleString($sha1);
2035 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2037 // Generate the password salt string
2038 $salt = substr($sha1, 0, getConfig('salt_length'));
2039 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2042 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2043 $salt = substr($salt, 0, getConfig('salt_length'));
2044 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2046 // Sanity check on salt
2047 if (strlen($salt) != getConfig('salt_length')) {
2049 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2054 return $salt.sha1($salt . $plainText);
2057 // Scramble a string
2058 function scrambleString($str) {
2062 // Final check, in case of failture it will return unscrambled string
2063 if (strlen($str) > 40) {
2064 // The string is to long
2066 } elseif (strlen($str) == 40) {
2068 $scrambleNums = explode(':', getConfig('pass_scramble'));
2070 // Generate new numbers
2071 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2074 // Scramble string here
2075 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2076 for ($idx = 0; $idx < strlen($str); $idx++) {
2077 // Get char on scrambled position
2078 $char = substr($str, $scrambleNums[$idx], 1);
2080 // Add it to final output string
2081 $scrambled .= $char;
2084 // Return scrambled string
2085 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2089 // De-scramble a string scrambled by scrambleString()
2090 function descrambleString($str) {
2091 // Scramble only 40 chars long strings
2092 if (strlen($str) != 40) return $str;
2094 // Load numbers from config
2095 $scrambleNums = explode(':', getConfig('pass_scramble'));
2098 if (count($scrambleNums) != 40) return $str;
2100 // Begin descrambling
2101 $orig = str_repeat(' ', 40);
2102 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2103 for ($idx = 0; $idx < 40; $idx++) {
2104 $char = substr($str, $idx, 1);
2105 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2108 // Return scrambled string
2109 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2113 // Generated a "string" for scrambling
2114 function genScrambleString ($len) {
2115 // Prepare array for the numbers
2116 $scrambleNumbers = array();
2118 // First we need to setup randomized numbers from 0 to 31
2119 for ($idx = 0; $idx < $len; $idx++) {
2121 $rand = mt_rand(0, ($len -1));
2123 // Check for it by creating more numbers
2124 while (array_key_exists($rand, $scrambleNumbers)) {
2125 $rand = mt_rand(0, ($len -1));
2129 $scrambleNumbers[$rand] = $rand;
2132 // So let's create the string for storing it in database
2133 $scrambleString = implode(':', $scrambleNumbers);
2134 return $scrambleString;
2137 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2138 function generatePassString ($passHash) {
2139 // Return vanilla password hash
2142 // Is a secret key and master salt already initialized?
2143 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2144 // Only calculate when the secret key is generated
2145 $newHash = ''; $start = 9;
2146 for ($idx = 0; $idx < 10; $idx++) {
2147 $part1 = hexdec(substr($passHash, $start, 4));
2148 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2149 $mod = dechex($idx);
2150 if ($part1 > $part2) {
2151 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2152 } elseif ($part2 > $part1) {
2153 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2155 $mod = substr($mod, 0, 4);
2156 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2157 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2158 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2163 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2164 $ret = generateHash($newHash, getConfig('master_salt'));
2165 //* DEBUG: */ print('ret='.$ret.'<br />');
2168 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2169 $ret = md5($passHash);
2170 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2177 // Fix "deleted" cookies
2178 function fixDeletedCookies ($cookies) {
2179 // Is this an array with entries?
2180 if ((is_array($cookies)) && (count($cookies) > 0)) {
2181 // Then check all cookies if they are marked as deleted!
2182 foreach ($cookies as $cookieName) {
2183 // Is the cookie set to "deleted"?
2184 if (getSession($cookieName) == 'deleted') {
2185 setSession($cookieName, '');
2191 // Output error messages in a fasioned way and die...
2192 function app_die ($F, $L, $message) {
2193 // Check if Script is already dieing and not let it kill itself another 1000 times
2194 if (!isset($GLOBALS['app_died'])) {
2195 // Make sure, that the script realy realy diese here and now
2196 $GLOBALS['app_died'] = true;
2199 loadIncludeOnce('inc/header.php');
2201 // Rewrite message for output
2202 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2204 // Better log this message away
2205 logDebugMessage($F, $L, $message);
2207 // Load the message template
2208 loadTemplate('admin_settings_saved', false, $message);
2211 loadIncludeOnce('inc/footer.php');
2213 // Script tried to kill itself twice
2214 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2218 // Display parsing time and number of SQL queries in footer
2219 function displayParsingTime() {
2220 // Is the timer started?
2221 if (!isset($GLOBALS['startTime'])) {
2227 $endTime = microtime(true);
2229 // "Explode" both times
2230 $start = explode(' ', $GLOBALS['startTime']);
2231 $end = explode(' ', $endTime);
2232 $runTime = $end[0] - $start[0];
2233 if ($runTime < 0) $runTime = 0;
2237 'runtime' => translateComma($runTime),
2238 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2241 // Load the template
2242 loadTemplate('show_timings', false, $content);
2245 // Check wether a boolean constant is set
2246 // Taken from user comments in PHP documentation for function constant()
2247 function isBooleanConstantAndTrue ($constName) { // : Boolean
2248 // Failed by default
2252 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2254 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2255 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2258 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2259 if (defined($constName)) {
2261 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2262 $res = (constant($constName) === true);
2266 $GLOBALS['cache_array']['const'][$constName] = $res;
2268 //* DEBUG: */ var_dump($res);
2274 // Checks if a given apache module is loaded
2275 function isApacheModuleLoaded ($apacheModule) {
2276 // Check it and return result
2277 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2280 // Get current theme name
2281 function getCurrentTheme () {
2282 // The default theme is 'default'... ;-)
2285 // Load default theme if not empty from configuration
2286 if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
2288 if (!isSessionVariableSet('mxchange_theme')) {
2289 // Set default theme
2291 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2292 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2293 // Get theme from cookie
2294 $ret = getSession('mxchange_theme');
2297 if (getThemeId($ret) == 0) {
2298 // Fix it to default
2301 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2302 // Prepare FQFN for checking
2303 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2305 // Installation mode active
2306 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2307 // Set cookie from URL data
2308 setTheme(getRequestElement('theme'));
2309 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2310 // Set cookie from posted data
2311 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2315 $ret = getSession('mxchange_theme');
2317 // Invalid design, reset cookie
2321 // Return theme value
2325 // Setter for theme in session
2326 function setTheme ($newTheme) {
2327 setSession('mxchange_theme', $newTheme);
2330 // Get id from theme
2331 // @TODO Try to move this to inc/libs/theme_functions.php
2332 function getThemeId ($name) {
2333 // Is the extension 'theme' installed?
2334 if (!isExtensionActive('theme')) {
2342 // Is the cache entry there?
2343 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2344 // Get the version from cache
2345 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2348 incrementStatsEntry('cache_hits');
2349 } elseif (getExtensionVersion('cache') != '0.1.8') {
2350 // Check if current theme is already imported or not
2351 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2352 array($name), __FUNCTION__, __LINE__);
2355 if (SQL_NUMROWS($result) == 1) {
2357 list($id) = SQL_FETCHROW($result);
2361 SQL_FREERESULT($result);
2368 // Generates an error code from given account status
2369 function generateErrorCodeFromUserStatus ($status='') {
2370 // If no status is provided, use the default, cached
2371 if ((empty($status)) && (isMember())) {
2373 $status = getUserData('status');
2376 // Default error code if unknown account status
2377 $errorCode = getCode('UNKNOWN_STATUS');
2379 // Generate constant name
2380 $constantName = sprintf("ID_%s", $status);
2382 // Is the constant there?
2383 if (isCodeSet($constantName)) {
2385 $errorCode = getCode($constantName);
2388 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2391 // Return error code
2395 // Function to search for the last modifified file
2396 function searchDirsRecursive ($dir, &$last_changed) {
2398 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2399 // Does it match what we are looking for? (We skip a lot files already!)
2400 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2401 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2402 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2403 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2405 // Walk through all entries
2406 foreach ($ds as $d) {
2407 // Generate proper FQFN
2408 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2410 // Is it a file and readable?
2411 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2412 if (isDirectory($FQFN)) {
2413 // $FQFN is a directory so also crawl into this directory
2415 if (!empty($dir)) $newDir = $dir . '/'. $d;
2416 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2417 searchDirsRecursive($newDir, $last_changed);
2418 } elseif (isFileReadable($FQFN)) {
2419 // $FQFN is a filename and no directory
2420 $time = filemtime($FQFN);
2421 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2422 if ($last_changed['time'] < $time) {
2423 // This file is newer as the file before
2424 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2425 $last_changed['path_name'] = $FQFN;
2426 $last_changed['time'] = $time;
2432 // "Getter" for revision/version data
2433 function getActualVersion ($type = 'Revision') {
2434 // By default nothing is new... ;-)
2437 // Is the cache entry there?
2438 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2439 // Found so increase cache hit
2440 incrementStatsEntry('cache_hits');
2443 return $GLOBALS['cache_array']['revision'][$type][0];
2445 // FQFN of revision file
2446 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2448 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2449 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2450 // Forced rebuild of .revision file
2453 // Check for revision file
2454 if (!isFileReadable($FQFN)) {
2455 // Not found, so we need to create it
2458 // Revision file found
2459 $ins_vers = explode("\n", readFromFile($FQFN));
2461 // Get array for mapping information
2462 $mapper = array_flip(getSearchFor());
2463 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2465 // Is the content valid?
2466 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2467 // File needs update!
2470 // Generate fake cache entry
2471 foreach ($mapper as $map=>$idx) {
2472 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2475 // Return found value
2476 return trim($ins_vers[$mapper[$type]]);
2481 // Has it been updated?
2482 if ($new === true) {
2484 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2486 // ... and call recursive
2487 return getActualVersion($type);
2492 // Repares an array we are looking for
2493 // 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
2494 function getSearchFor () {
2495 // Add Revision, Date, Tag and Author
2496 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2498 // Return the created array
2502 // @TODO Please describe this function
2503 function getArrayFromActualVersion () {
2507 // Directory to start with search
2508 $last_changed = array(
2513 // Init return array
2514 $akt_vers = array();
2516 // Init value for counting the founded keywords
2519 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2520 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2523 $last_file = readFromFile($last_changed['path_name']);
2525 // Get all the keywords to search for
2526 $searchFor = getSearchFor();
2528 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2529 foreach ($searchFor as $search) {
2530 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2531 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2532 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2533 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2536 // Save the last-changed filename for debugging
2537 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2539 // at least 3 keyword-Tags are needed for propper values
2540 if ($res && $res >= 3
2541 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2542 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2543 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2544 // Prepare content witch need special treadment
2546 // Prepare timestamp for date
2547 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2548 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2550 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2551 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2552 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2556 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2557 $version = sendGetRequest('check-updates3.php');
2560 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2561 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2562 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2563 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2564 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2565 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2568 // Return prepared array
2569 return $GLOBALS['cache_array']['revision'];
2572 // Back-ported from the new ship-simu engine. :-)
2573 function debug_get_printable_backtrace () {
2575 $backtrace = "<ol>\n";
2577 // Get and prepare backtrace for output
2578 $backtraceArray = debug_backtrace();
2579 foreach ($backtraceArray as $key => $trace) {
2580 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2581 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2582 if (!isset($trace['args'])) $trace['args'] = array();
2583 $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";
2587 $backtrace .= "</ol>\n";
2589 // Return the backtrace
2593 // Output a debug backtrace to the user
2594 function debug_report_bug ($message = '') {
2595 // Is this already called?
2596 if (isset($GLOBALS[__FUNCTION__])) {
2598 print 'Message:'.$message.'<br />Backtrace:<pre>';
2599 debug_print_backtrace();
2603 // Set this function as called
2604 $GLOBALS[__FUNCTION__] = true;
2609 // Is the optional message set?
2610 if (!empty($message)) {
2612 $debug = sprintf("Note: %s<br />\n",
2616 // @TODO Add a little more infos here
2617 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2621 $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>";
2622 $debug .= debug_get_printable_backtrace();
2623 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2624 $debug .= "Thank you for finding bugs.";
2627 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2631 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2632 function generateSeed () {
2633 list($usec, $sec) = explode(' ', microtime());
2634 $microTime = (((float)$sec + (float)$usec)) * 100000;
2638 // Converts a message code to a human-readable message
2639 function getMessageFromErrorCode ($code) {
2643 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2644 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2645 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2646 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2647 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2648 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2649 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2650 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2651 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2652 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2653 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2654 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2655 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2656 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2657 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2658 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2659 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2660 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2661 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2662 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2663 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2664 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2665 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2666 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2667 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2668 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2669 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2670 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2672 case getCode('ERROR_MAILID'):
2673 if (isExtensionActive('mailid', true)) {
2674 $message = getMessage('ERROR_CONFIRMING_MAIL');
2676 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2680 case getCode('EXTENSION_PROBLEM'):
2681 if (isGetRequestElementSet('ext')) {
2682 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2684 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2688 case getCode('URL_TLOCK'):
2689 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2690 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2692 // Load timestamp from last order
2693 list($timestamp) = SQL_FETCHROW($result);
2694 $timestamp = generateDateTime($timestamp, 1);
2697 SQL_FREERESULT($result);
2699 // Calculate hours...
2700 $STD = round(getConfig('url_tlock') / 60 / 60);
2703 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2706 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2708 // Finally contruct the message
2709 // @TODO Rewrite this old lost code to a template
2710 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2711 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2712 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2716 // Missing/invalid code
2717 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2720 logDebugMessage(__FUNCTION__, __LINE__, $message);
2724 // Return the message
2728 // Generate a "link" for the given admin id (admin_id)
2729 function generateAdminLink ($adminId) {
2730 // No assigned admin is default
2731 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2733 // Zero? = Not assigned
2734 if (bigintval($adminId) > 0) {
2735 // Load admin's login
2736 $login = getAdminLogin($adminId);
2738 // Is the login valid?
2739 if ($login != '***') {
2740 // Is the extension there?
2741 if (isExtensionActive('admins')) {
2743 $admin = "<a href=\"".generateEmailLink(getAdminEmail($adminId), 'admins')."\">" . $login."</a>";
2745 // Extension not found
2746 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2750 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $adminId)."</div>";
2758 // Compile characters which are allowed in URLs
2759 function compileUriCode ($code, $simple = true) {
2760 // Compile constants
2761 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2763 // Compile QUOT and other non-HTML codes
2764 $code = str_replace('{DOT}', '.',
2765 str_replace('{SLASH}', '/',
2766 str_replace('{QUOT}', "'",
2767 str_replace('{DOLLAR}', '$',
2768 str_replace('{OPEN_ANCHOR}', '(',
2769 str_replace('{CLOSE_ANCHOR}', ')',
2770 str_replace('{OPEN_SQR}', '[',
2771 str_replace('{CLOSE_SQR}', ']',
2772 str_replace('{PER}', '%',
2776 // Return compiled code
2780 // Function taken from user comments on www.php.net / function eregi()
2781 function isUrlValidSimple ($url) {
2783 $url = secureString(str_replace("\\", '', compileCode(urldecode($url))));
2785 // Allows http and https
2786 $http = "(http|https)+(:\/\/)";
2788 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2789 // Test double-domains (e.g. .de.vu)
2790 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2792 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2794 $dir = "((/)+([-_\.[:alnum:]])+)*";
2796 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2797 // ... and the string after and including question character
2798 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2799 // Pattern for URLs like http://url/dir/doc.html?var=value
2800 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2801 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2802 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2803 // Pattern for URLs like http://url/dir/?var=value
2804 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2805 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2806 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2807 // Pattern for URLs like http://url/dir/page.ext
2808 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2809 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2810 $pattern['ipdp'] = $http . $ip . $dir . $page;
2811 // Pattern for URLs like http://url/dir
2812 $pattern['d1d'] = $http . $domain1 . $dir;
2813 $pattern['d2d'] = $http . $domain2 . $dir;
2814 $pattern['ipd'] = $http . $ip . $dir;
2815 // Pattern for URLs like http://url/?var=value
2816 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2817 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2818 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2819 // Pattern for URLs like http://url?var=value
2820 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2821 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2822 $pattern['ipg12'] = $http . $ip . $getstring1;
2823 // Test all patterns
2825 foreach ($pattern as $key => $pat) {
2827 if (isDebugRegExpressionEnabled()) {
2828 // @TODO Are these convertions still required?
2829 $pat = str_replace('.', "\.", $pat);
2830 $pat = str_replace('@', "\@", $pat);
2831 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2834 // Check if expression matches
2835 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2838 if ($reg === true) break;
2841 // Return true/false
2845 // Wtites data to a config.php-style file
2846 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2847 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2848 // Initialize some variables
2854 // Is the file there and read-/write-able?
2855 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2856 $search = 'CFG: ' . $comment;
2857 $tmp = $FQFN . '.tmp';
2859 // Open the source file
2860 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2862 // Is the resource valid?
2863 if (is_resource($fp)) {
2864 // Open temporary file
2865 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2867 // Is the resource again valid?
2868 if (is_resource($fp_tmp)) {
2869 // Mark temporary file as readable
2870 $GLOBALS['file_readable'][$tmp] = true;
2873 while (!feof($fp)) {
2874 // Read from source file
2875 $line = fgets ($fp, 1024);
2877 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2880 if ($next === $seek) {
2882 $line = $prefix . $DATA . $suffix . "\n";
2888 // Write to temp file
2889 fputs($fp_tmp, $line);
2895 // Finished writing tmp file
2899 // Close source file
2902 if (($done === true) && ($found === true)) {
2903 // Copy back tmp file and delete tmp :-)
2904 copyFileVerified($tmp, $FQFN, 0644);
2905 return removeFile($tmp);
2906 } elseif ($found === false) {
2907 outputHtml('<strong>CHANGE:</strong> 404!');
2909 outputHtml('<strong>TMP:</strong> UNDONE!');
2913 // File not found, not readable or writeable
2914 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2917 // An error was detected!
2920 // Send notification to admin
2921 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = 0) {
2922 if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
2924 sendAdminsEmails($subject, $templateName, $content, $userid);
2926 // Send out out-dated way
2927 $message = loadEmailTemplate($templateName, $content, $userid);
2928 sendAdminEmails($subject, $message);
2932 // Debug message logger
2933 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2934 // Is debug mode enabled?
2935 if ((isDebugModeEnabled()) || ($force === true)) {
2937 $message = str_replace("\r", '', str_replace("\n", '', $message));
2939 // Log this message away, we better don't call app_die() here to prevent an endless loop
2940 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2941 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2946 // Handle extra values
2947 function handleExtraValues ($filterFunction, $value, $extraValue) {
2948 // Default is the value itself
2951 // Do we have a special filter function?
2952 if (!empty($filterFunction)) {
2953 // Does the filter function exist?
2954 if (function_exists($filterFunction)) {
2955 // Do we have extra parameters here?
2956 if (!empty($extraValue)) {
2957 // Put both parameters in one new array by default
2958 $args = array($value, $extraValue);
2960 // If we have an array simply use it and pre-extend it with our value
2961 if (is_array($extraValue)) {
2962 // Make the new args array
2963 $args = merge_array(array($value), $extraValue);
2966 // Call the multi-parameter call-back
2967 $ret = call_user_func_array($filterFunction, $args);
2969 // One parameter call
2970 $ret = call_user_func($filterFunction, $value);
2979 // Converts timestamp selections into a timestamp
2980 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2981 // Init test variable
2985 // Get last three chars
2986 $test = substr($id, -3);
2988 // Improved way of checking! :-)
2989 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2990 // Found a multi-selection for timings?
2991 $test = substr($id, 0, -3);
2992 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)) {
2993 // Generate timestamp
2994 $postData[$test] = createTimestampFromSelections($test, $postData);
2995 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2996 $GLOBALS['skip_config'][$test] = true;
2998 // Remove data from array
2999 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3000 unset($postData[$test . '_' . $rem]);
3011 // Reverts the german decimal comma into Computer decimal dot
3012 function convertCommaToDot ($str) {
3013 // Default float is not a float... ;-)
3016 // Which language is selected?
3017 switch (getLanguage()) {
3018 case 'de': // German language
3019 // Remove german thousand dots first
3020 $str = str_replace('.', '', $str);
3022 // Replace german commata with decimal dot and cast it
3023 $float = (float)str_replace(',', '.', $str);
3026 default: // US and so on
3027 // Remove thousand dots first and cast
3028 $float = (float)str_replace(',', '', $str);
3036 // Handle menu-depending failed logins and return the rendered content
3037 function handleLoginFailtures ($accessLevel) {
3038 // Default output is empty ;-)
3041 // Is the session data set?
3042 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3043 // Ignore zero values
3044 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3045 // Non-guest has login failures found, get both data and prepare it for template
3046 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3048 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3049 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3053 $OUT = loadTemplate('login_failures', true, $content);
3056 // Reset session data
3057 setSession('mxchange_' . $accessLevel.'_failures', '');
3058 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3061 // Return rendered content
3066 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3068 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3070 // Shall I remove the cache file?
3071 if (isCacheInstanceValid()) {
3073 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3075 $GLOBALS['cache_instance']->removeCacheFile($force);
3078 // Include file given?
3081 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3083 // Is the include there?
3084 if (isIncludeReadable($inc)) {
3085 // And rebuild it from scratch
3086 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3089 // Include not found!
3090 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3096 // Determines the real remote address
3097 function determineRealRemoteAddress () {
3098 // Is a proxy in use?
3099 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3101 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3102 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3103 // Yet, another proxy
3104 $address = $_SERVER['HTTP_CLIENT_IP'];
3106 // The regular address when no proxy was used
3107 $address = $_SERVER['REMOTE_ADDR'];
3110 // This strips out the real address from proxy output
3111 if (strstr($address, ',')) {
3112 $addressArray = explode(',', $address);
3113 $address = $addressArray[0];
3116 // Return the result
3120 // Adds a bonus mail to the queue
3121 // This is a high-level function!
3122 function addNewBonusMail ($data, $mode = '', $output=true) {
3123 // Use mode from data if not set and availble ;-)
3124 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3126 // Generate receiver list
3127 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3130 if (!empty($RECEIVER)) {
3131 // Add bonus mail to queue
3132 addBonusMailToQueue(
3144 // Mail inserted into bonus pool
3145 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3146 } elseif ($output) {
3147 // More entered than can be reached!
3148 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3151 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3155 // Determines referal id and sets it
3156 function determineReferalId () {
3157 // Skip this in non-html-mode and outside ref.php
3158 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3160 // Check if refid is set
3161 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3163 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3164 // The variable user comes from the click-counter script click.php and we only accept this here
3165 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3166 } elseif (isPostRequestElementSet('refid')) {
3167 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3168 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3169 } elseif (isGetRequestElementSet('refid')) {
3170 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3171 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3172 } elseif (isGetRequestElementSet('ref')) {
3173 // Set refid=ref (the referal link uses such variable)
3174 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3175 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3176 // Set session refid als global
3177 $GLOBALS['refid'] = bigintval(getSession('refid'));
3178 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3179 // Select a random user which has confirmed enougth mails
3180 $GLOBALS['refid'] = determineRandomReferalId();
3181 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3182 // Set default refid as refid in URL
3183 $GLOBALS['refid'] = getConfig('def_refid');
3185 // No default id when sql_patches is not installed or none set
3186 $GLOBALS['refid'] = 0;
3189 // Set cookie when default refid > 0
3190 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == 0) && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3191 // Default is not found
3194 // Do we have nickname or userid set?
3195 if (isNicknameUsed($GLOBALS['refid'])) {
3196 // Nickname in URL, so load the id
3197 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3198 } elseif ($GLOBALS['refid'] > 0) {
3199 // Direct userid entered
3200 $found = fetchUserData($GLOBALS['refid']);
3203 // Is the record valid?
3204 if (($found === false) || (!isUserDataValid())) {
3205 // No, then reset referal id
3206 $GLOBALS['refid'] = getConfig('def_refid');
3210 setSession('refid', $GLOBALS['refid']);
3213 // Return determined refid
3214 return $GLOBALS['refid'];
3217 // Enables the reset mode and runs it
3218 function doReset () {
3219 // Enable the reset mode
3220 $GLOBALS['reset_enabled'] = true;
3223 runFilterChain('reset');
3226 // Our shutdown-function
3227 function shutdown () {
3228 // Call the filter chain 'shutdown'
3229 runFilterChain('shutdown', null);
3231 if (SQL_IS_LINK_UP()) {
3233 SQL_CLOSE(__FILE__, __LINE__);
3234 } elseif (!isInstallationPhase()) {
3236 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3239 // Stop executing here
3243 // Setter for userid
3244 function setUserId ($userid) {
3245 // We should not set userid to zero
3246 if ($userid == 0) debug_report_bug('Userid should not be set zero.');
3249 $GLOBALS['userid'] = bigintval($userid);
3252 // Getter for userid or returns zero
3253 function getUserId () {
3257 // Is the userid set?
3258 if (isUserIdSet()) {
3260 $userid = $GLOBALS['userid'];
3267 // Checks ether the userid is set
3268 function isUserIdSet () {
3269 return (isset($GLOBALS['userid']));
3272 // Handle message codes from URL
3273 function handleCodeMessage () {
3274 if (isGetRequestElementSet('code')) {
3275 // Default extension is 'unknown'
3278 // Is extension given?
3279 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3281 // Convert the 'code' parameter from URL to a human-readable message
3282 $message = getMessageFromErrorCode(getRequestElement('code'));
3284 // Load message template
3285 loadTemplate('message', false, $message);
3289 // Setter for extra title
3290 function setExtraTitle ($extraTitle) {
3291 $GLOBALS['extra_title'] = $extraTitle;
3294 // Getter for extra title
3295 function getExtraTitle () {
3296 // Is the extra title set?
3297 if (!isExtraTitleSet()) {
3298 // No, then abort here
3299 debug_report_bug('extra_title is not set!');
3303 return $GLOBALS['extra_title'];
3306 // Checks if the extra title is set
3307 function isExtraTitleSet () {
3308 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3311 // Generates a 'extension foo inactive' message
3312 function generateExtensionInactiveMessage ($ext_name) {
3313 // Is the extension empty?
3314 if (empty($ext_name)) {
3315 // This should not happen
3316 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3320 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3322 // Is an admin logged in?
3324 // Then output admin message
3325 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3328 // Return prepared message
3332 // Generates a 'extension foo not installed' message
3333 function generateExtensionNotInstalledMessage ($ext_name) {
3334 // Is the extension empty?
3335 if (empty($ext_name)) {
3336 // This should not happen
3337 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3341 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3343 // Is an admin logged in?
3345 // Then output admin message
3346 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3349 // Return prepared message
3353 // Generates a message depending on if the extension is not installed or not
3355 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3359 // Is the extension not installed or just deactivated?
3360 switch (isExtensionInstalled($ext_name)) {
3361 case true; // Deactivated!
3362 $message = generateExtensionInactiveMessage($ext_name);
3365 case false; // Not installed!
3366 $message = generateExtensionNotInstalledMessage($ext_name);
3369 default: // Should not happen!
3370 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3371 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3375 // Return the message
3379 // Reads a directory recursively by default and searches for files not matching
3380 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3381 // a whole directory.
3382 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3383 // Add default entries we should exclude
3384 $excludeArray[] = '.';
3385 $excludeArray[] = '..';
3386 $excludeArray[] = '.svn';
3387 $excludeArray[] = '.htaccess';
3389 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3394 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3397 while ($baseFile = readdir($dirPointer)) {
3398 // Exclude '.', '..' and entries in $excludeArray automatically
3399 if (in_array($baseFile, $excludeArray, true)) {
3401 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3405 // Construct include filename and FQFN
3406 $fileName = $baseDir . $baseFile;
3407 $FQFN = getConfig('PATH') . $fileName;
3409 // Remove double slashes
3410 $FQFN = str_replace('//', '/', $FQFN);
3412 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3413 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3414 // These Lines are only for debugging!!
3415 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3416 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3417 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3423 // Skip also files with non-matching prefix genericly
3424 if (($recursive === true) && (isDirectory($FQFN))) {
3425 // Is a redirectory so read it as well
3426 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3428 // And skip further processing
3430 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3432 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3434 } elseif (!isFileReadable($FQFN)) {
3435 // Not readable so skip it
3436 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3440 // Is the file a PHP script or other?
3441 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3442 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3443 // Is this a valid include file?
3444 if ($extension == '.php') {
3445 // Remove both for extension name
3446 $extName = substr($baseFile, strlen($prefix), -4);
3448 // Is the extension valid and active?
3449 if (isExtensionNameValid($extName)) {
3450 // Then add this file
3451 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3452 $files[] = $fileName;
3454 // Add non-extension files as well
3455 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3456 if ($addBaseDir === true) {
3457 $files[] = $fileName;
3459 $files[] = $baseFile;
3463 // We found .php file but should not search for them, why?
3464 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3466 } elseif (substr($baseFile, -4, 4) == $extension) {
3467 // Other, generic file found
3468 $files[] = $fileName;
3473 closedir($dirPointer);
3478 // Return array with include files
3479 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3483 // Maps a module name into a database table name
3484 function mapModuleToTable ($moduleName) {
3485 // Map only these, still lame code...
3486 switch ($moduleName) {
3487 // 'index' is the guest's menu
3488 case 'index': $moduleName = 'guest'; break;
3489 // ... and 'login' the member's menu
3490 case 'login': $moduleName = 'member'; break;
3491 // Anything else will not be mapped, silently.
3498 // Add SQL debug data to array for later output
3499 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3500 // Already executed?
3501 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3502 // Then abort here, we don't need to profile a query twice
3506 // Remeber this as profiled (or not, but we don't care here)
3507 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3509 // Do we have cache?
3510 if (!isset($GLOBALS['debug_sql_available'])) {
3511 // Check it and cache it in $GLOBALS
3512 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3515 // Don't execute anything here if we don't need or ext-other is missing
3516 if ($GLOBALS['debug_sql_available'] === false) {
3522 'num_rows' => SQL_NUMROWS($result),
3523 'affected' => SQL_AFFECTEDROWS(),
3524 'sql_str' => $sqlString,
3525 'timing' => $timing,
3526 'file' => basename($F),
3531 $GLOBALS['debug_sqls'][] = $record;
3534 // Initializes the cache instance
3535 function initCacheInstance () {
3536 // Load include for CacheSystem class
3537 loadIncludeOnce('inc/classes/cachesystem.class.php');
3539 // Initialize cache system only when it's needed
3540 $GLOBALS['cache_instance'] = new CacheSystem();
3541 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3542 // Failed to initialize cache sustem
3543 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3547 // Getter for message from array or raw message
3548 function getMessageFromIndexedArray ($message, $pos, $array) {
3549 // Check if the requested message was found in array
3550 if (isset($array[$pos])) {
3551 // ... if yes then use it!
3552 $ret = $array[$pos];
3554 // ... else use default message
3562 // Print code with line numbers
3563 function linenumberCode ($code) {
3564 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3565 $count_lines = count($codeE);
3567 $r = 'Line | Code:<br />';
3568 foreach($codeE as $line => $c) {
3569 $r .= '<div class="line"><span class="linenum">';
3570 if ($count_lines == 1) {
3573 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3578 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3581 return '<div class="code">' . $r . '</div>';
3584 // Convert ';' to ', ' for e.g. receiver list
3585 function convertReceivers ($old) {
3586 return str_replace(';', ', ', $old);
3589 // Determines the right page title
3590 function determinePageTitle () {
3591 // Config and database connection valid?
3592 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3596 // Title decoration enabled?
3597 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
3599 // Do we have some extra title?
3600 if (isExtraTitleSet()) {
3602 $TITLE .= getExtraTitle() . ' by ';
3606 $TITLE .= getConfig('MAIN_TITLE');
3608 // Add title of module? (middle decoration will also be added!)
3609 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3610 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3613 // Add title from what file
3615 if (getModule() == 'login') $mode = 'member';
3616 elseif (getModule() == 'index') $mode = 'guest';
3617 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= " ".trim(getConfig('title_middle'))." ".getModuleDescription($mode, getWhat());
3619 // Add title decorations? (right)
3620 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= " ".trim(getConfig('title_right'));
3622 // Remember title in constant for the template
3623 $pageTitle = $TITLE;
3624 } elseif ((isInstalled()) && (isAdminRegistered())) {
3625 // Installed, admin registered but no ext-sql_patches
3626 $pageTitle = '[-- ' . getConfig('MAIN_TITLE').' - '.getModuleTitle(getModule()) . ' --]';
3627 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3628 // Installed but no admin registered
3629 $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
3630 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3631 // Installation mode
3632 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3634 // Configuration not found!
3635 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3637 // Do not add the fatal message in installation mode
3638 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3645 // Checks wethere there is a cache file there. This function is cached.
3646 function isTemplateCached ($template) {
3647 // Do we have cached this result?
3648 if (!isset($GLOBALS['template_cache'][$template])) {
3650 $FQFN = sprintf("%stemplates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3653 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3657 return $GLOBALS['template_cache'][$template];
3660 // Flushes non-flushed template cache to disk
3661 function flushTemplateCache ($template, $eval) {
3662 // Is this cache flushed?
3663 if (!isTemplateCached($template)) {
3665 $FQFN = sprintf("%stemplates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3667 // Replace username with a call
3668 $eval = str_replace('$username', '".getUsername()."', $eval);
3671 writeToFile($FQFN, $eval, true);
3675 // Reads a template cache
3676 function readTemplateCache ($template) {
3678 if (isTemplateCached($template)) {
3680 $FQFN = sprintf("%stemplates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3683 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3687 return $GLOBALS['template_eval'][$template];
3690 //////////////////////////////////////////////////
3691 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3692 //////////////////////////////////////////////////
3694 if (!function_exists('html_entity_decode')) {
3695 // Taken from documentation on www.php.net
3696 function html_entity_decode ($string) {
3697 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3698 $trans_tbl = array_flip($trans_tbl);
3699 return strtr($string, $trans_tbl);
3703 if (!function_exists('http_build_query')) {
3704 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3705 function http_build_query($data, $prefix='', $sep='', $key='') {
3707 foreach ((array)$data as $k => $v) {
3708 if (is_int($k) && $prefix != null) {
3709 $k = urlencode($prefix . $k);
3712 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3714 if (is_array($v) || is_object($v)) {
3715 array_push($ret, http_build_query($v, '', $sep, $k));
3717 array_push($ret, $k.'='.urlencode($v));
3721 if (empty($sep)) $sep = ini_get('arg_separator.output');
3723 return implode($sep, $ret);