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 = getUsername();
49 // Do we have HTML-Code here?
50 if (!empty($htmlCode)) {
51 // Yes, so we handle it as you have configured
52 switch (getConfig('OUTPUT_MODE')) {
54 // That's why you don't need any \n at the end of your HTML code... :-)
55 if (getPhpCaching() == 'on') {
56 // Output into PHP's internal buffer
57 outputRawCode($htmlCode);
59 // That's why you don't need any \n at the end of your HTML code... :-)
60 if ($newLine === true) print("\n");
62 // Render mode for old or lame servers...
63 $GLOBALS['output'] .= $htmlCode;
65 // That's why you don't need any \n at the end of your HTML code... :-)
66 if ($newLine === true) $GLOBALS['output'] .= "\n";
71 // If we are switching from render to direct output rendered code
72 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
74 // The same as above... ^
75 outputRawCode($htmlCode);
76 if ($newLine) print("\n");
80 // Huh, something goes wrong or maybe you have edited config.php ???
81 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
84 } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
85 // Headers already sent?
88 logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
90 // Trigger an user error
91 debug_report_bug('Headers are already sent!');
94 // Output cached HTML code
95 $GLOBALS['output'] = ob_get_contents();
97 // Clear output buffer for later output if output is found
98 if (!empty($GLOBALS['output'])) {
103 sendHeader('HTTP/1.1 200');
106 $now = gmdate('D, d M Y H:i:s') . ' GMT';
108 // General headers for no caching
109 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
110 sendHeader('Last-Modified: ' . $now);
111 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
112 sendHeader('Pragma: no-cache'); // HTTP/1.0
113 sendHeader('Connection: Close');
114 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
115 sendHeader('Content-language: ' . getLanguage());
117 // Extension 'rewrite' installed?
118 if ((isExtensionActive('rewrite')) && (getOutputMode() != '1')) {
119 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
122 // Compile and run finished rendered HTML code
123 while ((strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) {
124 // Prepare the content and eval() it...
129 $eval = "\$newContent = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";";
132 // Was that eval okay?
133 if (empty($newContent)) {
134 // Something went wrong!
135 debug_report_bug('Evaluation error:<pre>' . htmlentities($eval) . '</pre>');
137 $GLOBALS['output'] = $newContent;
140 // Output code here, DO NOT REMOVE! ;-)
141 outputRawCode($GLOBALS['output']);
142 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
143 // Rewrite links when rewrite extension is active
144 if ((isExtensionActive('rewrite')) && (getOutputMode() != '1')) {
145 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
148 // Compile and run finished rendered HTML code
149 while (strpos($GLOBALS['output'], '{!') > 0) {
150 eval("\$GLOBALS['output'] = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";");
153 // Output code here, DO NOT REMOVE! ;-)
154 outputRawCode($GLOBALS['output']);
158 // Output the raw HTML code
159 function outputRawCode ($htmlCode) {
160 // Output stripped HTML code to avoid broken JavaScript code, etc.
161 print(stripslashes(stripslashes($htmlCode)));
163 // Flush the output if only getPhpCaching() is not 'on'
164 if (getPhpCaching() != 'on') {
170 // Init fatal message array
171 function initFatalMessages () {
172 $GLOBALS['fatal_messages'] = array();
175 // Getter for whole fatal error messages
176 function getFatalArray () {
177 return $GLOBALS['fatal_messages'];
180 // Add a fatal error message to the queue array
181 function addFatalMessage ($F, $L, $message, $extra='') {
182 if (is_array($extra)) {
183 // Multiple extras for a message with masks
184 $message = call_user_func_array('sprintf', $extra);
185 } elseif (!empty($extra)) {
186 // $message is text with a mask plus extras to insert into the text
187 $message = sprintf($message, $extra);
190 // Add message to $GLOBALS['fatal_messages']
191 $GLOBALS['fatal_messages'][] = $message;
193 // Log fatal messages away
194 logDebugMessage($F, $L, " message={$message}");
197 // Getter for total fatal message count
198 function getTotalFatalErrors () {
202 // Do we have at least the first entry?
203 if (!empty($GLOBALS['fatal_messages'][0])) {
205 $count = count($GLOBALS['fatal_messages']);
212 // Load a template file and return it's content (only it's name; do not use ' or ")
213 function loadTemplate ($template, $return=false, $content=array()) {
214 // @TODO Remove this sanity-check if all is fine
215 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
217 // @TODO Try to rewrite all $DATA to $content
221 if (!isset($GLOBALS['template_eval'][$template])) {
222 // Add more variables which you want to use in your template files
223 $username = getUsername();
225 // Make all template names lowercase
226 $template = strtolower($template);
228 // Count the template load
229 incrementConfigEntry('num_templates');
233 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
235 // Generate date/time string
236 $date_time = generateDateTime(time(), '1');
238 // Is content an array
239 if (is_array($content)) $content['date_time'] = $date_time;
241 // @DEPRECATED Try to rewrite the if() condition
242 if ($template == 'member_support_form') {
243 // Support request of a member
244 $result = SQL_QUERY_ESC("SELECT `userid`, `gender`, `surname`, `family`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
245 array(getUserId()), __FUNCTION__, __LINE__);
247 // Is content an array?
248 if (is_array($content)) {
250 $content = merge_array($content, SQL_FETCHARRAY($result));
253 $content['gender'] = translateGender($content['gender']);
256 // @TODO Find all templates which are using these direct variables and rewrite them.
257 // @TODO After this step is done, this else-block is history
258 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
261 $gender = translateGender($gender);
262 logDebugMessage(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
266 SQL_FREERESULT($result);
270 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
273 // Check for admin/guest/member templates
274 if (substr($template, 0, 6) == 'admin_') {
275 // Admin template found
277 } elseif (substr($template, 0, 6) == 'guest_') {
278 // Guest template found
280 } elseif (substr($template, 0, 7) == 'member_') {
281 // Member template found
283 } elseif (substr($template, 0, 8) == 'install_') {
284 // Installation template found
286 } elseif (substr($template, 0, 4) == 'ext_') {
287 // Extension template found
289 } elseif (substr($template, 0, 3) == 'la_') {
290 // 'Logical-area' template found
292 } elseif (substr($template, 0, 3) == 'js_') {
293 // JavaScript template found
295 } elseif (substr($template, 0, 5) == 'menu_') {
296 // Menu template found
299 // Test for extension
300 $test = substr($template, 0, strpos($template, '_'));
302 // Probe for valid extension name
303 if (isExtensionNameValid($test)) {
304 // Set extra path to extension's name
309 ////////////////////////
310 // Generate file name //
311 ////////////////////////
312 $FQFN = $basePath . $mode . $template . '.tpl';
314 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
315 // Select what depended header/footer template file for admin/guest/member area
316 $file2 = sprintf("%s%s%s_%s.tpl",
324 if (isFileReadable($file2)) $FQFN = $file2;
326 // Remove variable from memory
330 // Does the special template exists?
331 if (!isFileReadable($FQFN)) {
332 // Reset to default template
333 $FQFN = $basePath . $template . '.tpl';
336 // Now does the final template exists?
337 if (isFileReadable($FQFN)) {
338 // The local file does exists so we load it. :)
339 $GLOBALS['tpl_content'] = readFromFile($FQFN);
341 // Replace ' to our own chars to preventing them being quoted
342 while (strpos($GLOBALS['tpl_content'], "'") !== false) { $GLOBALS['tpl_content'] = str_replace("'", '{QUOT}', $GLOBALS['tpl_content']); }
344 // Do we have to compile the code?
346 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
347 // Normal HTML output?
348 if ($GLOBALS['output_mode'] == 0) {
349 // Add surrounding HTML comments to help finding bugs faster
350 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
352 // Prepare eval() command
353 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
355 // Prepare eval() command
356 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
359 // Simply return loaded code
360 $eval = '$ret = $GLOBALS[\'tpl_content\'];';
363 // Cache the eval() command here
364 $GLOBALS['template_eval'][$template] = $eval;
367 eval($GLOBALS['template_eval'][$template]);
370 $GLOBALS['template_eval'][$template] = '404';
372 } elseif (((isAdmin()) || ((isInstalling()) && (!isInstalled()))) && ($GLOBALS['template_eval'][$template] == '404')) {
373 // Only admins shall see this warning or when installation mode is active
374 $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
375 (' . $template . ')<br />
377 {--TEMPLATE_CONTENT--}
378 <pre>' . print_r($content, true) . '</pre>
380 <pre>' . print_r($DATA, true) . '</pre>
384 eval($GLOBALS['template_eval'][$template]);
387 // Do we have some content to output or return?
389 // Not empty so let's put it out! ;)
390 if ($return === true) {
391 // Return the HTML code
397 } elseif (isDebugModeEnabled()) {
398 // Warning, empty output!
399 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
403 // Loads an email template and compiles it
404 function loadEmailTemplate ($template, $content = array(), $UID = '0') {
407 // Our configuration is kept non-global here
408 $_CONFIG = getConfigArray();
410 // Make sure all template names are lowercase!
411 $template = strtolower($template);
413 // Default 'nickname' if extension is not installed
416 // Prepare IP number and User Agent
417 $REMOTE_ADDR = detectRemoteAddr();
418 $HTTP_USER_AGENT = detectUserAgent();
421 $ADMIN = getConfig('MAIN_TITLE');
423 // Is the admin logged in?
426 $adminId = getCurrentAdminId();
429 $ADMIN = getAdminEmail($adminId);
432 // Neutral email address is default
433 $email = getConfig('WEBMASTER');
435 // Expiration in a nice output format
436 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
437 if (getConfig('auto_purge') == 0) {
438 // Will never expire!
439 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
441 // Create nice date string
442 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
445 // Is content an array?
446 if (is_array($content)) {
447 // Add expiration to array, $EXPIRATION is now deprecated!
448 $content['expiration'] = $EXPIRATION;
452 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />");
453 if (($UID > 0) && (is_array($content))) {
454 // If nickname extension is installed, fetch nickname as well
455 if (isExtensionActive('nickname')) {
456 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
458 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email`, `nickname` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
459 array(bigintval($UID)), __FUNCTION__, __LINE__);
461 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
463 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
464 array(bigintval($UID)), __FUNCTION__, __LINE__);
467 // Fetch and merge data
468 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
469 $content = merge_array($content, SQL_FETCHARRAY($result));
470 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
473 SQL_FREERESULT($result);
476 // Translate M to male or F to female if present
477 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
479 // Overwrite email from data if present
480 if (isset($content['email'])) $email = $content['email'];
482 // Store email for some functions in global data array
483 $DATA['email'] = $email;
486 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
488 // Check for admin/guest/member templates
489 if (substr($template, 0, 6) == 'admin_') {
490 // Admin template found
491 $FQFN = $basePath.'admin/' . $template.'.tpl';
492 } elseif (substr($template, 0, 6) == 'guest_') {
493 // Guest template found
494 $FQFN = $basePath.'guest/' . $template.'.tpl';
495 } elseif (substr($template, 0, 7) == 'member_') {
496 // Member template found
497 $FQFN = $basePath.'member/' . $template.'.tpl';
499 // Test for extension
500 $test = substr($template, 0, strpos($template, '_'));
501 if (isExtensionNameValid($test)) {
502 // Set extra path to extension's name
503 $FQFN = $basePath . $test.'/' . $template.'.tpl';
505 // No special filename
506 $FQFN = $basePath . $template.'.tpl';
510 // Does the special template exists?
511 if (!isFileReadable($FQFN)) {
512 // Reset to default template
513 $FQFN = $basePath . $template.'.tpl';
516 // Now does the final template exists?
518 if (isFileReadable($FQFN)) {
519 // The local file does exists so we load it. :)
520 $GLOBALS['tpl_content'] = readFromFile($FQFN);
521 $GLOBALS['tpl_content'] = SQL_ESCAPE($GLOBALS['tpl_content']);
524 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode($GLOBALS['tpl_content'])."\");";
525 eval($GLOBALS['tpl_content']);
526 } elseif (!empty($template)) {
527 // Template file not found!
528 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
529 {--TEMPLATE_CONTENT--}
530 <pre>".print_r($content, true)."</pre>
532 <pre>".print_r($DATA, true)."</pre>
535 // Debug mode not active? Then remove the HTML tags
536 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
538 // No template name supplied!
539 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
542 // Is there some content?
543 if (empty($newContent)) {
545 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
546 // Add last error if the required function exists
547 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
550 // Remove content and data
554 // Return compiled content
555 return compileCode($newContent);
558 // Send mail out to an email address
559 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
560 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
562 // Compile subject line (for POINTS constant etc.)
563 eval("\$subject = decodeEntities(\"".compileCode(smartAddSlashes($subject))."\");");
566 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
567 // Value detected, is the message extension installed?
568 // @TODO Extension 'msg' does not exist
569 if (isExtensionActive('msg')) {
570 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
573 // Load email address
574 $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
575 array(bigintval($toEmail)), __FUNCTION__, __LINE__);
576 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />");
578 // Does the user exist?
579 if (SQL_NUMROWS($result_email)) {
580 // Load email address
581 list($toEmail) = SQL_FETCHROW($result_email);
584 $toEmail = getConfig('WEBMASTER');
588 SQL_FREERESULT($result_email);
590 } elseif ($toEmail == '0') {
592 $toEmail = getConfig('WEBMASTER');
594 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
596 // Check for PHPMailer or debug-mode
597 if (!checkPhpMailerUsage()) {
598 // Not in PHPMailer-Mode
599 if (empty($mailHeader)) {
600 // Load email header template
601 $mailHeader = loadEmailTemplate('header');
604 $mailHeader .= loadEmailTemplate('header');
606 } elseif (isDebugModeEnabled()) {
607 if (empty($mailHeader)) {
608 // Load email header template
609 $mailHeader = loadEmailTemplate('header');
612 $mailHeader .= loadEmailTemplate('header');
617 eval("\$toEmail = \"".compileCode(smartAddSlashes($toEmail))."\";");
620 eval("\$message = \"".compileCode(smartAddSlashes($message))."\";");
622 // Fix HTML parameter (default is no!)
623 if (empty($isHtml)) $isHtml = 'N';
624 if (isDebugModeEnabled()) {
625 // In debug mode we want to display the mail instead of sending it away so we can debug this part
627 ".htmlentities(trim($mailHeader))."
629 Subject : " . $subject."
630 Message : " . $message."
632 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
633 // Send mail as HTML away
634 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
635 } elseif (!empty($toEmail)) {
637 sendRawEmail($toEmail, $subject, $message, $mailHeader);
638 } elseif ($isHtml != 'Y') {
640 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
644 // Check if legacy or PHPMailer command
645 // @TODO Rewrite this to an extension 'smtp'
647 function checkPhpMailerUsage() {
648 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
651 // Send out a raw email with PHPMailer class or legacy mail() command
652 function sendRawEmail ($toEmail, $subject, $message, $from) {
653 // Shall we use PHPMailer class or legacy mode?
654 if (checkPhpMailerUsage()) {
655 // Use PHPMailer class with SMTP enabled
656 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
657 loadIncludeOnce('inc/phpmailer/class.smtp.php');
660 $mail = new PHPMailer();
661 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
664 $mail->SMTPAuth = true;
665 $mail->Host = getConfig('SMTP_HOSTNAME');
667 $mail->Username = getConfig('SMTP_USER');
668 $mail->Password = getConfig('SMTP_PASSWORD');
670 $mail->From = getConfig('WEBMASTER');
674 $mail->FromName = getConfig('MAIN_TITLE');
675 $mail->Subject = $subject;
676 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
677 $mail->Body = $message;
678 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
679 $mail->WordWrap = 70;
682 $mail->Body = decodeEntities($message);
684 $mail->AddAddress($toEmail, '');
685 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
686 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
687 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
690 // Use legacy mail() command
691 mail($toEmail, $subject, decodeEntities($message), $from);
695 // Generate a password in a specified length or use default password length
696 function generatePassword ($length = 0) {
697 // Auto-fix invalid length of zero
698 if ($length == 0) $length = getConfig('pass_len');
700 // Initialize array with all allowed chars
701 $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,-,+,_,/,.');
703 // Start creating password
705 for ($i = 0; $i < $length; $i++) {
706 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
709 // When the size is below 40 we can also add additional security by scrambling
710 // it. Otherwise we may corrupt hashes
711 if (strlen($PASS) <= 40) {
712 // Also scramble the password
713 $PASS = scrambleString($PASS);
716 // Return the password
720 // Generates a human-readable timestamp from the Uni* stamp
721 function generateDateTime ($time, $mode = '0') {
722 // Filter out numbers
723 $time = bigintval($time);
725 // If the stamp is zero it mostly didn't "happen"
728 return getMessage('NEVER_HAPPENED');
731 switch (getLanguage()) {
732 case 'de': // German date / time format
734 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
735 case '1': $ret = strtolower(date("d.m.Y - H:i", $time)); break;
736 case '2': $ret = date("d.m.Y|H:i", $time); break;
737 case '3': $ret = date("d.m.Y", $time); break;
739 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
744 default: // Default is the US date / time format!
746 case '0': $ret = date("r", $time); break;
747 case '1': $ret = date("Y-m-d - g:i A", $time); break;
748 case '2': $ret = date("y-m-d|H:i", $time); break;
749 case '3': $ret = date("y-m-d", $time); break;
751 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
760 // Translates Y/N to yes/no
761 function translateYesNo ($yn) {
763 $translated = "??? (" . $yn.')';
765 case 'Y': $translated = getMessage('YES'); break;
766 case 'N': $translated = getMessage('NO'); break;
769 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
777 // Translates the "pool type" into human-readable
778 function translatePoolType ($type) {
779 // Default?type is unknown
780 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
783 $constName = sprintf("POOL_TYPE_%s", $type);
786 if (isMessageIdValid($constName)) {
788 $translated = getMessage($constName);
791 // Return "translation"
795 // Translates the american decimal dot into a german comma
796 function translateComma ($dotted, $cut = true, $max = 0) {
797 // Default is 3 you can change this in admin area "Misc -> Misc Options"
798 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
800 // Use from config is default
801 $maxComma = getConfig('max_comma');
803 // Use from parameter?
804 if ($max > 0) $maxComma = $max;
807 if (($cut === true) && ($max == 0)) {
808 // Test for commata if in cut-mode
809 $com = explode('.', $dotted);
810 if (count($com) < 2) {
811 // Don't display commatas even if there are none... ;-)
817 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
820 switch (getLanguage()) {
821 case 'de': // German language
822 $dotted = number_format($dotted, $maxComma, ',', '.');
825 default: // All others
826 $dotted = number_format($dotted, $maxComma, '.', ',');
830 // Return translated value
834 // Translate Uni*-like gender to human-readable
835 function translateGender ($gender) {
837 $ret = '!' . $gender . '!';
839 // Male/female or company?
841 case 'M': $ret = getMessage('GENDER_M'); break;
842 case 'F': $ret = getMessage('GENDER_F'); break;
843 case 'C': $ret = getMessage('GENDER_C'); break;
845 // Log unknown gender
846 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
850 // Return translated gender
854 // "Translates" the user status
855 function translateUserStatus ($status) {
856 // Generate message depending on status
861 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
866 $ret = getMessage('ACCOUNT_DELETED');
870 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
871 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
879 // Generates an URL for the dereferer
880 function generateDerefererUrl ($URL) {
881 // Don't de-refer our own links!
882 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
883 // De-refer this link
884 $URL = 'modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
891 // Generates an URL for the frametester
892 function generateFrametesterUrl ($URL) {
893 // Prepare frametester URL
894 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
895 encodeString(compileUriCode($URL))
898 // Return the new URL
899 return $frametesterUrl;
902 // Count entries from e.g. a selection box
903 function countSelection ($array) {
905 if (!is_array($array)) {
907 debug_report_bug(__FUNCTION__.': No array provided.');
914 foreach ($array as $key => $selected) {
916 if (!empty($selected)) $ret++;
919 // Return counted selections
923 // Generate XHTML code for the CAPTCHA
924 function generateCaptchaCode ($code, $type, $DATA, $userid) {
925 return '<IMG border="0" alt="Code" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
928 // Generates a timestamp (some wrapper for mktime())
929 function makeTime ($H, $M, $S, $stamp) {
930 // Extract day, month and year from given timestamp
931 $day = date('d', $stamp);
932 $month = date('m', $stamp);
933 $year = date('Y', $stamp);
935 // Create timestamp for wished time which depends on extracted date
936 return mktime($H, $M, $S, $month, $day, $year);
939 // Redirects to an URL and if neccessarry extends it with own base URL
940 function redirectToUrl ($URL) {
941 // Compile out URI codes
942 $URL = compileUriCode($URL);
944 // Check if http(s):// is there
945 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
946 // Make all URLs full-qualified
947 $URL = getConfig('URL') . '/' . $URL;
950 // Three different debug ways...
951 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
952 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $URL);
953 //* DEBUG: */ die($URL);
955 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
956 $rel = ' rel="external"';
958 // Do we have internal or external URL?
959 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
960 // Own (=internal) URL
965 $GLOBALS['output'] = ob_get_contents();
967 // Clear it only if there is content
968 if (!empty($GLOBALS['output'])) {
972 // Simple probe for bots/spiders from search engines
973 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
974 // Secure the URL against bad things such als HTML insertions and so on...
975 $URL = secureString($URL);
977 // Output new location link as anchor
978 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
979 } elseif (!headers_sent()) {
980 // Load URL when headers are not sent
981 //* DEBUG: */ debug_report_bug("URL={$URL}");
982 sendHeader('Location: '.str_replace('&', '&', $URL));
984 // Output error message
985 loadInclude('inc/header.php');
986 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
987 loadInclude('inc/footer.php');
990 // Shut the mailer down here
994 // Wrapper for redirectToUrl but URL comes from a configuration entry
995 function redirectToConfiguredUrl ($configEntry) {
997 $URL = getConfig($configEntry);
1000 if (is_null($URL)) {
1002 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1006 redirectToUrl($URL);
1009 // Compiles the given HTML/mail code
1010 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1011 // Is the code a string?
1012 if (!is_string($code)) {
1013 // Silently return it
1017 // Init replacement-array with full security characters
1018 $secChars = $GLOBALS['security_chars'];
1020 // Select smaller set of chars to replace when we e.g. want to compile URLs
1021 if ($full === false) $secChars = $GLOBALS['url_chars'];
1023 // Compile more through a filter
1024 $code = runFilterChain('compile_code', $code);
1026 // Compile constants
1027 if ($constants === true) {
1028 // BEFORE 0.2.1 : Language and data constants
1029 // WITH 0.2.1+ : Only language constants
1030 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1032 // BEFORE 0.2.1 : Not used
1033 // WITH 0.2.1+ : Data constants
1034 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1037 // Compile QUOT and other non-HTML codes
1038 foreach ($secChars['to'] as $k => $to) {
1039 // Do the reversed thing as in inc/libs/security_functions.php
1040 $code = str_replace($to, $secChars['from'][$k], $code);
1043 // But shall I keep simple quotes for later use?
1044 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1046 // Find $content[bla][blub] entries
1047 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1049 // Are some matches found?
1050 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1051 // Replace all matches
1052 $matchesFound = array();
1053 foreach ($matches[0] as $key => $match) {
1054 // Fuzzy look has failed by default
1055 $fuzzyFound = false;
1057 // Fuzzy look on match if already found
1058 foreach ($matchesFound as $found => $set) {
1060 $test = substr($found, 0, strlen($match));
1062 // Does this entry exist?
1063 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1064 if ($test == $match) {
1066 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1073 if ($fuzzyFound === true) continue;
1075 // Take all string elements
1076 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1077 // Replace it in the code
1078 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1079 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1080 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1081 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1082 $matchesFound[$match] = 1;
1083 } elseif (!isset($matchesFound[$match])) {
1084 // Not yet replaced!
1085 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1086 $code = str_replace($match, "\"." . $match.".\"", $code);
1087 $matchesFound[$match] = 1;
1092 // Return compiled code
1096 /************************************************************************
1098 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1099 * $a_sort sortiert: *
1101 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1102 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1103 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1104 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1105 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1107 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1108 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1109 * Sie, dass es doch nicht so schwer ist! :-) *
1111 ************************************************************************/
1112 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1114 while ($primary_key < count($a_sort)) {
1115 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1116 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1118 if ($nums === false) {
1119 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1120 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1121 } elseif ($key != $key2) {
1122 // Sort numbers (E.g.: 9 < 10)
1123 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1124 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1128 // We have found two different values, so let's sort whole array
1129 foreach ($dummy as $sort_key => $sort_val) {
1130 $t = $dummy[$sort_key][$key];
1131 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1132 $dummy[$sort_key][$key2] = $t;
1143 // Write back sorted array
1148 function addSelectionBox ($type, $default, $prefix = '', $id = '0') {
1151 if ($type == 'yn') {
1152 // This is a yes/no selection only!
1153 if ($id > 0) $prefix .= "[" . $id."]";
1154 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1156 // Begin with regular selection box here
1157 if (!empty($prefix)) $prefix .= "_";
1159 if ($id > 0) $type2 .= "[" . $id."]";
1160 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1165 for ($idx = 1; $idx < 32; $idx++) {
1166 $OUT .= "<option value=\"" . $idx."\"";
1167 if ($default == $idx) $OUT .= ' selected="selected"';
1168 $OUT .= ">" . $idx."</option>\n";
1172 case 'month': // Month
1173 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1174 $OUT .= "<option value=\"" . $month."\"";
1175 if ($default == $month) $OUT .= ' selected="selected"';
1176 $OUT .= ">" . $descr."</option>\n";
1180 case 'year': // Year
1182 $year = date('Y', time());
1184 // Use configured min age or fixed?
1185 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1187 $startYear = $year - getConfig('min_age');
1190 $startYear = $year - 16;
1193 // Calculate earliest year (100 years old people can still enter Internet???)
1194 $minYear = $year - 100;
1196 // Check if the default value is larger than minimum and bigger than actual year
1197 if (($default > $minYear) && ($default >= $year)) {
1198 for ($idx = $year; $idx < ($year + 11); $idx++) {
1199 $OUT .= "<option value=\"" . $idx."\"";
1200 if ($default == $idx) $OUT .= ' selected="selected"';
1201 $OUT .= ">" . $idx."</option>\n";
1203 } elseif ($default == -1) {
1204 // Current year minus 1
1205 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1207 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1210 // Get current year and subtract the configured minimum age
1211 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1212 // Calculate earliest year depending on extension version
1213 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1214 // Use configured minimum age
1215 $year = date('Y', time()) - getConfig('min_age');
1217 // Use fixed 16 years age
1218 $year = date('Y', time()) - 16;
1221 // Construct year selection list
1222 for ($idx = $minYear; $idx <= $year; $idx++) {
1223 $OUT .= "<option value=\"" . $idx."\"";
1224 if ($default == $idx) $OUT .= ' selected="selected"';
1225 $OUT .= ">" . $idx."</option>\n";
1232 for ($idx = 0; $idx < 60; $idx+=5) {
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 for ($idx = 0; $idx < 24; $idx++) {
1242 if (strlen($idx) == 1) $idx = '0' . $idx;
1243 $OUT .= "<option value=\"" . $idx."\"";
1244 if ($default == $idx) $OUT .= ' selected="selected"';
1245 $OUT .= ">" . $idx."</option>\n";
1250 $OUT .= "<option value=\"Y\"";
1251 if ($default == 'Y') $OUT .= ' selected="selected"';
1252 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1253 if ($default != 'Y') $OUT .= ' selected="selected"';
1254 $OUT .= ">{--NO--}</option>\n";
1257 $OUT .= " </select>\n";
1262 // Deprecated : $length
1265 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1266 // Build server string
1267 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1270 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1271 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1272 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1273 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1274 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1276 // Build string from misc data
1277 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1279 // Add more additional data
1280 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1282 // Add referal id, language, theme and userid
1283 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1284 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1285 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1286 $data .= getConfig('ENCRYPT_SEPERATOR') . getUserId();
1288 // Calculate number for generating the code
1289 $a = $code + getConfig('_ADD') - 1;
1291 if (isConfigEntrySet('master_hash')) {
1292 // Generate hash with master salt from modula of number with the prime number and other data
1293 $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'));
1295 // Create number from hash
1296 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1298 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1299 $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, 8));
1301 // Create number from hash
1302 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1305 // At least 10 numbers shall be secure enought!
1306 $len = getConfig('code_length');
1307 if ($len == 0) $len = $length;
1308 if ($len == 0) $len = 10;
1310 // Cut off requested counts of number
1311 $return = substr(str_replace('.', '', $rcode), 0, $len);
1313 // Done building code
1317 // Does only allow numbers
1318 function bigintval ($num, $castValue = true) {
1319 // Filter all numbers out
1320 $ret = preg_replace("/[^0123456789]/", '', $num);
1323 if ($castValue) $ret = (double)$ret;
1325 // Has the whole value changed?
1326 // @TODO Remove this if() block if all is working fine
1327 if ('' . $ret . '' != '' . $num . '') {
1329 //debug_report_bug("{$ret}<>{$num}");
1336 // Insert the code in $img_code into jpeg or PNG image
1337 function generateImageOrCode ($img_code, $headerSent=true) {
1338 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1339 // Stop execution of function here because of over-sized code length
1341 } elseif ($headerSent === false) {
1342 // Return in an HTML code code
1343 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1347 $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
1348 if (isFileReadable($img)) {
1349 // Switch image type
1350 switch (getConfig('img_type'))
1353 // Okay, load image and hide all errors
1354 $image = imagecreatefromjpeg($img);
1358 // Okay, load image and hide all errors
1359 $image = imagecreatefrompng($img);
1363 // Exit function here
1364 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1368 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1369 $text_color = imagecolorallocate($image, 0, 0, 0);
1371 // Insert code into image
1372 imagestring($image, 5, 14, 2, $img_code, $text_color);
1374 // Return to browser
1375 sendHeader('Content-Type: image/' . getConfig('img_type'));
1377 // Output image with matching image factory
1378 switch (getConfig('img_type')) {
1379 case 'jpg': imagejpeg($image); break;
1380 case 'png': imagepng($image); break;
1383 // Remove image from memory
1384 imagedestroy($image);
1386 // Create selection box or array of splitted timestamp
1387 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1388 // Calculate 2-seconds timestamp
1389 $stamp = round($timestamp);
1390 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1392 // Do we have a leap year?
1394 $TEST = date('Y', time()) / 4;
1395 $M1 = date('m', time());
1396 $M2 = date('m', (time() + $timestamp));
1398 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1399 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1401 // First of all years...
1402 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1403 //* DEBUG: */ print("Y={$Y}<br />");
1405 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1406 //* DEBUG: */ print("M={$M}<br />");
1408 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1409 //* DEBUG: */ print("W={$W}<br />");
1411 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1412 //* DEBUG: */ print("D={$D}<br />");
1414 $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));
1415 //* DEBUG: */ print("h={$h}<br />");
1417 $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));
1418 //* DEBUG: */ print("m={$m}<br />");
1419 // And at last seconds...
1420 $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));
1421 //* DEBUG: */ print("s={$s}<br />");
1423 // Is seconds zero and time is < 60 seconds?
1424 if (($s == 0) && ($timestamp < 60)) {
1426 $s = round($timestamp);
1430 // Now we convert them in seconds...
1432 if ($return_array) {
1433 // Just put all data in an array for later use
1445 $OUT = "<div align=\"" . $align."\">\n";
1446 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1449 if (ereg('Y', $display) || (empty($display))) {
1450 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1453 if (ereg('M', $display) || (empty($display))) {
1454 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1457 if (ereg("W", $display) || (empty($display))) {
1458 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1461 if (ereg("D", $display) || (empty($display))) {
1462 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1465 if (ereg("h", $display) || (empty($display))) {
1466 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1469 if (ereg('m', $display) || (empty($display))) {
1470 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1473 if (ereg("s", $display) || (empty($display))) {
1474 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1480 if (ereg('Y', $display) || (empty($display))) {
1481 // Generate year selection
1482 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1483 for ($idx = 0; $idx <= 10; $idx++) {
1484 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1485 if ($idx == $Y) $OUT .= ' selected="selected"';
1486 $OUT .= ">" . $idx."</option>\n";
1488 $OUT .= " </select></td>\n";
1490 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1493 if (ereg('M', $display) || (empty($display))) {
1494 // Generate month selection
1495 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1496 for ($idx = 0; $idx <= 11; $idx++)
1498 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1499 if ($idx == $M) $OUT .= ' selected="selected"';
1500 $OUT .= ">" . $idx."</option>\n";
1502 $OUT .= " </select></td>\n";
1504 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1507 if (ereg("W", $display) || (empty($display))) {
1508 // Generate week selection
1509 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1510 for ($idx = 0; $idx <= 4; $idx++) {
1511 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1512 if ($idx == $W) $OUT .= ' selected="selected"';
1513 $OUT .= ">" . $idx."</option>\n";
1515 $OUT .= " </select></td>\n";
1517 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1520 if (ereg("D", $display) || (empty($display))) {
1521 // Generate day selection
1522 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1523 for ($idx = 0; $idx <= 31; $idx++) {
1524 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1525 if ($idx == $D) $OUT .= ' selected="selected"';
1526 $OUT .= ">" . $idx."</option>\n";
1528 $OUT .= " </select></td>\n";
1530 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1533 if (ereg("h", $display) || (empty($display))) {
1534 // Generate hour selection
1535 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1536 for ($idx = 0; $idx <= 23; $idx++) {
1537 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1538 if ($idx == $h) $OUT .= ' selected="selected"';
1539 $OUT .= ">" . $idx."</option>\n";
1541 $OUT .= " </select></td>\n";
1543 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1546 if (ereg('m', $display) || (empty($display))) {
1547 // Generate minute selection
1548 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1549 for ($idx = 0; $idx <= 59; $idx++) {
1550 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1551 if ($idx == $m) $OUT .= ' selected="selected"';
1552 $OUT .= ">" . $idx."</option>\n";
1554 $OUT .= " </select></td>\n";
1556 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1559 if (ereg("s", $display) || (empty($display))) {
1560 // Generate second selection
1561 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1562 for ($idx = 0; $idx <= 59; $idx++) {
1563 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1564 if ($idx == $s) $OUT .= ' selected="selected"';
1565 $OUT .= ">" . $idx."</option>\n";
1567 $OUT .= " </select></td>\n";
1569 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1572 $OUT .= "</table>\n";
1574 // Return generated HTML code
1580 function createTimestampFromSelections ($prefix, $postData) {
1581 // Initial return value
1584 // Do we have a leap year?
1586 $TEST = date('Y', time()) / 4;
1587 $M1 = date('m', time());
1588 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1589 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1590 // First add years...
1591 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1593 $ret += $postData[$prefix."_mo"] * 2628000;
1595 $ret += $postData[$prefix."_we"] * 604800;
1597 $ret += $postData[$prefix."_da"] * 86400;
1599 $ret += $postData[$prefix."_ho"] * 3600;
1601 $ret += $postData[$prefix."_mi"] * 60;
1602 // And at last seconds...
1603 $ret += $postData[$prefix."_se"];
1604 // Return calculated value
1608 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1609 function createFancyTime ($stamp) {
1610 // Get data array with years/months/weeks/days/...
1611 $data = createTimeSelections($stamp, '', '', '', true);
1613 foreach($data as $k => $v) {
1615 // Value is greater than 0 "eval" data to return string
1616 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1621 // Do we have something there?
1622 if (strlen($ret) > 0) {
1623 // Remove leading commata and space
1624 $ret = substr($ret, 2);
1627 $ret = "0 {--_SECONDS--}";
1630 // Return fancy time string
1634 // Generates a navigation row for listing emails
1635 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1636 $SEP = ''; $TOP = '';
1637 if ($show_form === false) {
1639 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1643 for ($page = 1; $page <= $PAGES; $page++) {
1644 // Is the page currently selected or shall we generate a link to it?
1645 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
1646 // Is currently selected, so only highlight it
1647 $NAV .= '<strong>-';
1649 // Open anchor tag and add base URL
1650 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1652 // Add userid when we shall show all mails from a single member
1653 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1655 // Close open anchor tag
1659 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
1660 // Is currently selected, so only highlight it
1661 $NAV .= '-</strong>';
1667 // Add seperator if we have not yet reached total pages
1668 if ($page < $PAGES) $NAV .= ' | ';
1671 // Define constants only once
1672 $content['nav'] = $NAV;
1673 $content['span'] = $colspan;
1674 $content['top'] = $TOP;
1675 $content['sep'] = $SEP;
1677 // Load navigation template
1678 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1680 if ($return === true) {
1681 // Return generated HTML-Code
1689 // Extract host from script name
1690 function extractHostnameFromUrl (&$script) {
1691 // Use default SERVER_URL by default... ;) So?
1692 $url = getConfig('SERVER_URL');
1694 // Is this URL valid?
1695 if (substr($script, 0, 7) == 'http://') {
1696 // Use the hostname from script URL as new hostname
1697 $url = substr($script, 7);
1698 $extract = explode('/', $url);
1700 // Done extracting the URL :)
1703 // Extract host name
1704 $host = str_replace('http://', '', $url);
1705 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1707 // Generate relative URL
1708 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1709 if (substr(strtolower($script), 0, 7) == 'http://') {
1710 // But only if http:// is in front!
1711 $script = substr($script, (strlen($url) + 7));
1712 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1714 $script = substr($script, (strlen($url) + 8));
1717 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1718 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1724 // Send a GET request
1725 function sendGetRequest ($script) {
1726 // Extract host name from script
1727 $host = extractHostnameFromUrl($script);
1729 // Generate GET request header
1730 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1731 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1732 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1733 if (isConfigEntrySet('FULL_VERSION')) {
1734 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1736 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1738 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1739 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1740 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1742 // Send the raw request
1743 $response = sendRawRequest($host, $request);
1745 // Return the result to the caller function
1749 // Send a POST request
1750 function sendPostRequest ($script, $postData) {
1751 // Is postData an array?
1752 if (!is_array($postData)) {
1754 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1755 return array('', '', '');
1758 // Compile the script name
1759 $script = compileCode($script);
1761 // Extract host name from script
1762 $host = extractHostnameFromUrl($script);
1764 // Construct request
1765 $data = http_build_query($postData, '','&');
1767 // Generate POST request header
1768 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1769 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1770 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1771 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1772 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1773 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1774 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1775 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1778 // Send the raw request
1779 $response = sendRawRequest($host, $request);
1781 // Return the result to the caller function
1785 // Sends a raw request to another host
1786 function sendRawRequest ($host, $request) {
1787 // Init errno and errdesc with 'all fine' values
1788 $errno = 0; $errdesc = '';
1791 $response = array('', '', '');
1793 // Default is not to use proxy
1796 // Are proxy settins set?
1797 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1803 //* DEBUG: */ die("SCRIPT=" . $script."<br />");
1804 if ($useProxy === true) {
1805 // Connect to host through proxy connection
1806 $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1808 // Connect to host directly
1809 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1813 if (!is_resource($fp)) {
1819 if ($useProxy === true) {
1820 // Generate CONNECT request header
1821 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1822 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1824 // Use login data to proxy? (username at least!)
1825 if (getConfig('proxy_username') != '') {
1827 $encodedAuth = base64_encode(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
1828 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1831 // Add last new-line
1832 $proxyTunnel .= getConfig('HTTP_EOL');
1833 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1836 fputs($fp, $proxyTunnel);
1840 // No response received
1844 // Read the first line
1845 $resp = trim(fgets($fp, 10240));
1846 $respArray = explode(' ', $resp);
1847 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1848 // Invalid response!
1854 fputs($fp, $request);
1857 while (!feof($fp)) {
1858 $response[] = trim(fgets($fp, 1024));
1864 // Skip first empty lines
1866 foreach ($resp as $idx => $line) {
1868 $line = trim($line);
1870 // Is this line empty?
1873 array_shift($response);
1875 // Abort on first non-empty line
1880 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1882 // Proxy agent found?
1883 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1884 // Proxy header detected, so remove two lines
1885 array_shift($response);
1886 array_shift($response);
1889 // Was the request successfull?
1890 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1891 // Not found / access forbidden
1892 $response = array('', '', '');
1899 // Taken from www.php.net eregi() user comments
1900 function isEmailValid ($email) {
1902 $email = compileCode($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'))) && (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 $salt = substr($salt, 0, getConfig('salt_length'));
2043 //* DEBUG: */ outputHtml("GIVEN={$salt}<br />");
2047 return $salt.sha1($salt . $plainText);
2050 // Scramble a string
2051 function scrambleString($str) {
2055 // Final check, in case of failture it will return unscrambled string
2056 if (strlen($str) > 40) {
2057 // The string is to long
2059 } elseif (strlen($str) == 40) {
2061 $scrambleNums = explode(':', getConfig('pass_scramble'));
2063 // Generate new numbers
2064 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2067 // Scramble string here
2068 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2069 for ($idx = 0; $idx < strlen($str); $idx++) {
2070 // Get char on scrambled position
2071 $char = substr($str, $scrambleNums[$idx], 1);
2073 // Add it to final output string
2074 $scrambled .= $char;
2077 // Return scrambled string
2078 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2082 // De-scramble a string scrambled by scrambleString()
2083 function descrambleString($str) {
2084 // Scramble only 40 chars long strings
2085 if (strlen($str) != 40) return $str;
2087 // Load numbers from config
2088 $scrambleNums = explode(':', getConfig('pass_scramble'));
2091 if (count($scrambleNums) != 40) return $str;
2093 // Begin descrambling
2094 $orig = str_repeat(' ', 40);
2095 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2096 for ($idx = 0; $idx < 40; $idx++) {
2097 $char = substr($str, $idx, 1);
2098 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2101 // Return scrambled string
2102 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2106 // Generated a "string" for scrambling
2107 function genScrambleString ($len) {
2108 // Prepare array for the numbers
2109 $scrambleNumbers = array();
2111 // First we need to setup randomized numbers from 0 to 31
2112 for ($idx = 0; $idx < $len; $idx++) {
2114 $rand = mt_rand(0, ($len -1));
2116 // Check for it by creating more numbers
2117 while (array_key_exists($rand, $scrambleNumbers)) {
2118 $rand = mt_rand(0, ($len -1));
2122 $scrambleNumbers[$rand] = $rand;
2125 // So let's create the string for storing it in database
2126 $scrambleString = implode(':', $scrambleNumbers);
2127 return $scrambleString;
2130 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2131 function generatePassString ($passHash) {
2132 // Return vanilla password hash
2135 // Is a secret key and master salt already initialized?
2136 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2137 // Only calculate when the secret key is generated
2138 $newHash = ''; $start = 9;
2139 for ($idx = 0; $idx < 10; $idx++) {
2140 $part1 = hexdec(substr($passHash, $start, 4));
2141 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2142 $mod = dechex($idx);
2143 if ($part1 > $part2) {
2144 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2145 } elseif ($part2 > $part1) {
2146 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2148 $mod = substr(round($mod), 0, 4);
2149 $mod = str_repeat('0', 4-strlen($mod)) . $mod;
2150 //* DEBUG: */ outputHtml("*" . $start.'=' . $mod."*<br />");
2155 //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
2156 $ret = generateHash($newHash, getConfig('master_salt'));
2157 //* DEBUG: */ print($ret."<br />");
2160 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2161 $ret = md5($passHash);
2162 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2169 // Fix "deleted" cookies
2170 function fixDeletedCookies ($cookies) {
2171 // Is this an array with entries?
2172 if ((is_array($cookies)) && (count($cookies) > 0)) {
2173 // Then check all cookies if they are marked as deleted!
2174 foreach ($cookies as $cookieName) {
2175 // Is the cookie set to "deleted"?
2176 if (getSession($cookieName) == 'deleted') {
2177 setSession($cookieName, '');
2183 // Output error messages in a fasioned way and die...
2184 function app_die ($F, $L, $message) {
2185 // Check if Script is already dieing and not let it kill itself another 1000 times
2186 if (!isset($GLOBALS['app_died'])) {
2187 // Make sure, that the script realy realy diese here and now
2188 $GLOBALS['app_died'] = true;
2191 loadIncludeOnce('inc/header.php');
2193 // Rewrite message for output
2194 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2196 // Better log this message away
2197 logDebugMessage($F, $L, $message);
2199 // Load the message template
2200 loadTemplate('admin_settings_saved', false, $message);
2203 loadIncludeOnce('inc/footer.php');
2205 // Script tried to kill itself twice
2206 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2210 // Display parsing time and number of SQL queries in footer
2211 function displayParsingTime() {
2212 // Is the timer started?
2213 if (!isset($GLOBALS['startTime'])) {
2219 $endTime = microtime(true);
2221 // "Explode" both times
2222 $start = explode(' ', $GLOBALS['startTime']);
2223 $end = explode(' ', $endTime);
2224 $runTime = $end[0] - $start[0];
2225 if ($runTime < 0) $runTime = 0;
2229 'runtime' => translateComma($runTime),
2230 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2233 // Load the template
2234 loadTemplate('show_timings', false, $content);
2237 // Check wether a boolean constant is set
2238 // Taken from user comments in PHP documentation for function constant()
2239 function isBooleanConstantAndTrue ($constName) { // : Boolean
2240 // Failed by default
2244 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2246 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2247 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2250 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2251 if (defined($constName)) {
2253 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2254 $res = (constant($constName) === true);
2258 $GLOBALS['cache_array']['const'][$constName] = $res;
2260 //* DEBUG: */ var_dump($res);
2266 // Checks if a given apache module is loaded
2267 function isApacheModuleLoaded ($apacheModule) {
2268 // Check it and return result
2269 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2272 // Get current theme name
2273 function getCurrentTheme () {
2274 // The default theme is 'default'... ;-)
2277 // Load default theme if not empty from configuration
2278 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2280 if (!isSessionVariableSet('mxchange_theme')) {
2281 // Set default theme
2283 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2284 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2285 // Get theme from cookie
2286 $ret = getSession('mxchange_theme');
2289 if (getThemeId($ret) == 0) {
2290 // Fix it to default
2293 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2294 // Prepare FQFN for checking
2295 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2297 // Installation mode active
2298 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2299 // Set cookie from URL data
2300 setTheme(getRequestElement('theme'));
2301 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2302 // Set cookie from posted data
2303 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2307 $ret = getSession('mxchange_theme');
2309 // Invalid design, reset cookie
2313 // Return theme value
2317 // Setter for theme in session
2318 function setTheme ($newTheme) {
2319 setSession('mxchange_theme', $newTheme);
2322 // Get id from theme
2323 // @TODO Try to move this to inc/libs/theme_functions.php
2324 function getThemeId ($name) {
2325 // Is the extension 'theme' installed?
2326 if (!isExtensionActive('theme')) {
2334 // Is the cache entry there?
2335 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2336 // Get the version from cache
2337 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2340 incrementStatsEntry('cache_hits');
2341 } elseif (getExtensionVersion('cache') != '0.1.8') {
2342 // Check if current theme is already imported or not
2343 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2344 array($name), __FUNCTION__, __LINE__);
2347 if (SQL_NUMROWS($result) == 1) {
2349 list($id) = SQL_FETCHROW($result);
2353 SQL_FREERESULT($result);
2360 // Generates an error code from given account status
2361 function generateErrorCodeFromUserStatus ($status) {
2362 // @TODO The status should never be empty
2363 if (empty($status)) {
2364 // Something really bad happend here
2365 debug_report_bug(__FUNCTION__ . ': status is empty.');
2368 // Default error code if unknown account status
2369 $errorCode = getCode('UNKNOWN_STATUS');
2371 // Generate constant name
2372 $constantName = sprintf("ID_%s", $status);
2374 // Is the constant there?
2375 if (isCodeSet($constantName)) {
2377 $errorCode = getCode($constantName);
2380 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2383 // Return error code
2387 // Function to search for the last modifified file
2388 function searchDirsRecursive ($dir, &$last_changed) {
2390 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />");
2391 // Does it match what we are looking for? (We skip a lot files already!)
2392 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2393 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2394 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2395 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />");
2397 // Walk through all entries
2398 foreach ($ds as $d) {
2399 // Generate proper FQFN
2400 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2402 // Is it a file and readable?
2403 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2404 if (isDirectory($FQFN)) {
2405 // $FQFN is a directory so also crawl into this directory
2407 if (!empty($dir)) $newDir = $dir . '/'. $d;
2408 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />");
2409 searchDirsRecursive($newDir, $last_changed);
2410 } elseif (isFileReadable($FQFN)) {
2411 // $FQFN is a filename and no directory
2412 $time = filemtime($FQFN);
2413 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2414 if ($last_changed['time'] < $time) {
2415 // This file is newer as the file before
2416 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2417 $last_changed['path_name'] = $FQFN;
2418 $last_changed['time'] = $time;
2424 // "Getter" for revision/version data
2425 function getActualVersion ($type = 'Revision') {
2426 // By default nothing is new... ;-)
2429 // Is the cache entry there?
2430 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2431 // Found so increase cache hit
2432 incrementStatsEntry('cache_hits');
2435 return $GLOBALS['cache_array']['revision'][$type][0];
2437 // FQFN of revision file
2438 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2440 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2441 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2442 // Forced rebuild of .revision file
2445 // Check for revision file
2446 if (!isFileReadable($FQFN)) {
2447 // Not found, so we need to create it
2450 // Revision file found
2451 $ins_vers = explode("\n", readFromFile($FQFN));
2453 // Get array for mapping information
2454 $mapper = array_flip(getSearchFor());
2455 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2457 // Is the content valid?
2458 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2459 // File needs update!
2462 // Generate fake cache entry
2463 foreach ($mapper as $map=>$idx) {
2464 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2467 // Return found value
2468 return trim($ins_vers[$mapper[$type]]);
2473 // Has it been updated?
2474 if ($new === true) {
2476 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2478 // ... and call recursive
2479 return getActualVersion($type);
2484 // Repares an array we are looking for
2485 // 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
2486 function getSearchFor () {
2487 // Add Revision, Date, Tag and Author
2488 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2490 // Return the created array
2494 // @TODO Please describe this function
2495 function getArrayFromActualVersion () {
2499 // Directory to start with search
2500 $last_changed = array(
2505 // Init return array
2506 $akt_vers = array();
2508 // Init value for counting the founded keywords
2511 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2512 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2515 $last_file = readFromFile($last_changed['path_name']);
2517 // Get all the keywords to search for
2518 $searchFor = getSearchFor();
2520 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2521 foreach ($searchFor as $search) {
2522 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2523 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2524 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2525 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2528 // Save the last-changed filename for debugging
2529 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2531 // at least 3 keyword-Tags are needed for propper values
2532 if ($res && $res >= 3
2533 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2534 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2535 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2536 // Prepare content witch need special treadment
2538 // Prepare timestamp for date
2539 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2540 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2542 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2543 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2544 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2548 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2549 $version = sendGetRequest('check-updates3.php');
2552 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2553 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2554 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2555 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2556 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2557 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2560 // Return prepared array
2561 return $GLOBALS['cache_array']['revision'];
2564 // Back-ported from the new ship-simu engine. :-)
2565 function debug_get_printable_backtrace () {
2567 $backtrace = "<ol>\n";
2569 // Get and prepare backtrace for output
2570 $backtraceArray = debug_backtrace();
2571 foreach ($backtraceArray as $key => $trace) {
2572 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2573 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2574 if (!isset($trace['args'])) $trace['args'] = array();
2575 $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";
2579 $backtrace .= "</ol>\n";
2581 // Return the backtrace
2585 // Output a debug backtrace to the user
2586 function debug_report_bug ($message = '') {
2590 // Is the optional message set?
2591 if (!empty($message)) {
2593 $debug = sprintf("Note: %s<br />\n",
2597 // @TODO Add a little more infos here
2598 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2602 $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>";
2603 $debug .= debug_get_printable_backtrace();
2604 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2605 $debug .= "Thank you for finding bugs.";
2608 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2612 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2613 function generateSeed () {
2614 list($usec, $sec) = explode(' ', microtime());
2615 $microTime = (((float)$sec + (float)$usec)) * 100000;
2619 // Converts a message code to a human-readable message
2620 function getMessageFromErrorCode ($code) {
2624 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2625 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2626 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2627 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2628 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2629 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2630 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2631 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2632 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2633 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2634 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2635 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2636 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2637 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2638 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2639 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2640 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2641 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2642 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2643 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2644 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), '0'); break;
2645 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2646 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2647 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2648 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2649 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2650 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2651 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2653 case getCode('ERROR_MAILID'):
2654 if (isExtensionActive('mailid', true)) {
2655 $message = getMessage('ERROR_CONFIRMING_MAIL');
2657 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2661 case getCode('EXTENSION_PROBLEM'):
2662 if (isGetRequestElementSet('ext')) {
2663 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2665 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2669 case getCode('URL_TLOCK'):
2670 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2671 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2673 // Load timestamp from last order
2674 list($timestamp) = SQL_FETCHROW($result);
2675 $timestamp = generateDateTime($timestamp, '1');
2678 SQL_FREERESULT($result);
2680 // Calculate hours...
2681 $STD = round(getConfig('url_tlock') / 60 / 60);
2684 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2687 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2689 // Finally contruct the message
2690 // @TODO Rewrite this old lost code to a template
2691 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2692 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2693 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2697 // Missing/invalid code
2698 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2701 logDebugMessage(__FUNCTION__, __LINE__, $message);
2705 // Return the message
2709 // Generate a "link" for the given admin id (admin_id)
2710 function generateAdminLink ($adminId) {
2711 // No assigned admin is default
2712 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2714 // Zero? = Not assigned
2715 if (bigintval($adminId) > 0) {
2716 // Load admin's login
2717 $login = getAdminLogin($adminId);
2719 // Is the login valid?
2720 if ($login != '***') {
2721 // Is the extension there?
2722 if (isExtensionActive('admins')) {
2724 $admin = "<a href=\"".generateEmailLink(getAdminEmail($adminId), 'admins')."\">" . $login."</a>";
2726 // Extension not found
2727 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2731 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $adminId)."</div>";
2739 // Compile characters which are allowed in URLs
2740 function compileUriCode ($code, $simple = true) {
2741 // Compile constants
2742 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2744 // Compile QUOT and other non-HTML codes
2745 $code = str_replace('{DOT}', '.',
2746 str_replace('{SLASH}', '/',
2747 str_replace('{QUOT}', "'",
2748 str_replace('{DOLLAR}', '$',
2749 str_replace('{OPEN_ANCHOR}', '(',
2750 str_replace('{CLOSE_ANCHOR}', ')',
2751 str_replace('{OPEN_SQR}', '[',
2752 str_replace('{CLOSE_SQR}', ']',
2753 str_replace('{PER}', '%',
2757 // Return compiled code
2761 // Function taken from user comments on www.php.net / function eregi()
2762 function isUrlValidSimple ($url) {
2764 $url = secureString(str_replace("\\", '', compileCode(urldecode($url))));
2766 // Allows http and https
2767 $http = "(http|https)+(:\/\/)";
2769 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2770 // Test double-domains (e.g. .de.vu)
2771 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2773 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2775 $dir = "((/)+([-_\.[:alnum:]])+)*";
2777 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2778 // ... and the string after and including question character
2779 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2780 // Pattern for URLs like http://url/dir/doc.html?var=value
2781 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2782 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2783 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2784 // Pattern for URLs like http://url/dir/?var=value
2785 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2786 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2787 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2788 // Pattern for URLs like http://url/dir/page.ext
2789 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2790 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2791 $pattern['ipdp'] = $http . $ip . $dir . $page;
2792 // Pattern for URLs like http://url/dir
2793 $pattern['d1d'] = $http . $domain1 . $dir;
2794 $pattern['d2d'] = $http . $domain2 . $dir;
2795 $pattern['ipd'] = $http . $ip . $dir;
2796 // Pattern for URLs like http://url/?var=value
2797 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2798 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2799 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2800 // Pattern for URLs like http://url?var=value
2801 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2802 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2803 $pattern['ipg12'] = $http . $ip . $getstring1;
2804 // Test all patterns
2806 foreach ($pattern as $key => $pat) {
2808 if (isDebugRegExpressionEnabled()) {
2809 // @TODO Are these convertions still required?
2810 $pat = str_replace('.', "\.", $pat);
2811 $pat = str_replace('@', "\@", $pat);
2812 //* DEBUG: */ outputHtml($key."= " . $pat . "<br />");
2815 // Check if expression matches
2816 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2819 if ($reg === true) break;
2822 // Return true/false
2826 // Wtites data to a config.php-style file
2827 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2828 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2829 // Initialize some variables
2835 // Is the file there and read-/write-able?
2836 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2837 $search = 'CFG: ' . $comment;
2838 $tmp = $FQFN . '.tmp';
2840 // Open the source file
2841 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2843 // Is the resource valid?
2844 if (is_resource($fp)) {
2845 // Open temporary file
2846 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2848 // Is the resource again valid?
2849 if (is_resource($fp_tmp)) {
2850 // Mark temporary file as readable
2851 $GLOBALS['file_readable'][$tmp] = true;
2854 while (!feof($fp)) {
2855 // Read from source file
2856 $line = fgets ($fp, 1024);
2858 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2861 if ($next === $seek) {
2863 $line = $prefix . $DATA . $suffix . "\n";
2869 // Write to temp file
2870 fputs($fp_tmp, $line);
2876 // Finished writing tmp file
2880 // Close source file
2883 if (($done === true) && ($found === true)) {
2884 // Copy back tmp file and delete tmp :-)
2885 copyFileVerified($tmp, $FQFN, 0644);
2886 return removeFile($tmp);
2887 } elseif ($found === false) {
2888 outputHtml('<strong>CHANGE:</strong> 404!');
2890 outputHtml('<strong>TMP:</strong> UNDONE!');
2894 // File not found, not readable or writeable
2895 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2898 // An error was detected!
2901 // Send notification to admin
2902 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2903 if (getExtensionVersion('admins') >= '0.4.1') {
2905 sendAdminsEmails($subject, $templateName, $content, $userid);
2907 // Send out out-dated way
2908 $message = loadEmailTemplate($templateName, $content, $userid);
2909 sendAdminEmails($subject, $message);
2913 // Debug message logger
2914 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2915 // Is debug mode enabled?
2916 if ((isDebugModeEnabled()) || ($force === true)) {
2918 $message = str_replace("\r", '', str_replace("\n", '', $message));
2920 // Log this message away, we better don't call app_die() here to prevent an endless loop
2921 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2922 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2927 // Handle extra values
2928 function handleExtraValues ($filterFunction, $value, $extraValue) {
2929 // Default is the value itself
2932 // Do we have a special filter function?
2933 if (!empty($filterFunction)) {
2934 // Does the filter function exist?
2935 if (function_exists($filterFunction)) {
2936 // Do we have extra parameters here?
2937 if (!empty($extraValue)) {
2938 // Put both parameters in one new array by default
2939 $args = array($value, $extraValue);
2941 // If we have an array simply use it and pre-extend it with our value
2942 if (is_array($extraValue)) {
2943 // Make the new args array
2944 $args = merge_array(array($value), $extraValue);
2947 // Call the multi-parameter call-back
2948 $ret = call_user_func_array($filterFunction, $args);
2950 // One parameter call
2951 $ret = call_user_func($filterFunction, $value);
2960 // Converts timestamp selections into a timestamp
2961 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2962 // Init test variable
2965 // Get last three chars
2966 $test = substr($id, -3);
2968 // Improved way of checking! :-)
2969 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2970 // Found a multi-selection for timings?
2971 $test = substr($id, 0, -3);
2972 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)) {
2973 // Generate timestamp
2974 $postData[$test] = createTimestampFromSelections($test, $postData);
2975 $DATA[] = sprintf("%s='%s'", $test, $postData[$test]);
2977 // Remove data from array
2978 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2979 unset($postData[$test.'_' . $rem]);
2983 unset($id); $skip = true; $test2 = $test;
2986 // Process this entry
2992 // Reverts the german decimal comma into Computer decimal dot
2993 function convertCommaToDot ($str) {
2994 // Default float is not a float... ;-)
2997 // Which language is selected?
2998 switch (getLanguage()) {
2999 case 'de': // German language
3000 // Remove german thousand dots first
3001 $str = str_replace('.', '', $str);
3003 // Replace german commata with decimal dot and cast it
3004 $float = (float)str_replace(',', '.', $str);
3007 default: // US and so on
3008 // Remove thousand dots first and cast
3009 $float = (float)str_replace(',', '', $str);
3017 // Handle menu-depending failed logins and return the rendered content
3018 function handleLoginFailtures ($accessLevel) {
3019 // Default output is empty ;-)
3022 // Is the session data set?
3023 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3024 // Ignore zero values
3025 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3026 // Non-guest has login failures found, get both data and prepare it for template
3027 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3029 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3030 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), '2')
3034 $OUT = loadTemplate('login_failures', true, $content);
3037 // Reset session data
3038 setSession('mxchange_' . $accessLevel.'_failures', '');
3039 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3042 // Return rendered content
3047 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3049 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3051 // Shall I remove the cache file?
3052 if (isCacheInstanceValid()) {
3054 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3056 $GLOBALS['cache_instance']->removeCacheFile(false, $force);
3059 // Include file given?
3062 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3064 // Is the include there?
3065 if (isIncludeReadable($inc)) {
3066 // And rebuild it from scratch
3067 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3070 // Include not found!
3071 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3077 // Determines the real remote address
3078 function determineRealRemoteAddress () {
3079 // Is a proxy in use?
3080 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3082 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3083 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3084 // Yet, another proxy
3085 $address = $_SERVER['HTTP_CLIENT_IP'];
3087 // The regular address when no proxy was used
3088 $address = $_SERVER['REMOTE_ADDR'];
3091 // This strips out the real address from proxy output
3092 if (strstr($address, ',')) {
3093 $addressArray = explode(',', $address);
3094 $address = $addressArray[0];
3097 // Return the result
3101 // Adds a bonus mail to the queue
3102 // This is a high-level function!
3103 function addNewBonusMail ($data, $mode = '', $output=true) {
3104 // Use mode from data if not set and availble ;-)
3105 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3107 // Generate receiver list
3108 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3111 if (!empty($RECEIVER)) {
3112 // Add bonus mail to queue
3113 addBonusMailToQueue(
3125 // Mail inserted into bonus pool
3126 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3127 } elseif ($output) {
3128 // More entered than can be reached!
3129 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3132 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3136 // Determines referal id and sets it
3137 function determineReferalId () {
3138 // Skip this in non-html-mode
3139 if (getOutputMode() != '0') return false;
3141 // Check if refid is set
3142 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3144 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3145 // The variable user comes from the click-counter script click.php and we only accept this here
3146 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3147 } elseif (isPostRequestElementSet('refid')) {
3148 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3149 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3150 } elseif (isGetRequestElementSet('refid')) {
3151 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3152 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3153 } elseif (isGetRequestElementSet('ref')) {
3154 // Set refid=ref (the referal link uses such variable)
3155 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3156 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3157 // Set session refid als global
3158 $GLOBALS['refid'] = bigintval(getSession('refid'));
3159 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3160 // Select a random user which has confirmed enougth mails
3161 $GLOBALS['refid'] = determineRandomReferalId();
3162 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3163 // Set default refid as refid in URL
3164 $GLOBALS['refid'] = getConfig('def_refid');
3166 // No default ID when sql_patches is not installed or none set
3167 $GLOBALS['refid'] = 0;
3170 // Set cookie when default refid > 0
3171 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3173 setSession('refid', $GLOBALS['refid']);
3176 // Return determined refid
3177 return $GLOBALS['refid'];
3180 // Enables the reset mode and runs it
3181 function doReset () {
3182 // Enable the reset mode
3183 $GLOBALS['reset_enabled'] = true;
3186 runFilterChain('reset');
3189 // Our shutdown-function
3190 function shutdown () {
3191 // Call the filter chain 'shutdown'
3192 runFilterChain('shutdown', null);
3194 if (SQL_IS_LINK_UP()) {
3196 SQL_CLOSE(__FILE__, __LINE__);
3197 } elseif (!isInstallationPhase()) {
3199 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3202 // Stop executing here
3206 // Setter for userid
3207 function setUserId ($userid) {
3208 $GLOBALS['userid'] = bigintval($userid);
3211 // Getter for userid or returns zero
3212 function getUserId () {
3216 // Is the userid set?
3217 if (isUserIdSet()) {
3219 $userid = $GLOBALS['userid'];
3226 // Checks ether the userid is set
3227 function isUserIdSet () {
3228 return (isset($GLOBALS['userid']));
3231 // Handle message codes from URL
3232 function handleCodeMessage () {
3233 if (isGetRequestElementSet('code')) {
3234 // Default extension is 'unknown'
3237 // Is extension given?
3238 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3240 // Convert the 'code' parameter from URL to a human-readable message
3241 $message = getMessageFromErrorCode(getRequestElement('code'));
3243 // Load message template
3244 loadTemplate('message', false, $message);
3248 // Setter for extra title
3249 function setExtraTitle ($extraTitle) {
3250 $GLOBALS['extra_title'] = $extraTitle;
3253 // Getter for extra title
3254 function getExtraTitle () {
3255 // Is the extra title set?
3256 if (!isExtraTitleSet()) {
3257 // No, then abort here
3258 debug_report_bug('extra_title is not set!');
3262 return $GLOBALS['extra_title'];
3265 // Checks if the extra title is set
3266 function isExtraTitleSet () {
3267 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3270 // Generates a 'extension foo inactive' message
3271 function generateExtensionInactiveMessage ($ext_name) {
3272 // Is the extension empty?
3273 if (empty($ext_name)) {
3274 // This should not happen
3275 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3279 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3281 // Is an admin logged in?
3283 // Then output admin message
3284 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3287 // Return prepared message
3291 // Generates a 'extension foo not installed' message
3292 function generateExtensionNotInstalledMessage ($ext_name) {
3293 // Is the extension empty?
3294 if (empty($ext_name)) {
3295 // This should not happen
3296 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3300 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3302 // Is an admin logged in?
3304 // Then output admin message
3305 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3308 // Return prepared message
3312 // Generates a message depending on if the extension is not installed or not
3314 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3318 // Is the extension not installed or just deactivated?
3319 switch (isExtensionInstalled($ext_name)) {
3320 case true; // Deactivated!
3321 $message = generateExtensionInactiveMessage($ext_name);
3324 case false; // Not installed!
3325 $message = generateExtensionNotInstalledMessage($ext_name);
3328 default: // Should not happen!
3329 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3330 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3334 // Return the message
3338 // Reads a directory recursively by default and searches for files not matching
3339 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3340 // a whole directory.
3341 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3342 // Add default entries we should exclude
3343 $excludeArray[] = '.';
3344 $excludeArray[] = '..';
3345 $excludeArray[] = '.svn';
3346 $excludeArray[] = '.htaccess';
3348 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3353 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3356 while ($baseFile = readdir($dirPointer)) {
3357 // Exclude '.', '..' and entries in $excludeArray automatically
3358 if (in_array($baseFile, $excludeArray, true)) {
3360 //* DEBUG: */ outputHtml('excluded=' . $baseFile . "<br />");
3364 // Construct include filename and FQFN
3365 $fileName = $baseDir . $baseFile;
3366 $FQFN = getConfig('PATH') . $fileName;
3368 // Remove double slashes
3369 $FQFN = str_replace('//', '/', $FQFN);
3371 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3372 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3373 // These Lines are only for debugging!!
3374 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . "<br />");
3375 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . "<br />");
3376 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . "<br />");
3382 // Skip also files with non-matching prefix genericly
3383 if (($recursive === true) && (isDirectory($FQFN))) {
3384 // Is a redirectory so read it as well
3385 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3387 // And skip further processing
3389 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3391 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3393 } elseif (!isFileReadable($FQFN)) {
3394 // Not readable so skip it
3395 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3399 // Is the file a PHP script or other?
3400 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3401 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3402 // Is this a valid include file?
3403 if ($extension == '.php') {
3404 // Remove both for extension name
3405 $extName = substr($baseFile, strlen($prefix), -4);
3407 // Is the extension valid and active?
3408 if (isExtensionNameValid($extName)) {
3409 // Then add this file
3410 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3411 $files[] = $fileName;
3413 // Add non-extension files as well
3414 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3415 if ($addBaseDir === true) {
3416 $files[] = $fileName;
3418 $files[] = $baseFile;
3422 // We found .php file but should not search for them, why?
3423 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3425 } elseif (substr($baseFile, -4, 4) == $extension) {
3426 // Other, generic file found
3427 $files[] = $fileName;
3432 closedir($dirPointer);
3437 // Return array with include files
3438 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3442 // Maps a module name into a database table name
3443 function mapModuleToTable ($moduleName) {
3444 // Map only these, still lame code...
3445 switch ($moduleName) {
3446 // 'index' is the guest's menu
3447 case 'index': $moduleName = 'guest'; break;
3448 // ... and 'login' the member's menu
3449 case 'login': $moduleName = 'member'; break;
3450 // Anything else will not be mapped, silently.
3457 // Add SQL debug data to array for later output
3458 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3459 // Don't execute anything here if we don't need
3460 if (getConfig('display_debug_sqls') != 'Y') return;
3464 'num_rows' => SQL_NUMROWS($result),
3465 'affected' => SQL_AFFECTEDROWS(),
3466 'sql_str' => $sqlString,
3467 'timing' => $timing,
3468 'file' => basename($F),
3473 $GLOBALS['debug_sqls'][] = $record;
3476 // Initializes the cache instance
3477 function initCacheInstance () {
3478 // Load include for CacheSystem class
3479 loadIncludeOnce('inc/classes/cachesystem.class.php');
3481 // Initialize cache system only when it's needed
3482 $GLOBALS['cache_instance'] = new CacheSystem();
3483 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3484 // Failed to initialize cache sustem
3485 addFatalMessage(__FILE__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_CANNOT_INITIALIZE'));
3489 // Getter for message from array or raw message
3490 function getMessageFromIndexedArray ($message, $pos, $array) {
3491 // Check if the requested message was found in array
3492 if (isset($array[$pos])) {
3493 // ... if yes then use it!
3494 $ret = $array[$pos];
3496 // ... else use default message
3504 // Handles fatal errors
3505 function handleFatalErrors () {
3506 // Do we have errors to handle and right output mode?
3507 if ((getTotalFatalErrors() == 0) || (getOutputMode() != 0)) {
3508 // Abort executing here
3513 loadIncludeOnce('inc/load_config.php');
3515 // Set unset variable
3516 if (empty($check)) $check = '';
3521 // Installation phase or regular mode?
3522 if ((isInstallationPhase())) {
3523 // While we are installing ouput other header than while it is installed... :-)
3525 foreach (getFatalArray() as $key => $value) {
3526 // Prepare content for the template
3528 'key' => ($key + 1),
3532 // Load row template
3533 $OUT .= loadTemplate('install_fatal_row', true, $content);
3536 // Load main template
3537 $content = loadTemplate('install_fatal_table', true, $OUT);
3538 } elseif (isInstalled()) {
3539 // Display all runtime fatal errors
3541 foreach (getFatalArray() as $key => $value) {
3542 // Prepare content for the template
3544 'key' => ($key + 1),
3548 // Load row template
3549 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
3552 // Load main template
3553 $content = loadTemplate('runtime_fatal_table', true, $OUT);
3556 // Message to regular users (non-admin)
3557 $CORR = getMessage('FATAL_REPORT_ERRORS');
3559 // PHP warnings fixed
3560 if ($check == 'done') {
3561 if (isAdmin()) $CORR = getMessage('FATAL_CORRECT_ERRORS');
3564 // Remember all in array
3570 // Load main template
3571 loadTemplate('fatal_errors', false, $content);
3573 // Delete all to prevent double-display
3574 initFatalMessages();
3577 loadIncludeOnce('inc/footer.php');
3583 //////////////////////////////////////////////////
3584 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3585 //////////////////////////////////////////////////
3587 if (!function_exists('html_entity_decode')) {
3588 // Taken from documentation on www.php.net
3589 function html_entity_decode ($string) {
3590 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3591 $trans_tbl = array_flip($trans_tbl);
3592 return strtr($string, $trans_tbl);