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']);
125 // Compile and run finished rendered HTML code
126 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
127 // Prepare the content and eval() it...
132 $eval = "\$newContent = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";";
135 // Was that eval okay?
136 if (empty($newContent)) {
137 // Something went wrong!
138 debug_report_bug('Evaluation error:<pre>' . htmlentities($eval) . '</pre>');
140 $GLOBALS['output'] = $newContent;
146 // Output code here, DO NOT REMOVE! ;-)
147 outputRawCode($GLOBALS['output']);
148 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
149 // Rewrite links when rewrite extension is active
150 if ((isExtensionActive('rewrite')) && (getOutputMode() != '1')) {
151 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
154 // Compile and run finished rendered HTML code
155 while (strpos($GLOBALS['output'], '{!') > 0) {
156 eval("\$GLOBALS['output'] = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";");
159 // Output code here, DO NOT REMOVE! ;-)
160 outputRawCode($GLOBALS['output']);
164 // Output the raw HTML code
165 function outputRawCode ($htmlCode) {
166 // Output stripped HTML code to avoid broken JavaScript code, etc.
167 print(stripslashes(stripslashes($htmlCode)));
169 // Flush the output if only getPhpCaching() is not 'on'
170 if (getPhpCaching() != 'on') {
176 // Init fatal message array
177 function initFatalMessages () {
178 $GLOBALS['fatal_messages'] = array();
181 // Getter for whole fatal error messages
182 function getFatalArray () {
183 return $GLOBALS['fatal_messages'];
186 // Add a fatal error message to the queue array
187 function addFatalMessage ($F, $L, $message, $extra='') {
188 if (is_array($extra)) {
189 // Multiple extras for a message with masks
190 $message = call_user_func_array('sprintf', $extra);
191 } elseif (!empty($extra)) {
192 // $message is text with a mask plus extras to insert into the text
193 $message = sprintf($message, $extra);
196 // Add message to $GLOBALS['fatal_messages']
197 $GLOBALS['fatal_messages'][] = $message;
199 // Log fatal messages away
200 debug_report_bug($message);
201 logDebugMessage($F, $L, " message={$message}");
204 // Getter for total fatal message count
205 function getTotalFatalErrors () {
209 // Do we have at least the first entry?
210 if (!empty($GLOBALS['fatal_messages'][0])) {
212 $count = count($GLOBALS['fatal_messages']);
219 // Load a template file and return it's content (only it's name; do not use ' or ")
220 function loadTemplate ($template, $return=false, $content=array()) {
221 // @TODO Remove this sanity-check if all is fine
222 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
224 // @TODO Try to rewrite all $DATA to $content
228 if (!isset($GLOBALS['template_eval'][$template])) {
229 // Add more variables which you want to use in your template files
230 $username = getUsername();
232 // Make all template names lowercase
233 $template = strtolower($template);
235 // Count the template load
236 incrementConfigEntry('num_templates');
240 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
242 // Generate date/time string
243 $date_time = generateDateTime(time(), '1');
245 // Is content an array
246 if (is_array($content)) $content['date_time'] = $date_time;
248 // @DEPRECATED Try to rewrite the if() condition
249 if ($template == 'member_support_form') {
250 // Support request of a member
251 $result = SQL_QUERY_ESC("SELECT `userid`, `gender`, `surname`, `family`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
252 array(getUserId()), __FUNCTION__, __LINE__);
254 // Is content an array?
255 if (is_array($content)) {
257 $content = merge_array($content, SQL_FETCHARRAY($result));
260 $content['gender'] = translateGender($content['gender']);
263 // @TODO Find all templates which are using these direct variables and rewrite them.
264 // @TODO After this step is done, this else-block is history
265 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
268 $gender = translateGender($gender);
269 logDebugMessage(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
273 SQL_FREERESULT($result);
277 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
280 // Check for admin/guest/member templates
281 if (substr($template, 0, 6) == 'admin_') {
282 // Admin template found
284 } elseif (substr($template, 0, 6) == 'guest_') {
285 // Guest template found
287 } elseif (substr($template, 0, 7) == 'member_') {
288 // Member template found
290 } elseif (substr($template, 0, 8) == 'install_') {
291 // Installation template found
293 } elseif (substr($template, 0, 4) == 'ext_') {
294 // Extension template found
296 } elseif (substr($template, 0, 3) == 'la_') {
297 // 'Logical-area' template found
299 } elseif (substr($template, 0, 3) == 'js_') {
300 // JavaScript template found
302 } elseif (substr($template, 0, 5) == 'menu_') {
303 // Menu template found
306 // Test for extension
307 $test = substr($template, 0, strpos($template, '_'));
309 // Probe for valid extension name
310 if (isExtensionNameValid($test)) {
311 // Set extra path to extension's name
316 ////////////////////////
317 // Generate file name //
318 ////////////////////////
319 $FQFN = $basePath . $mode . $template . '.tpl';
321 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
322 // Select what depended header/footer template file for admin/guest/member area
323 $file2 = sprintf("%s%s%s_%s.tpl",
331 if (isFileReadable($file2)) $FQFN = $file2;
333 // Remove variable from memory
337 // Does the special template exists?
338 if (!isFileReadable($FQFN)) {
339 // Reset to default template
340 $FQFN = $basePath . $template . '.tpl';
343 // Now does the final template exists?
344 if (isFileReadable($FQFN)) {
345 // The local file does exists so we load it. :)
346 $GLOBALS['tpl_content'] = readFromFile($FQFN);
348 // Replace ' to our own chars to preventing them being quoted
349 while (strpos($GLOBALS['tpl_content'], "'") !== false) { $GLOBALS['tpl_content'] = str_replace("'", '{QUOT}', $GLOBALS['tpl_content']); }
351 // Do we have to compile the code?
353 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
354 // Normal HTML output?
355 if ($GLOBALS['output_mode'] == 0) {
356 // Add surrounding HTML comments to help finding bugs faster
357 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
359 // Prepare eval() command
360 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
362 // Prepare eval() command
363 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
366 // Add surrounding HTML comments to help finding bugs faster
367 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
368 $eval = '$ret = "' . smartAddSlashes($ret) . '";';
371 // Cache the eval() command here
372 $GLOBALS['template_eval'][$template] = $eval;
375 eval($GLOBALS['template_eval'][$template]);
378 $GLOBALS['template_eval'][$template] = '404';
380 } elseif (((isAdmin()) || ((isInstalling()) && (!isInstalled()))) && ($GLOBALS['template_eval'][$template] == '404')) {
381 // Only admins shall see this warning or when installation mode is active
382 $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
383 (' . $template . ')<br />
385 {--TEMPLATE_CONTENT--}
386 <pre>' . print_r($content, true) . '</pre>
388 <pre>' . print_r($DATA, true) . '</pre>
392 eval($GLOBALS['template_eval'][$template]);
395 // Do we have some content to output or return?
397 // Not empty so let's put it out! ;)
398 if ($return === true) {
399 // Return the HTML code
405 } elseif (isDebugModeEnabled()) {
406 // Warning, empty output!
407 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
411 // Loads an email template and compiles it
412 function loadEmailTemplate ($template, $content = array(), $UID = '0') {
415 // Our configuration is kept non-global here
416 $_CONFIG = getConfigArray();
418 // Make sure all template names are lowercase!
419 $template = strtolower($template);
421 // Default 'nickname' if extension is not installed
424 // Prepare IP number and User Agent
425 $REMOTE_ADDR = detectRemoteAddr();
426 $HTTP_USER_AGENT = detectUserAgent();
429 $ADMIN = getConfig('MAIN_TITLE');
431 // Is the admin logged in?
434 $adminId = getCurrentAdminId();
437 $ADMIN = getAdminEmail($adminId);
440 // Neutral email address is default
441 $email = getConfig('WEBMASTER');
443 // Expiration in a nice output format
444 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
445 if (getConfig('auto_purge') == 0) {
446 // Will never expire!
447 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
449 // Create nice date string
450 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
453 // Is content an array?
454 if (is_array($content)) {
455 // Add expiration to array, $EXPIRATION is now deprecated!
456 $content['expiration'] = $EXPIRATION;
460 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />");
461 if (($UID > 0) && (is_array($content))) {
462 // If nickname extension is installed, fetch nickname as well
463 if (isExtensionActive('nickname')) {
464 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
466 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email`, `nickname` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
467 array(bigintval($UID)), __FUNCTION__, __LINE__);
469 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
471 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
472 array(bigintval($UID)), __FUNCTION__, __LINE__);
475 // Fetch and merge data
476 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
477 $content = merge_array($content, SQL_FETCHARRAY($result));
478 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
481 SQL_FREERESULT($result);
484 // Translate M to male or F to female if present
485 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
487 // Overwrite email from data if present
488 if (isset($content['email'])) $email = $content['email'];
490 // Store email for some functions in global data array
491 $DATA['email'] = $email;
494 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
496 // Check for admin/guest/member templates
497 if (substr($template, 0, 6) == 'admin_') {
498 // Admin template found
499 $FQFN = $basePath.'admin/' . $template.'.tpl';
500 } elseif (substr($template, 0, 6) == 'guest_') {
501 // Guest template found
502 $FQFN = $basePath.'guest/' . $template.'.tpl';
503 } elseif (substr($template, 0, 7) == 'member_') {
504 // Member template found
505 $FQFN = $basePath.'member/' . $template.'.tpl';
507 // Test for extension
508 $test = substr($template, 0, strpos($template, '_'));
509 if (isExtensionNameValid($test)) {
510 // Set extra path to extension's name
511 $FQFN = $basePath . $test.'/' . $template.'.tpl';
513 // No special filename
514 $FQFN = $basePath . $template.'.tpl';
518 // Does the special template exists?
519 if (!isFileReadable($FQFN)) {
520 // Reset to default template
521 $FQFN = $basePath . $template.'.tpl';
524 // Now does the final template exists?
526 if (isFileReadable($FQFN)) {
527 // The local file does exists so we load it. :)
528 $GLOBALS['tpl_content'] = readFromFile($FQFN);
529 $GLOBALS['tpl_content'] = SQL_ESCAPE($GLOBALS['tpl_content']);
532 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode($GLOBALS['tpl_content'])."\");";
533 eval($GLOBALS['tpl_content']);
534 } elseif (!empty($template)) {
535 // Template file not found!
536 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
537 {--TEMPLATE_CONTENT--}
538 <pre>".print_r($content, true)."</pre>
540 <pre>".print_r($DATA, true)."</pre>
543 // Debug mode not active? Then remove the HTML tags
544 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
546 // No template name supplied!
547 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
550 // Is there some content?
551 if (empty($newContent)) {
553 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
554 // Add last error if the required function exists
555 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
558 // Remove content and data
562 // Return compiled content
563 return compileCode($newContent);
566 // Send mail out to an email address
567 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
568 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
570 // Compile subject line (for POINTS constant etc.)
571 eval("\$subject = decodeEntities(\"".compileCode(smartAddSlashes($subject))."\");");
574 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
575 // Value detected, is the message extension installed?
576 // @TODO Extension 'msg' does not exist
577 if (isExtensionActive('msg')) {
578 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
581 // Load email address
582 $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
583 array(bigintval($toEmail)), __FUNCTION__, __LINE__);
584 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />");
586 // Does the user exist?
587 if (SQL_NUMROWS($result_email)) {
588 // Load email address
589 list($toEmail) = SQL_FETCHROW($result_email);
592 $toEmail = getConfig('WEBMASTER');
596 SQL_FREERESULT($result_email);
598 } elseif ($toEmail == '0') {
600 $toEmail = getConfig('WEBMASTER');
602 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
604 // Check for PHPMailer or debug-mode
605 if (!checkPhpMailerUsage()) {
606 // Not in PHPMailer-Mode
607 if (empty($mailHeader)) {
608 // Load email header template
609 $mailHeader = loadEmailTemplate('header');
612 $mailHeader .= loadEmailTemplate('header');
614 } elseif (isDebugModeEnabled()) {
615 if (empty($mailHeader)) {
616 // Load email header template
617 $mailHeader = loadEmailTemplate('header');
620 $mailHeader .= loadEmailTemplate('header');
625 eval("\$toEmail = \"".compileCode(smartAddSlashes($toEmail))."\";");
628 eval("\$message = \"".compileCode(smartAddSlashes($message))."\";");
630 // Fix HTML parameter (default is no!)
631 if (empty($isHtml)) $isHtml = 'N';
632 if (isDebugModeEnabled()) {
633 // In debug mode we want to display the mail instead of sending it away so we can debug this part
635 ".htmlentities(trim($mailHeader))."
637 Subject : " . $subject."
638 Message : " . $message."
640 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
641 // Send mail as HTML away
642 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
643 } elseif (!empty($toEmail)) {
645 sendRawEmail($toEmail, $subject, $message, $mailHeader);
646 } elseif ($isHtml != 'Y') {
648 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
652 // Check if legacy or PHPMailer command
653 // @TODO Rewrite this to an extension 'smtp'
655 function checkPhpMailerUsage() {
656 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
659 // Send out a raw email with PHPMailer class or legacy mail() command
660 function sendRawEmail ($toEmail, $subject, $message, $from) {
661 // Shall we use PHPMailer class or legacy mode?
662 if (checkPhpMailerUsage()) {
663 // Use PHPMailer class with SMTP enabled
664 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
665 loadIncludeOnce('inc/phpmailer/class.smtp.php');
668 $mail = new PHPMailer();
669 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
672 $mail->SMTPAuth = true;
673 $mail->Host = getConfig('SMTP_HOSTNAME');
675 $mail->Username = getConfig('SMTP_USER');
676 $mail->Password = getConfig('SMTP_PASSWORD');
678 $mail->From = getConfig('WEBMASTER');
682 $mail->FromName = getConfig('MAIN_TITLE');
683 $mail->Subject = $subject;
684 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
685 $mail->Body = $message;
686 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
687 $mail->WordWrap = 70;
690 $mail->Body = decodeEntities($message);
692 $mail->AddAddress($toEmail, '');
693 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
694 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
695 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
698 // Use legacy mail() command
699 mail($toEmail, $subject, decodeEntities($message), $from);
703 // Generate a password in a specified length or use default password length
704 function generatePassword ($length = 0) {
705 // Auto-fix invalid length of zero
706 if ($length == 0) $length = getConfig('pass_len');
708 // Initialize array with all allowed chars
709 $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,-,+,_,/,.');
711 // Start creating password
713 for ($i = 0; $i < $length; $i++) {
714 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
717 // When the size is below 40 we can also add additional security by scrambling
718 // it. Otherwise we may corrupt hashes
719 if (strlen($PASS) <= 40) {
720 // Also scramble the password
721 $PASS = scrambleString($PASS);
724 // Return the password
728 // Generates a human-readable timestamp from the Uni* stamp
729 function generateDateTime ($time, $mode = '0') {
730 // Filter out numbers
731 $time = bigintval($time);
733 // If the stamp is zero it mostly didn't "happen"
736 return getMessage('NEVER_HAPPENED');
739 switch (getLanguage()) {
740 case 'de': // German date / time format
742 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
743 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
744 case '2': $ret = date('d.m.Y|H:i', $time); break;
745 case '3': $ret = date('d.m.Y', $time); break;
747 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
752 default: // Default is the US date / time format!
754 case '0': $ret = date('r', $time); break;
755 case '1': $ret = date('Y-m-d - g:i A', $time); break;
756 case '2': $ret = date('y-m-d|H:i', $time); break;
757 case '3': $ret = date('y-m-d', $time); break;
759 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
768 // Translates Y/N to yes/no
769 function translateYesNo ($yn) {
771 $translated = '??? (' . $yn . ')';
773 case 'Y': $translated = getMessage('YES'); break;
774 case 'N': $translated = getMessage('NO'); break;
777 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
785 // Translates the "pool type" into human-readable
786 function translatePoolType ($type) {
787 // Default?type is unknown
788 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
791 $constName = sprintf("POOL_TYPE_%s", $type);
794 if (isMessageIdValid($constName)) {
796 $translated = getMessage($constName);
799 // Return "translation"
803 // Translates the american decimal dot into a german comma
804 function translateComma ($dotted, $cut = true, $max = 0) {
805 // Default is 3 you can change this in admin area "Misc -> Misc Options"
806 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
808 // Use from config is default
809 $maxComma = getConfig('max_comma');
811 // Use from parameter?
812 if ($max > 0) $maxComma = $max;
815 if (($cut === true) && ($max == 0)) {
816 // Test for commata if in cut-mode
817 $com = explode('.', $dotted);
818 if (count($com) < 2) {
819 // Don't display commatas even if there are none... ;-)
825 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
828 switch (getLanguage()) {
829 case 'de': // German language
830 $dotted = number_format($dotted, $maxComma, ',', '.');
833 default: // All others
834 $dotted = number_format($dotted, $maxComma, '.', ',');
838 // Return translated value
842 // Translate Uni*-like gender to human-readable
843 function translateGender ($gender) {
845 $ret = '!' . $gender . '!';
847 // Male/female or company?
849 case 'M': $ret = getMessage('GENDER_M'); break;
850 case 'F': $ret = getMessage('GENDER_F'); break;
851 case 'C': $ret = getMessage('GENDER_C'); break;
853 // Log unknown gender
854 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
858 // Return translated gender
862 // "Translates" the user status
863 function translateUserStatus ($status) {
864 // Generate message depending on status
869 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
874 $ret = getMessage('ACCOUNT_DELETED');
878 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
879 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
887 // Generates an URL for the dereferer
888 function generateDerefererUrl ($URL) {
889 // Don't de-refer our own links!
890 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
891 // De-refer this link
892 $URL = 'modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
899 // Generates an URL for the frametester
900 function generateFrametesterUrl ($URL) {
901 // Prepare frametester URL
902 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
903 encodeString(compileUriCode($URL))
906 // Return the new URL
907 return $frametesterUrl;
910 // Count entries from e.g. a selection box
911 function countSelection ($array) {
913 if (!is_array($array)) {
915 debug_report_bug(__FUNCTION__.': No array provided.');
922 foreach ($array as $key => $selected) {
924 if (!empty($selected)) $ret++;
927 // Return counted selections
931 // Generate XHTML code for the CAPTCHA
932 function generateCaptchaCode ($code, $type, $DATA, $userid) {
933 return '<IMG border="0" alt="Code" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
936 // Generates a timestamp (some wrapper for mktime())
937 function makeTime ($H, $M, $S, $stamp) {
938 // Extract day, month and year from given timestamp
939 $day = date('d', $stamp);
940 $month = date('m', $stamp);
941 $year = date('Y', $stamp);
943 // Create timestamp for wished time which depends on extracted date
944 return mktime($H, $M, $S, $month, $day, $year);
947 // Redirects to an URL and if neccessarry extends it with own base URL
948 function redirectToUrl ($URL) {
949 // Compile out URI codes
950 $URL = compileUriCode($URL);
952 // Check if http(s):// is there
953 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
954 // Make all URLs full-qualified
955 $URL = getConfig('URL') . '/' . $URL;
958 // Three different debug ways...
959 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
960 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $URL);
961 //* DEBUG: */ die($URL);
963 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
964 $rel = ' rel="external"';
966 // Do we have internal or external URL?
967 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
968 // Own (=internal) URL
973 $GLOBALS['output'] = ob_get_contents();
975 // Clear it only if there is content
976 if (!empty($GLOBALS['output'])) {
980 // Simple probe for bots/spiders from search engines
981 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
982 // Secure the URL against bad things such als HTML insertions and so on...
983 $URL = secureString($URL);
985 // Output new location link as anchor
986 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
987 } elseif (!headers_sent()) {
988 // Load URL when headers are not sent
989 //* DEBUG: */ debug_report_bug("URL={$URL}");
990 sendHeader('Location: '.str_replace('&', '&', $URL));
992 // Output error message
993 loadInclude('inc/header.php');
994 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
995 loadInclude('inc/footer.php');
998 // Shut the mailer down here
1002 // Wrapper for redirectToUrl but URL comes from a configuration entry
1003 function redirectToConfiguredUrl ($configEntry) {
1005 $URL = getConfig($configEntry);
1008 if (is_null($URL)) {
1010 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1014 redirectToUrl($URL);
1017 // Compiles the given HTML/mail code
1018 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1019 // Is the code a string?
1020 if (!is_string($code)) {
1021 // Silently return it
1025 // Init replacement-array with full security characters
1026 $secChars = $GLOBALS['security_chars'];
1028 // Select smaller set of chars to replace when we e.g. want to compile URLs
1029 if ($full === false) $secChars = $GLOBALS['url_chars'];
1031 // Compile more through a filter
1032 $code = runFilterChain('compile_code', $code);
1034 // Compile constants
1035 if ($constants === true) {
1036 // BEFORE 0.2.1 : Language and data constants
1037 // WITH 0.2.1+ : Only language constants
1038 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1040 // BEFORE 0.2.1 : Not used
1041 // WITH 0.2.1+ : Data constants
1042 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1045 // Compile QUOT and other non-HTML codes
1046 foreach ($secChars['to'] as $k => $to) {
1047 // Do the reversed thing as in inc/libs/security_functions.php
1048 $code = str_replace($to, $secChars['from'][$k], $code);
1051 // But shall I keep simple quotes for later use?
1052 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1054 // Find $content[bla][blub] entries
1055 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1057 // Are some matches found?
1058 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1059 // Replace all matches
1060 $matchesFound = array();
1061 foreach ($matches[0] as $key => $match) {
1062 // Fuzzy look has failed by default
1063 $fuzzyFound = false;
1065 // Fuzzy look on match if already found
1066 foreach ($matchesFound as $found => $set) {
1068 $test = substr($found, 0, strlen($match));
1070 // Does this entry exist?
1071 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1072 if ($test == $match) {
1074 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1081 if ($fuzzyFound === true) continue;
1083 // Take all string elements
1084 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1085 // Replace it in the code
1086 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1087 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1088 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1089 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1090 $matchesFound[$match] = 1;
1091 } elseif (!isset($matchesFound[$match])) {
1092 // Not yet replaced!
1093 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1094 $code = str_replace($match, "\"." . $match.".\"", $code);
1095 $matchesFound[$match] = 1;
1100 // Return compiled code
1104 /************************************************************************
1106 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1107 * $a_sort sortiert: *
1109 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1110 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1111 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1112 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1113 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1115 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1116 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1117 * Sie, dass es doch nicht so schwer ist! :-) *
1119 ************************************************************************/
1120 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1122 while ($primary_key < count($a_sort)) {
1123 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1124 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1126 if ($nums === false) {
1127 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1128 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1129 } elseif ($key != $key2) {
1130 // Sort numbers (E.g.: 9 < 10)
1131 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1132 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1136 // We have found two different values, so let's sort whole array
1137 foreach ($dummy as $sort_key => $sort_val) {
1138 $t = $dummy[$sort_key][$key];
1139 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1140 $dummy[$sort_key][$key2] = $t;
1151 // Write back sorted array
1156 function addSelectionBox ($type, $default, $prefix = '', $id = '0') {
1159 if ($type == 'yn') {
1160 // This is a yes/no selection only!
1161 if ($id > 0) $prefix .= "[" . $id."]";
1162 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1164 // Begin with regular selection box here
1165 if (!empty($prefix)) $prefix .= "_";
1167 if ($id > 0) $type2 .= "[" . $id."]";
1168 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1173 for ($idx = 1; $idx < 32; $idx++) {
1174 $OUT .= "<option value=\"" . $idx."\"";
1175 if ($default == $idx) $OUT .= ' selected="selected"';
1176 $OUT .= ">" . $idx."</option>\n";
1180 case 'month': // Month
1181 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1182 $OUT .= "<option value=\"" . $month."\"";
1183 if ($default == $month) $OUT .= ' selected="selected"';
1184 $OUT .= ">" . $descr."</option>\n";
1188 case 'year': // Year
1190 $year = date('Y', time());
1192 // Use configured min age or fixed?
1193 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1195 $startYear = $year - getConfig('min_age');
1198 $startYear = $year - 16;
1201 // Calculate earliest year (100 years old people can still enter Internet???)
1202 $minYear = $year - 100;
1204 // Check if the default value is larger than minimum and bigger than actual year
1205 if (($default > $minYear) && ($default >= $year)) {
1206 for ($idx = $year; $idx < ($year + 11); $idx++) {
1207 $OUT .= "<option value=\"" . $idx."\"";
1208 if ($default == $idx) $OUT .= ' selected="selected"';
1209 $OUT .= ">" . $idx."</option>\n";
1211 } elseif ($default == -1) {
1212 // Current year minus 1
1213 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1215 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1218 // Get current year and subtract the configured minimum age
1219 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1220 // Calculate earliest year depending on extension version
1221 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1222 // Use configured minimum age
1223 $year = date('Y', time()) - getConfig('min_age');
1225 // Use fixed 16 years age
1226 $year = date('Y', time()) - 16;
1229 // Construct year selection list
1230 for ($idx = $minYear; $idx <= $year; $idx++) {
1231 $OUT .= "<option value=\"" . $idx."\"";
1232 if ($default == $idx) $OUT .= ' selected="selected"';
1233 $OUT .= ">" . $idx."</option>\n";
1240 for ($idx = 0; $idx < 60; $idx+=5) {
1241 if (strlen($idx) == 1) $idx = '0' . $idx;
1242 $OUT .= "<option value=\"" . $idx."\"";
1243 if ($default == $idx) $OUT .= ' selected="selected"';
1244 $OUT .= ">" . $idx."</option>\n";
1249 for ($idx = 0; $idx < 24; $idx++) {
1250 if (strlen($idx) == 1) $idx = '0' . $idx;
1251 $OUT .= "<option value=\"" . $idx."\"";
1252 if ($default == $idx) $OUT .= ' selected="selected"';
1253 $OUT .= ">" . $idx."</option>\n";
1258 $OUT .= "<option value=\"Y\"";
1259 if ($default == 'Y') $OUT .= ' selected="selected"';
1260 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1261 if ($default != 'Y') $OUT .= ' selected="selected"';
1262 $OUT .= ">{--NO--}</option>\n";
1265 $OUT .= " </select>\n";
1270 // Deprecated : $length
1273 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1274 // Build server string
1275 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1278 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1279 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1280 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1281 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1282 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1284 // Build string from misc data
1285 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1287 // Add more additional data
1288 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1290 // Add referal id, language, theme and userid
1291 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1292 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1293 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1294 $data .= getConfig('ENCRYPT_SEPERATOR') . getUserId();
1296 // Calculate number for generating the code
1297 $a = $code + getConfig('_ADD') - 1;
1299 if (isConfigEntrySet('master_hash')) {
1300 // Generate hash with master salt from modula of number with the prime number and other data
1301 $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'));
1303 // Create number from hash
1304 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1306 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1307 $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));
1309 // Create number from hash
1310 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1313 // At least 10 numbers shall be secure enought!
1314 $len = getConfig('code_length');
1315 if ($len == 0) $len = $length;
1316 if ($len == 0) $len = 10;
1318 // Cut off requested counts of number
1319 $return = substr(str_replace('.', '', $rcode), 0, $len);
1321 // Done building code
1325 // Does only allow numbers
1326 function bigintval ($num, $castValue = true) {
1327 // Filter all numbers out
1328 $ret = preg_replace('/[^0123456789]/', '', $num);
1331 if ($castValue) $ret = (double)$ret;
1333 // Has the whole value changed?
1334 // @TODO Remove this if() block if all is working fine
1335 if ('' . $ret . '' != '' . $num . '') {
1337 //debug_report_bug("{$ret}<>{$num}");
1344 // Insert the code in $img_code into jpeg or PNG image
1345 function generateImageOrCode ($img_code, $headerSent=true) {
1346 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1347 // Stop execution of function here because of over-sized code length
1349 } elseif ($headerSent === false) {
1350 // Return in an HTML code code
1351 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1355 $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
1356 if (isFileReadable($img)) {
1357 // Switch image type
1358 switch (getConfig('img_type'))
1361 // Okay, load image and hide all errors
1362 $image = imagecreatefromjpeg($img);
1366 // Okay, load image and hide all errors
1367 $image = imagecreatefrompng($img);
1371 // Exit function here
1372 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1376 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1377 $text_color = imagecolorallocate($image, 0, 0, 0);
1379 // Insert code into image
1380 imagestring($image, 5, 14, 2, $img_code, $text_color);
1382 // Return to browser
1383 sendHeader('Content-Type: image/' . getConfig('img_type'));
1385 // Output image with matching image factory
1386 switch (getConfig('img_type')) {
1387 case 'jpg': imagejpeg($image); break;
1388 case 'png': imagepng($image); break;
1391 // Remove image from memory
1392 imagedestroy($image);
1394 // Create selection box or array of splitted timestamp
1395 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1396 // Calculate 2-seconds timestamp
1397 $stamp = round($timestamp);
1398 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1400 // Do we have a leap year?
1402 $TEST = date('Y', time()) / 4;
1403 $M1 = date('m', time());
1404 $M2 = date('m', (time() + $timestamp));
1406 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1407 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1409 // First of all years...
1410 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1411 //* DEBUG: */ print("Y={$Y}<br />");
1413 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1414 //* DEBUG: */ print("M={$M}<br />");
1416 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1417 //* DEBUG: */ print("W={$W}<br />");
1419 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1420 //* DEBUG: */ print("D={$D}<br />");
1422 $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));
1423 //* DEBUG: */ print("h={$h}<br />");
1425 $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));
1426 //* DEBUG: */ print("m={$m}<br />");
1427 // And at last seconds...
1428 $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));
1429 //* DEBUG: */ print("s={$s}<br />");
1431 // Is seconds zero and time is < 60 seconds?
1432 if (($s == 0) && ($timestamp < 60)) {
1434 $s = round($timestamp);
1438 // Now we convert them in seconds...
1440 if ($return_array) {
1441 // Just put all data in an array for later use
1453 $OUT = "<div align=\"" . $align."\">\n";
1454 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1457 if (ereg('Y', $display) || (empty($display))) {
1458 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1461 if (ereg('M', $display) || (empty($display))) {
1462 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1465 if (ereg("W", $display) || (empty($display))) {
1466 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1469 if (ereg("D", $display) || (empty($display))) {
1470 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1473 if (ereg("h", $display) || (empty($display))) {
1474 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1477 if (ereg('m', $display) || (empty($display))) {
1478 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1481 if (ereg("s", $display) || (empty($display))) {
1482 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1488 if (ereg('Y', $display) || (empty($display))) {
1489 // Generate year selection
1490 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1491 for ($idx = 0; $idx <= 10; $idx++) {
1492 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1493 if ($idx == $Y) $OUT .= ' selected="selected"';
1494 $OUT .= ">" . $idx."</option>\n";
1496 $OUT .= " </select></td>\n";
1498 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1501 if (ereg('M', $display) || (empty($display))) {
1502 // Generate month selection
1503 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1504 for ($idx = 0; $idx <= 11; $idx++)
1506 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1507 if ($idx == $M) $OUT .= ' selected="selected"';
1508 $OUT .= ">" . $idx."</option>\n";
1510 $OUT .= " </select></td>\n";
1512 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1515 if (ereg("W", $display) || (empty($display))) {
1516 // Generate week selection
1517 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1518 for ($idx = 0; $idx <= 4; $idx++) {
1519 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1520 if ($idx == $W) $OUT .= ' selected="selected"';
1521 $OUT .= ">" . $idx."</option>\n";
1523 $OUT .= " </select></td>\n";
1525 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1528 if (ereg("D", $display) || (empty($display))) {
1529 // Generate day selection
1530 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1531 for ($idx = 0; $idx <= 31; $idx++) {
1532 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1533 if ($idx == $D) $OUT .= ' selected="selected"';
1534 $OUT .= ">" . $idx."</option>\n";
1536 $OUT .= " </select></td>\n";
1538 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1541 if (ereg("h", $display) || (empty($display))) {
1542 // Generate hour selection
1543 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1544 for ($idx = 0; $idx <= 23; $idx++) {
1545 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1546 if ($idx == $h) $OUT .= ' selected="selected"';
1547 $OUT .= ">" . $idx."</option>\n";
1549 $OUT .= " </select></td>\n";
1551 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1554 if (ereg('m', $display) || (empty($display))) {
1555 // Generate minute selection
1556 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1557 for ($idx = 0; $idx <= 59; $idx++) {
1558 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1559 if ($idx == $m) $OUT .= ' selected="selected"';
1560 $OUT .= ">" . $idx."</option>\n";
1562 $OUT .= " </select></td>\n";
1564 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1567 if (ereg("s", $display) || (empty($display))) {
1568 // Generate second selection
1569 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1570 for ($idx = 0; $idx <= 59; $idx++) {
1571 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1572 if ($idx == $s) $OUT .= ' selected="selected"';
1573 $OUT .= ">" . $idx."</option>\n";
1575 $OUT .= " </select></td>\n";
1577 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1580 $OUT .= "</table>\n";
1582 // Return generated HTML code
1588 function createTimestampFromSelections ($prefix, $postData) {
1589 // Initial return value
1592 // Do we have a leap year?
1594 $TEST = date('Y', time()) / 4;
1595 $M1 = date('m', time());
1596 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1597 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1598 // First add years...
1599 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1601 $ret += $postData[$prefix."_mo"] * 2628000;
1603 $ret += $postData[$prefix."_we"] * 604800;
1605 $ret += $postData[$prefix."_da"] * 86400;
1607 $ret += $postData[$prefix."_ho"] * 3600;
1609 $ret += $postData[$prefix."_mi"] * 60;
1610 // And at last seconds...
1611 $ret += $postData[$prefix."_se"];
1612 // Return calculated value
1616 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1617 function createFancyTime ($stamp) {
1618 // Get data array with years/months/weeks/days/...
1619 $data = createTimeSelections($stamp, '', '', '', true);
1621 foreach($data as $k => $v) {
1623 // Value is greater than 0 "eval" data to return string
1624 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1629 // Do we have something there?
1630 if (strlen($ret) > 0) {
1631 // Remove leading commata and space
1632 $ret = substr($ret, 2);
1635 $ret = "0 {--_SECONDS--}";
1638 // Return fancy time string
1642 // Generates a navigation row for listing emails
1643 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1644 $SEP = ''; $TOP = '';
1645 if ($show_form === false) {
1647 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1651 for ($page = 1; $page <= $PAGES; $page++) {
1652 // Is the page currently selected or shall we generate a link to it?
1653 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
1654 // Is currently selected, so only highlight it
1655 $NAV .= '<strong>-';
1657 // Open anchor tag and add base URL
1658 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1660 // Add userid when we shall show all mails from a single member
1661 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1663 // Close open anchor tag
1667 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
1668 // Is currently selected, so only highlight it
1669 $NAV .= '-</strong>';
1675 // Add seperator if we have not yet reached total pages
1676 if ($page < $PAGES) $NAV .= ' | ';
1679 // Define constants only once
1680 $content['nav'] = $NAV;
1681 $content['span'] = $colspan;
1682 $content['top'] = $TOP;
1683 $content['sep'] = $SEP;
1685 // Load navigation template
1686 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1688 if ($return === true) {
1689 // Return generated HTML-Code
1697 // Extract host from script name
1698 function extractHostnameFromUrl (&$script) {
1699 // Use default SERVER_URL by default... ;) So?
1700 $url = getConfig('SERVER_URL');
1702 // Is this URL valid?
1703 if (substr($script, 0, 7) == 'http://') {
1704 // Use the hostname from script URL as new hostname
1705 $url = substr($script, 7);
1706 $extract = explode('/', $url);
1708 // Done extracting the URL :)
1711 // Extract host name
1712 $host = str_replace('http://', '', $url);
1713 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1715 // Generate relative URL
1716 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1717 if (substr(strtolower($script), 0, 7) == 'http://') {
1718 // But only if http:// is in front!
1719 $script = substr($script, (strlen($url) + 7));
1720 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1722 $script = substr($script, (strlen($url) + 8));
1725 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1726 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1732 // Send a GET request
1733 function sendGetRequest ($script) {
1734 // Extract host name from script
1735 $host = extractHostnameFromUrl($script);
1737 // Generate GET request header
1738 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1739 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1740 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1741 if (isConfigEntrySet('FULL_VERSION')) {
1742 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1744 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1746 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1747 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1748 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1750 // Send the raw request
1751 $response = sendRawRequest($host, $request);
1753 // Return the result to the caller function
1757 // Send a POST request
1758 function sendPostRequest ($script, $postData) {
1759 // Is postData an array?
1760 if (!is_array($postData)) {
1762 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1763 return array('', '', '');
1766 // Compile the script name
1767 $script = compileCode($script);
1769 // Extract host name from script
1770 $host = extractHostnameFromUrl($script);
1772 // Construct request
1773 $data = http_build_query($postData, '','&');
1775 // Generate POST request header
1776 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1777 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1778 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1779 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1780 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1781 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1782 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1783 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1786 // Send the raw request
1787 $response = sendRawRequest($host, $request);
1789 // Return the result to the caller function
1793 // Sends a raw request to another host
1794 function sendRawRequest ($host, $request) {
1795 // Init errno and errdesc with 'all fine' values
1796 $errno = 0; $errdesc = '';
1799 $response = array('', '', '');
1801 // Default is not to use proxy
1804 // Are proxy settins set?
1805 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1811 //* DEBUG: */ die("SCRIPT=" . $script."<br />");
1812 if ($useProxy === true) {
1813 // Connect to host through proxy connection
1814 $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1816 // Connect to host directly
1817 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1821 if (!is_resource($fp)) {
1827 if ($useProxy === true) {
1828 // Generate CONNECT request header
1829 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1830 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1832 // Use login data to proxy? (username at least!)
1833 if (getConfig('proxy_username') != '') {
1835 $encodedAuth = base64_encode(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
1836 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1839 // Add last new-line
1840 $proxyTunnel .= getConfig('HTTP_EOL');
1841 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1844 fputs($fp, $proxyTunnel);
1848 // No response received
1852 // Read the first line
1853 $resp = trim(fgets($fp, 10240));
1854 $respArray = explode(' ', $resp);
1855 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1856 // Invalid response!
1862 fputs($fp, $request);
1865 while (!feof($fp)) {
1866 $response[] = trim(fgets($fp, 1024));
1872 // Skip first empty lines
1874 foreach ($resp as $idx => $line) {
1876 $line = trim($line);
1878 // Is this line empty?
1881 array_shift($response);
1883 // Abort on first non-empty line
1888 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1890 // Proxy agent found?
1891 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1892 // Proxy header detected, so remove two lines
1893 array_shift($response);
1894 array_shift($response);
1897 // Was the request successfull?
1898 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1899 // Not found / access forbidden
1900 $response = array('', '', '');
1907 // Taken from www.php.net eregi() user comments
1908 function isEmailValid ($email) {
1910 $email = compileCode($email);
1912 // Check first part of email address
1913 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1916 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1919 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1921 // Return check result
1922 return preg_match($regex, $email);
1925 // Function taken from user comments on www.php.net / function eregi()
1926 function isUrlValid ($URL, $compile=true) {
1927 // Trim URL a little
1928 $URL = trim(urldecode($URL));
1929 //* DEBUG: */ outputHtml($URL."<br />");
1931 // Compile some chars out...
1932 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1933 //* DEBUG: */ outputHtml($URL."<br />");
1935 // Check for the extension filter
1936 if (isExtensionActive('filter')) {
1937 // Use the extension's filter set
1938 return FILTER_VALIDATE_URL($URL, false);
1941 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1942 // https:// in front of the URLs
1943 return isUrlValidSimple($URL);
1946 // Generate a list of administrative links to a given userid
1947 function generateMemberAdminActionLinks ($userid, $status = '') {
1948 // Make sure userid is a number
1949 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1951 // Define all main targets
1952 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1954 // Begin of navigation links
1957 foreach ($targetArray as $tar) {
1958 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1959 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1960 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1961 // Locked accounts shall be unlocked
1962 $OUT .= 'UNLOCK_USER';
1964 // All other status is fine
1965 $OUT .= strtoupper($tar);
1967 $OUT .= "_TITLE--}\">{--ADMIN_";
1968 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1969 // Locked accounts shall be unlocked
1970 $OUT .= 'UNLOCK_USER';
1972 // All other status is fine
1973 $OUT .= strtoupper($tar);
1975 $OUT .= "--}</a></span> | ";
1978 // Finish navigation link
1979 $OUT = substr($OUT, 0, -7) . ']';
1985 // Generate an email link
1986 function generateEmailLink ($email, $table = 'admins') {
1987 // Default email link (INSECURE! Spammer can read this by harvester programs)
1988 $EMAIL = 'mailto:' . $email;
1990 // Check for several extensions
1991 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1992 // Create email link for contacting admin in guest area
1993 $EMAIL = generateAdminEmailLink($email);
1994 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
1995 // Create email link for contacting a member within admin area (or later in other areas, too?)
1996 $EMAIL = generateUserEmailLink($email, 'admin');
1997 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1998 // Create email link to contact sponsor within admin area (or like the link above?)
1999 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2002 // Shall I close the link when there is no admin?
2003 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2005 // Return email link
2009 // Generate a hash for extra-security for all passwords
2010 function generateHash ($plainText, $salt = '') {
2011 // Is the required extension 'sql_patches' there and a salt is not given?
2012 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches'))) && (empty($salt))) {
2013 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2014 return md5($plainText);
2017 // Do we miss an arry element here?
2018 if (!isConfigEntrySet('file_hash')) {
2020 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2023 // When the salt is empty build a new one, else use the first x configured characters as the salt
2025 // Build server string (inc/databases.php is no longer updated with every commit)
2026 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2029 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('secret_key') . getConfig('ENCRYPT_SEPERATOR') . getConfig('file_hash') . getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime')) . getConfig('ENCRYPT_SEPERATOR') . getConfig('master_salt');
2032 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2034 // Calculate number for generating the code
2035 $a = time() + getConfig('_ADD') - 1;
2037 // Generate SHA1 sum from modula of number and the prime number
2038 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2039 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2040 $sha1 = scrambleString($sha1);
2041 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2042 //* DEBUG: */ $sha1b = descrambleString($sha1);
2043 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2045 // Generate the password salt string
2046 $salt = substr($sha1, 0, getConfig('salt_length'));
2047 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2050 $salt = substr($salt, 0, getConfig('salt_length'));
2051 //* DEBUG: */ outputHtml("GIVEN={$salt}<br />");
2055 return $salt.sha1($salt . $plainText);
2058 // Scramble a string
2059 function scrambleString($str) {
2063 // Final check, in case of failture it will return unscrambled string
2064 if (strlen($str) > 40) {
2065 // The string is to long
2067 } elseif (strlen($str) == 40) {
2069 $scrambleNums = explode(':', getConfig('pass_scramble'));
2071 // Generate new numbers
2072 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2075 // Scramble string here
2076 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2077 for ($idx = 0; $idx < strlen($str); $idx++) {
2078 // Get char on scrambled position
2079 $char = substr($str, $scrambleNums[$idx], 1);
2081 // Add it to final output string
2082 $scrambled .= $char;
2085 // Return scrambled string
2086 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2090 // De-scramble a string scrambled by scrambleString()
2091 function descrambleString($str) {
2092 // Scramble only 40 chars long strings
2093 if (strlen($str) != 40) return $str;
2095 // Load numbers from config
2096 $scrambleNums = explode(':', getConfig('pass_scramble'));
2099 if (count($scrambleNums) != 40) return $str;
2101 // Begin descrambling
2102 $orig = str_repeat(' ', 40);
2103 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2104 for ($idx = 0; $idx < 40; $idx++) {
2105 $char = substr($str, $idx, 1);
2106 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2109 // Return scrambled string
2110 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2114 // Generated a "string" for scrambling
2115 function genScrambleString ($len) {
2116 // Prepare array for the numbers
2117 $scrambleNumbers = array();
2119 // First we need to setup randomized numbers from 0 to 31
2120 for ($idx = 0; $idx < $len; $idx++) {
2122 $rand = mt_rand(0, ($len -1));
2124 // Check for it by creating more numbers
2125 while (array_key_exists($rand, $scrambleNumbers)) {
2126 $rand = mt_rand(0, ($len -1));
2130 $scrambleNumbers[$rand] = $rand;
2133 // So let's create the string for storing it in database
2134 $scrambleString = implode(':', $scrambleNumbers);
2135 return $scrambleString;
2138 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2139 function generatePassString ($passHash) {
2140 // Return vanilla password hash
2143 // Is a secret key and master salt already initialized?
2144 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2145 // Only calculate when the secret key is generated
2146 $newHash = ''; $start = 9;
2147 for ($idx = 0; $idx < 10; $idx++) {
2148 $part1 = hexdec(substr($passHash, $start, 4));
2149 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2150 $mod = dechex($idx);
2151 if ($part1 > $part2) {
2152 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2153 } elseif ($part2 > $part1) {
2154 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2156 $mod = substr(round($mod), 0, 4);
2157 $mod = str_repeat('0', 4-strlen($mod)) . $mod;
2158 //* DEBUG: */ outputHtml("*" . $start.'=' . $mod."*<br />");
2163 //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
2164 $ret = generateHash($newHash, getConfig('master_salt'));
2165 //* DEBUG: */ print($ret."<br />");
2168 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2169 $ret = md5($passHash);
2170 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2177 // Fix "deleted" cookies
2178 function fixDeletedCookies ($cookies) {
2179 // Is this an array with entries?
2180 if ((is_array($cookies)) && (count($cookies) > 0)) {
2181 // Then check all cookies if they are marked as deleted!
2182 foreach ($cookies as $cookieName) {
2183 // Is the cookie set to "deleted"?
2184 if (getSession($cookieName) == 'deleted') {
2185 setSession($cookieName, '');
2191 // Output error messages in a fasioned way and die...
2192 function app_die ($F, $L, $message) {
2193 // Check if Script is already dieing and not let it kill itself another 1000 times
2194 if (!isset($GLOBALS['app_died'])) {
2195 // Make sure, that the script realy realy diese here and now
2196 $GLOBALS['app_died'] = true;
2199 loadIncludeOnce('inc/header.php');
2201 // Rewrite message for output
2202 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2204 // Better log this message away
2205 logDebugMessage($F, $L, $message);
2207 // Load the message template
2208 loadTemplate('admin_settings_saved', false, $message);
2211 loadIncludeOnce('inc/footer.php');
2213 // Script tried to kill itself twice
2214 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2218 // Display parsing time and number of SQL queries in footer
2219 function displayParsingTime() {
2220 // Is the timer started?
2221 if (!isset($GLOBALS['startTime'])) {
2227 $endTime = microtime(true);
2229 // "Explode" both times
2230 $start = explode(' ', $GLOBALS['startTime']);
2231 $end = explode(' ', $endTime);
2232 $runTime = $end[0] - $start[0];
2233 if ($runTime < 0) $runTime = 0;
2237 'runtime' => translateComma($runTime),
2238 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2241 // Load the template
2242 loadTemplate('show_timings', false, $content);
2245 // Check wether a boolean constant is set
2246 // Taken from user comments in PHP documentation for function constant()
2247 function isBooleanConstantAndTrue ($constName) { // : Boolean
2248 // Failed by default
2252 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2254 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2255 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2258 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2259 if (defined($constName)) {
2261 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2262 $res = (constant($constName) === true);
2266 $GLOBALS['cache_array']['const'][$constName] = $res;
2268 //* DEBUG: */ var_dump($res);
2274 // Checks if a given apache module is loaded
2275 function isApacheModuleLoaded ($apacheModule) {
2276 // Check it and return result
2277 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2280 // Get current theme name
2281 function getCurrentTheme () {
2282 // The default theme is 'default'... ;-)
2285 // Load default theme if not empty from configuration
2286 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2288 if (!isSessionVariableSet('mxchange_theme')) {
2289 // Set default theme
2291 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2292 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2293 // Get theme from cookie
2294 $ret = getSession('mxchange_theme');
2297 if (getThemeId($ret) == 0) {
2298 // Fix it to default
2301 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2302 // Prepare FQFN for checking
2303 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2305 // Installation mode active
2306 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2307 // Set cookie from URL data
2308 setTheme(getRequestElement('theme'));
2309 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2310 // Set cookie from posted data
2311 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2315 $ret = getSession('mxchange_theme');
2317 // Invalid design, reset cookie
2321 // Return theme value
2325 // Setter for theme in session
2326 function setTheme ($newTheme) {
2327 setSession('mxchange_theme', $newTheme);
2330 // Get id from theme
2331 // @TODO Try to move this to inc/libs/theme_functions.php
2332 function getThemeId ($name) {
2333 // Is the extension 'theme' installed?
2334 if (!isExtensionActive('theme')) {
2342 // Is the cache entry there?
2343 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2344 // Get the version from cache
2345 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2348 incrementStatsEntry('cache_hits');
2349 } elseif (getExtensionVersion('cache') != '0.1.8') {
2350 // Check if current theme is already imported or not
2351 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2352 array($name), __FUNCTION__, __LINE__);
2355 if (SQL_NUMROWS($result) == 1) {
2357 list($id) = SQL_FETCHROW($result);
2361 SQL_FREERESULT($result);
2368 // Generates an error code from given account status
2369 function generateErrorCodeFromUserStatus ($status) {
2370 // @TODO The status should never be empty
2371 if (empty($status)) {
2372 // Something really bad happend here
2373 debug_report_bug(__FUNCTION__ . ': status is empty.');
2376 // Default error code if unknown account status
2377 $errorCode = getCode('UNKNOWN_STATUS');
2379 // Generate constant name
2380 $constantName = sprintf("ID_%s", $status);
2382 // Is the constant there?
2383 if (isCodeSet($constantName)) {
2385 $errorCode = getCode($constantName);
2388 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2391 // Return error code
2395 // Function to search for the last modifified file
2396 function searchDirsRecursive ($dir, &$last_changed) {
2398 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />");
2399 // Does it match what we are looking for? (We skip a lot files already!)
2400 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2401 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2402 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2403 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />");
2405 // Walk through all entries
2406 foreach ($ds as $d) {
2407 // Generate proper FQFN
2408 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2410 // Is it a file and readable?
2411 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2412 if (isDirectory($FQFN)) {
2413 // $FQFN is a directory so also crawl into this directory
2415 if (!empty($dir)) $newDir = $dir . '/'. $d;
2416 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />");
2417 searchDirsRecursive($newDir, $last_changed);
2418 } elseif (isFileReadable($FQFN)) {
2419 // $FQFN is a filename and no directory
2420 $time = filemtime($FQFN);
2421 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2422 if ($last_changed['time'] < $time) {
2423 // This file is newer as the file before
2424 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2425 $last_changed['path_name'] = $FQFN;
2426 $last_changed['time'] = $time;
2432 // "Getter" for revision/version data
2433 function getActualVersion ($type = 'Revision') {
2434 // By default nothing is new... ;-)
2437 // Is the cache entry there?
2438 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2439 // Found so increase cache hit
2440 incrementStatsEntry('cache_hits');
2443 return $GLOBALS['cache_array']['revision'][$type][0];
2445 // FQFN of revision file
2446 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2448 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2449 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2450 // Forced rebuild of .revision file
2453 // Check for revision file
2454 if (!isFileReadable($FQFN)) {
2455 // Not found, so we need to create it
2458 // Revision file found
2459 $ins_vers = explode("\n", readFromFile($FQFN));
2461 // Get array for mapping information
2462 $mapper = array_flip(getSearchFor());
2463 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2465 // Is the content valid?
2466 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2467 // File needs update!
2470 // Generate fake cache entry
2471 foreach ($mapper as $map=>$idx) {
2472 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2475 // Return found value
2476 return trim($ins_vers[$mapper[$type]]);
2481 // Has it been updated?
2482 if ($new === true) {
2484 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2486 // ... and call recursive
2487 return getActualVersion($type);
2492 // Repares an array we are looking for
2493 // The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
2494 function getSearchFor () {
2495 // Add Revision, Date, Tag and Author
2496 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2498 // Return the created array
2502 // @TODO Please describe this function
2503 function getArrayFromActualVersion () {
2507 // Directory to start with search
2508 $last_changed = array(
2513 // Init return array
2514 $akt_vers = array();
2516 // Init value for counting the founded keywords
2519 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2520 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2523 $last_file = readFromFile($last_changed['path_name']);
2525 // Get all the keywords to search for
2526 $searchFor = getSearchFor();
2528 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2529 foreach ($searchFor as $search) {
2530 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2531 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2532 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2533 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2536 // Save the last-changed filename for debugging
2537 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2539 // at least 3 keyword-Tags are needed for propper values
2540 if ($res && $res >= 3
2541 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2542 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2543 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2544 // Prepare content witch need special treadment
2546 // Prepare timestamp for date
2547 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2548 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2550 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2551 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2552 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2556 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2557 $version = sendGetRequest('check-updates3.php');
2560 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2561 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2562 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2563 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2564 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2565 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2568 // Return prepared array
2569 return $GLOBALS['cache_array']['revision'];
2572 // Back-ported from the new ship-simu engine. :-)
2573 function debug_get_printable_backtrace () {
2575 $backtrace = "<ol>\n";
2577 // Get and prepare backtrace for output
2578 $backtraceArray = debug_backtrace();
2579 foreach ($backtraceArray as $key => $trace) {
2580 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2581 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2582 if (!isset($trace['args'])) $trace['args'] = array();
2583 $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:" . $trace['line'].", <span class=\"backtrace_function\">" . $trace['function'].'('.count($trace['args']).")</span></li>\n";
2587 $backtrace .= "</ol>\n";
2589 // Return the backtrace
2593 // Output a debug backtrace to the user
2594 function debug_report_bug ($message = '') {
2598 // Is the optional message set?
2599 if (!empty($message)) {
2601 $debug = sprintf("Note: %s<br />\n",
2605 // @TODO Add a little more infos here
2606 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2610 $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>";
2611 $debug .= debug_get_printable_backtrace();
2612 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2613 $debug .= "Thank you for finding bugs.";
2616 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2620 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2621 function generateSeed () {
2622 list($usec, $sec) = explode(' ', microtime());
2623 $microTime = (((float)$sec + (float)$usec)) * 100000;
2627 // Converts a message code to a human-readable message
2628 function getMessageFromErrorCode ($code) {
2632 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2633 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2634 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2635 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2636 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2637 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2638 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2639 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2640 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2641 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2642 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2643 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2644 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2645 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2646 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2647 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2648 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2649 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2650 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2651 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2652 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), '0'); break;
2653 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2654 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2655 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2656 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2657 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2658 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2659 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2661 case getCode('ERROR_MAILID'):
2662 if (isExtensionActive('mailid', true)) {
2663 $message = getMessage('ERROR_CONFIRMING_MAIL');
2665 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2669 case getCode('EXTENSION_PROBLEM'):
2670 if (isGetRequestElementSet('ext')) {
2671 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2673 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2677 case getCode('URL_TLOCK'):
2678 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2679 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2681 // Load timestamp from last order
2682 list($timestamp) = SQL_FETCHROW($result);
2683 $timestamp = generateDateTime($timestamp, '1');
2686 SQL_FREERESULT($result);
2688 // Calculate hours...
2689 $STD = round(getConfig('url_tlock') / 60 / 60);
2692 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2695 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2697 // Finally contruct the message
2698 // @TODO Rewrite this old lost code to a template
2699 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2700 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2701 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2705 // Missing/invalid code
2706 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2709 logDebugMessage(__FUNCTION__, __LINE__, $message);
2713 // Return the message
2717 // Generate a "link" for the given admin id (admin_id)
2718 function generateAdminLink ($adminId) {
2719 // No assigned admin is default
2720 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2722 // Zero? = Not assigned
2723 if (bigintval($adminId) > 0) {
2724 // Load admin's login
2725 $login = getAdminLogin($adminId);
2727 // Is the login valid?
2728 if ($login != '***') {
2729 // Is the extension there?
2730 if (isExtensionActive('admins')) {
2732 $admin = "<a href=\"".generateEmailLink(getAdminEmail($adminId), 'admins')."\">" . $login."</a>";
2734 // Extension not found
2735 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2739 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $adminId)."</div>";
2747 // Compile characters which are allowed in URLs
2748 function compileUriCode ($code, $simple = true) {
2749 // Compile constants
2750 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2752 // Compile QUOT and other non-HTML codes
2753 $code = str_replace('{DOT}', '.',
2754 str_replace('{SLASH}', '/',
2755 str_replace('{QUOT}', "'",
2756 str_replace('{DOLLAR}', '$',
2757 str_replace('{OPEN_ANCHOR}', '(',
2758 str_replace('{CLOSE_ANCHOR}', ')',
2759 str_replace('{OPEN_SQR}', '[',
2760 str_replace('{CLOSE_SQR}', ']',
2761 str_replace('{PER}', '%',
2765 // Return compiled code
2769 // Function taken from user comments on www.php.net / function eregi()
2770 function isUrlValidSimple ($url) {
2772 $url = secureString(str_replace("\\", '', compileCode(urldecode($url))));
2774 // Allows http and https
2775 $http = "(http|https)+(:\/\/)";
2777 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2778 // Test double-domains (e.g. .de.vu)
2779 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2781 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2783 $dir = "((/)+([-_\.[:alnum:]])+)*";
2785 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2786 // ... and the string after and including question character
2787 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2788 // Pattern for URLs like http://url/dir/doc.html?var=value
2789 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2790 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2791 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2792 // Pattern for URLs like http://url/dir/?var=value
2793 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2794 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2795 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2796 // Pattern for URLs like http://url/dir/page.ext
2797 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2798 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2799 $pattern['ipdp'] = $http . $ip . $dir . $page;
2800 // Pattern for URLs like http://url/dir
2801 $pattern['d1d'] = $http . $domain1 . $dir;
2802 $pattern['d2d'] = $http . $domain2 . $dir;
2803 $pattern['ipd'] = $http . $ip . $dir;
2804 // Pattern for URLs like http://url/?var=value
2805 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2806 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2807 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2808 // Pattern for URLs like http://url?var=value
2809 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2810 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2811 $pattern['ipg12'] = $http . $ip . $getstring1;
2812 // Test all patterns
2814 foreach ($pattern as $key => $pat) {
2816 if (isDebugRegExpressionEnabled()) {
2817 // @TODO Are these convertions still required?
2818 $pat = str_replace('.', "\.", $pat);
2819 $pat = str_replace('@', "\@", $pat);
2820 //* DEBUG: */ outputHtml($key."= " . $pat . "<br />");
2823 // Check if expression matches
2824 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2827 if ($reg === true) break;
2830 // Return true/false
2834 // Wtites data to a config.php-style file
2835 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2836 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2837 // Initialize some variables
2843 // Is the file there and read-/write-able?
2844 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2845 $search = 'CFG: ' . $comment;
2846 $tmp = $FQFN . '.tmp';
2848 // Open the source file
2849 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2851 // Is the resource valid?
2852 if (is_resource($fp)) {
2853 // Open temporary file
2854 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2856 // Is the resource again valid?
2857 if (is_resource($fp_tmp)) {
2858 // Mark temporary file as readable
2859 $GLOBALS['file_readable'][$tmp] = true;
2862 while (!feof($fp)) {
2863 // Read from source file
2864 $line = fgets ($fp, 1024);
2866 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2869 if ($next === $seek) {
2871 $line = $prefix . $DATA . $suffix . "\n";
2877 // Write to temp file
2878 fputs($fp_tmp, $line);
2884 // Finished writing tmp file
2888 // Close source file
2891 if (($done === true) && ($found === true)) {
2892 // Copy back tmp file and delete tmp :-)
2893 copyFileVerified($tmp, $FQFN, 0644);
2894 return removeFile($tmp);
2895 } elseif ($found === false) {
2896 outputHtml('<strong>CHANGE:</strong> 404!');
2898 outputHtml('<strong>TMP:</strong> UNDONE!');
2902 // File not found, not readable or writeable
2903 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2906 // An error was detected!
2909 // Send notification to admin
2910 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2911 if (getExtensionVersion('admins') >= '0.4.1') {
2913 sendAdminsEmails($subject, $templateName, $content, $userid);
2915 // Send out out-dated way
2916 $message = loadEmailTemplate($templateName, $content, $userid);
2917 sendAdminEmails($subject, $message);
2921 // Debug message logger
2922 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2923 // Is debug mode enabled?
2924 if ((isDebugModeEnabled()) || ($force === true)) {
2926 $message = str_replace("\r", '', str_replace("\n", '', $message));
2928 // Log this message away, we better don't call app_die() here to prevent an endless loop
2929 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2930 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2935 // Handle extra values
2936 function handleExtraValues ($filterFunction, $value, $extraValue) {
2937 // Default is the value itself
2940 // Do we have a special filter function?
2941 if (!empty($filterFunction)) {
2942 // Does the filter function exist?
2943 if (function_exists($filterFunction)) {
2944 // Do we have extra parameters here?
2945 if (!empty($extraValue)) {
2946 // Put both parameters in one new array by default
2947 $args = array($value, $extraValue);
2949 // If we have an array simply use it and pre-extend it with our value
2950 if (is_array($extraValue)) {
2951 // Make the new args array
2952 $args = merge_array(array($value), $extraValue);
2955 // Call the multi-parameter call-back
2956 $ret = call_user_func_array($filterFunction, $args);
2958 // One parameter call
2959 $ret = call_user_func($filterFunction, $value);
2968 // Converts timestamp selections into a timestamp
2969 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2970 // Init test variable
2973 // Get last three chars
2974 $test = substr($id, -3);
2976 // Improved way of checking! :-)
2977 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2978 // Found a multi-selection for timings?
2979 $test = substr($id, 0, -3);
2980 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)) {
2981 // Generate timestamp
2982 $postData[$test] = createTimestampFromSelections($test, $postData);
2983 $DATA[] = sprintf("%s='%s'", $test, $postData[$test]);
2985 // Remove data from array
2986 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2987 unset($postData[$test.'_' . $rem]);
2991 unset($id); $skip = true; $test2 = $test;
2994 // Process this entry
3000 // Reverts the german decimal comma into Computer decimal dot
3001 function convertCommaToDot ($str) {
3002 // Default float is not a float... ;-)
3005 // Which language is selected?
3006 switch (getLanguage()) {
3007 case 'de': // German language
3008 // Remove german thousand dots first
3009 $str = str_replace('.', '', $str);
3011 // Replace german commata with decimal dot and cast it
3012 $float = (float)str_replace(',', '.', $str);
3015 default: // US and so on
3016 // Remove thousand dots first and cast
3017 $float = (float)str_replace(',', '', $str);
3025 // Handle menu-depending failed logins and return the rendered content
3026 function handleLoginFailtures ($accessLevel) {
3027 // Default output is empty ;-)
3030 // Is the session data set?
3031 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3032 // Ignore zero values
3033 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3034 // Non-guest has login failures found, get both data and prepare it for template
3035 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3037 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3038 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), '2')
3042 $OUT = loadTemplate('login_failures', true, $content);
3045 // Reset session data
3046 setSession('mxchange_' . $accessLevel.'_failures', '');
3047 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3050 // Return rendered content
3055 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3057 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3059 // Shall I remove the cache file?
3060 if (isCacheInstanceValid()) {
3062 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3064 $GLOBALS['cache_instance']->removeCacheFile($force);
3067 // Include file given?
3070 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3072 // Is the include there?
3073 if (isIncludeReadable($inc)) {
3074 // And rebuild it from scratch
3075 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3078 // Include not found!
3079 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3085 // Determines the real remote address
3086 function determineRealRemoteAddress () {
3087 // Is a proxy in use?
3088 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3090 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3091 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3092 // Yet, another proxy
3093 $address = $_SERVER['HTTP_CLIENT_IP'];
3095 // The regular address when no proxy was used
3096 $address = $_SERVER['REMOTE_ADDR'];
3099 // This strips out the real address from proxy output
3100 if (strstr($address, ',')) {
3101 $addressArray = explode(',', $address);
3102 $address = $addressArray[0];
3105 // Return the result
3109 // Adds a bonus mail to the queue
3110 // This is a high-level function!
3111 function addNewBonusMail ($data, $mode = '', $output=true) {
3112 // Use mode from data if not set and availble ;-)
3113 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3115 // Generate receiver list
3116 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3119 if (!empty($RECEIVER)) {
3120 // Add bonus mail to queue
3121 addBonusMailToQueue(
3133 // Mail inserted into bonus pool
3134 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3135 } elseif ($output) {
3136 // More entered than can be reached!
3137 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3140 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3144 // Determines referal id and sets it
3145 function determineReferalId () {
3146 // Skip this in non-html-mode
3147 if (getOutputMode() != '0') return false;
3149 // Check if refid is set
3150 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3152 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3153 // The variable user comes from the click-counter script click.php and we only accept this here
3154 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3155 } elseif (isPostRequestElementSet('refid')) {
3156 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3157 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3158 } elseif (isGetRequestElementSet('refid')) {
3159 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3160 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3161 } elseif (isGetRequestElementSet('ref')) {
3162 // Set refid=ref (the referal link uses such variable)
3163 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3164 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3165 // Set session refid als global
3166 $GLOBALS['refid'] = bigintval(getSession('refid'));
3167 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3168 // Select a random user which has confirmed enougth mails
3169 $GLOBALS['refid'] = determineRandomReferalId();
3170 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3171 // Set default refid as refid in URL
3172 $GLOBALS['refid'] = getConfig('def_refid');
3174 // No default ID when sql_patches is not installed or none set
3175 $GLOBALS['refid'] = 0;
3178 // Set cookie when default refid > 0
3179 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3181 setSession('refid', $GLOBALS['refid']);
3184 // Return determined refid
3185 return $GLOBALS['refid'];
3188 // Enables the reset mode and runs it
3189 function doReset () {
3190 // Enable the reset mode
3191 $GLOBALS['reset_enabled'] = true;
3194 runFilterChain('reset');
3197 // Our shutdown-function
3198 function shutdown () {
3199 // Call the filter chain 'shutdown'
3200 runFilterChain('shutdown', null);
3202 if (SQL_IS_LINK_UP()) {
3204 SQL_CLOSE(__FILE__, __LINE__);
3205 } elseif (!isInstallationPhase()) {
3207 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3210 // Stop executing here
3214 // Setter for userid
3215 function setUserId ($userid) {
3216 $GLOBALS['userid'] = bigintval($userid);
3219 // Getter for userid or returns zero
3220 function getUserId () {
3224 // Is the userid set?
3225 if (isUserIdSet()) {
3227 $userid = $GLOBALS['userid'];
3234 // Checks ether the userid is set
3235 function isUserIdSet () {
3236 return (isset($GLOBALS['userid']));
3239 // Handle message codes from URL
3240 function handleCodeMessage () {
3241 if (isGetRequestElementSet('code')) {
3242 // Default extension is 'unknown'
3245 // Is extension given?
3246 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3248 // Convert the 'code' parameter from URL to a human-readable message
3249 $message = getMessageFromErrorCode(getRequestElement('code'));
3251 // Load message template
3252 loadTemplate('message', false, $message);
3256 // Setter for extra title
3257 function setExtraTitle ($extraTitle) {
3258 $GLOBALS['extra_title'] = $extraTitle;
3261 // Getter for extra title
3262 function getExtraTitle () {
3263 // Is the extra title set?
3264 if (!isExtraTitleSet()) {
3265 // No, then abort here
3266 debug_report_bug('extra_title is not set!');
3270 return $GLOBALS['extra_title'];
3273 // Checks if the extra title is set
3274 function isExtraTitleSet () {
3275 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3278 // Generates a 'extension foo inactive' message
3279 function generateExtensionInactiveMessage ($ext_name) {
3280 // Is the extension empty?
3281 if (empty($ext_name)) {
3282 // This should not happen
3283 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3287 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3289 // Is an admin logged in?
3291 // Then output admin message
3292 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3295 // Return prepared message
3299 // Generates a 'extension foo not installed' message
3300 function generateExtensionNotInstalledMessage ($ext_name) {
3301 // Is the extension empty?
3302 if (empty($ext_name)) {
3303 // This should not happen
3304 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3308 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3310 // Is an admin logged in?
3312 // Then output admin message
3313 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3316 // Return prepared message
3320 // Generates a message depending on if the extension is not installed or not
3322 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3326 // Is the extension not installed or just deactivated?
3327 switch (isExtensionInstalled($ext_name)) {
3328 case true; // Deactivated!
3329 $message = generateExtensionInactiveMessage($ext_name);
3332 case false; // Not installed!
3333 $message = generateExtensionNotInstalledMessage($ext_name);
3336 default: // Should not happen!
3337 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3338 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3342 // Return the message
3346 // Reads a directory recursively by default and searches for files not matching
3347 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3348 // a whole directory.
3349 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3350 // Add default entries we should exclude
3351 $excludeArray[] = '.';
3352 $excludeArray[] = '..';
3353 $excludeArray[] = '.svn';
3354 $excludeArray[] = '.htaccess';
3356 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3361 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3364 while ($baseFile = readdir($dirPointer)) {
3365 // Exclude '.', '..' and entries in $excludeArray automatically
3366 if (in_array($baseFile, $excludeArray, true)) {
3368 //* DEBUG: */ outputHtml('excluded=' . $baseFile . "<br />");
3372 // Construct include filename and FQFN
3373 $fileName = $baseDir . $baseFile;
3374 $FQFN = getConfig('PATH') . $fileName;
3376 // Remove double slashes
3377 $FQFN = str_replace('//', '/', $FQFN);
3379 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3380 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3381 // These Lines are only for debugging!!
3382 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . "<br />");
3383 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . "<br />");
3384 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . "<br />");
3390 // Skip also files with non-matching prefix genericly
3391 if (($recursive === true) && (isDirectory($FQFN))) {
3392 // Is a redirectory so read it as well
3393 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3395 // And skip further processing
3397 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3399 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3401 } elseif (!isFileReadable($FQFN)) {
3402 // Not readable so skip it
3403 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3407 // Is the file a PHP script or other?
3408 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3409 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3410 // Is this a valid include file?
3411 if ($extension == '.php') {
3412 // Remove both for extension name
3413 $extName = substr($baseFile, strlen($prefix), -4);
3415 // Is the extension valid and active?
3416 if (isExtensionNameValid($extName)) {
3417 // Then add this file
3418 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3419 $files[] = $fileName;
3421 // Add non-extension files as well
3422 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3423 if ($addBaseDir === true) {
3424 $files[] = $fileName;
3426 $files[] = $baseFile;
3430 // We found .php file but should not search for them, why?
3431 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3433 } elseif (substr($baseFile, -4, 4) == $extension) {
3434 // Other, generic file found
3435 $files[] = $fileName;
3440 closedir($dirPointer);
3445 // Return array with include files
3446 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3450 // Maps a module name into a database table name
3451 function mapModuleToTable ($moduleName) {
3452 // Map only these, still lame code...
3453 switch ($moduleName) {
3454 // 'index' is the guest's menu
3455 case 'index': $moduleName = 'guest'; break;
3456 // ... and 'login' the member's menu
3457 case 'login': $moduleName = 'member'; break;
3458 // Anything else will not be mapped, silently.
3465 // Add SQL debug data to array for later output
3466 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3467 // Don't execute anything here if we don't need
3468 if (getConfig('display_debug_sqls') != 'Y') return;
3472 'num_rows' => SQL_NUMROWS($result),
3473 'affected' => SQL_AFFECTEDROWS(),
3474 'sql_str' => $sqlString,
3475 'timing' => $timing,
3476 'file' => basename($F),
3481 $GLOBALS['debug_sqls'][] = $record;
3484 // Initializes the cache instance
3485 function initCacheInstance () {
3486 // Load include for CacheSystem class
3487 loadIncludeOnce('inc/classes/cachesystem.class.php');
3489 // Initialize cache system only when it's needed
3490 $GLOBALS['cache_instance'] = new CacheSystem();
3491 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3492 // Failed to initialize cache sustem
3493 addFatalMessage(__FILE__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_CANNOT_INITIALIZE'));
3497 // Getter for message from array or raw message
3498 function getMessageFromIndexedArray ($message, $pos, $array) {
3499 // Check if the requested message was found in array
3500 if (isset($array[$pos])) {
3501 // ... if yes then use it!
3502 $ret = $array[$pos];
3504 // ... else use default message
3512 // Handles fatal errors
3513 function handleFatalErrors () {
3514 // Do we have errors to handle and right output mode?
3515 if ((getTotalFatalErrors() == 0) || (getOutputMode() != 0)) {
3516 // Abort executing here
3521 setContentType('text/html');
3524 loadIncludeOnce('inc/load_config.php');
3526 // Set unset variable
3527 if (empty($check)) $check = '';
3532 // Installation phase or regular mode?
3533 if ((isInstallationPhase())) {
3534 // While we are installing ouput other header than while it is installed... :-)
3536 foreach (getFatalArray() as $key => $value) {
3537 // Prepare content for the template
3539 'key' => ($key + 1),
3543 // Load row template
3544 $OUT .= loadTemplate('install_fatal_row', true, $content);
3547 // Load main template
3548 $content = loadTemplate('install_fatal_table', true, $OUT);
3549 } elseif (isInstalled()) {
3550 // Display all runtime fatal errors
3552 foreach (getFatalArray() as $key => $value) {
3553 // Prepare content for the template
3555 'key' => ($key + 1),
3559 // Load row template
3560 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
3563 // Load main template
3564 $content = loadTemplate('runtime_fatal_table', true, $OUT);
3567 // Message to regular users (non-admin)
3568 $CORR = getMessage('FATAL_REPORT_ERRORS');
3570 // PHP warnings fixed
3571 if ($check == 'done') {
3572 if (isAdmin()) $CORR = getMessage('FATAL_CORRECT_ERRORS');
3575 // Remember all in array
3582 loadIncludeOnce('inc/header.php');
3584 // Load main template
3585 loadTemplate('fatal_errors', false, $content);
3587 // Delete all to prevent double-display
3588 initFatalMessages();
3591 loadIncludeOnce('inc/footer.php');
3597 //////////////////////////////////////////////////
3598 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3599 //////////////////////////////////////////////////
3601 if (!function_exists('html_entity_decode')) {
3602 // Taken from documentation on www.php.net
3603 function html_entity_decode ($string) {
3604 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3605 $trans_tbl = array_flip($trans_tbl);
3606 return strtr($string, $trans_tbl);