2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/25/2003 *
4 * =============== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
44 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
45 function outputHtml ($htmlCode, $newLine = true) {
47 $username = getMessage('USERNAME_UNKNOWN');
48 if (isset($GLOBALS['username'])) $username = getUsername();
50 // Do we have HTML-Code here?
51 if (!empty($htmlCode)) {
52 // Yes, so we handle it as you have configured
53 switch (getConfig('OUTPUT_MODE')) {
55 // That's why you don't need any \n at the end of your HTML code... :-)
56 if (getPhpCaching() == 'on') {
57 // Output into PHP's internal buffer
58 outputRawCode($htmlCode);
60 // That's why you don't need any \n at the end of your HTML code... :-)
61 if ($newLine === true) print("\n");
63 // Render mode for old or lame servers...
64 $GLOBALS['output'] .= $htmlCode;
66 // That's why you don't need any \n at the end of your HTML code... :-)
67 if ($newLine === true) $GLOBALS['output'] .= "\n";
72 // If we are switching from render to direct output rendered code
73 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
75 // The same as above... ^
76 outputRawCode($htmlCode);
77 if ($newLine) print("\n");
81 // Huh, something goes wrong or maybe you have edited config.php ???
82 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
85 } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
86 // Headers already sent?
89 logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
91 // Trigger an user error
92 debug_report_bug('Headers are already sent!');
95 // Output cached HTML code
96 $GLOBALS['output'] = ob_get_contents();
98 // Clear output buffer for later output if output is found
99 if (!empty($GLOBALS['output'])) {
104 sendHeader('HTTP/1.1 200');
107 $now = gmdate('D, d M Y H:i:s') . ' GMT';
109 // General headers for no caching
110 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
111 sendHeader('Last-Modified: ' . $now);
112 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
113 sendHeader('Pragma: no-cache'); // HTTP/1.0
114 sendHeader('Connection: Close');
115 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
116 sendHeader('Content-language: ' . getLanguage());
118 // Extension 'rewrite' installed?
119 if ((isExtensionActive('rewrite')) && (getOutputMode() != '1')) {
120 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
126 // Compile and run finished rendered HTML code
127 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
128 // Prepare the content and eval() it...
133 $eval = "\$newContent = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";";
136 // Was that eval okay?
137 if (empty($newContent)) {
138 // Something went wrong!
139 debug_report_bug('Evaluation error:<pre>' . htmlentities($eval) . '</pre>');
141 $GLOBALS['output'] = $newContent;
147 // Output code here, DO NOT REMOVE! ;-)
148 outputRawCode($GLOBALS['output']);
149 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
150 // Rewrite links when rewrite extension is active
151 if ((isExtensionActive('rewrite')) && (getOutputMode() != '1')) {
152 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
155 // Compile and run finished rendered HTML code
156 while (strpos($GLOBALS['output'], '{!') > 0) {
157 eval("\$GLOBALS['output'] = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";");
160 // Output code here, DO NOT REMOVE! ;-)
161 outputRawCode($GLOBALS['output']);
165 // Output the raw HTML code
166 function outputRawCode ($htmlCode) {
167 // Output stripped HTML code to avoid broken JavaScript code, etc.
168 print(stripslashes(stripslashes($htmlCode)));
170 // Flush the output if only getPhpCaching() is not 'on'
171 if (getPhpCaching() != 'on') {
177 // Init fatal message array
178 function initFatalMessages () {
179 $GLOBALS['fatal_messages'] = array();
182 // Getter for whole fatal error messages
183 function getFatalArray () {
184 return $GLOBALS['fatal_messages'];
187 // Add a fatal error message to the queue array
188 function addFatalMessage ($F, $L, $message, $extra='') {
189 if (is_array($extra)) {
190 // Multiple extras for a message with masks
191 $message = call_user_func_array('sprintf', $extra);
192 } elseif (!empty($extra)) {
193 // $message is text with a mask plus extras to insert into the text
194 $message = sprintf($message, $extra);
197 // Add message to $GLOBALS['fatal_messages']
198 $GLOBALS['fatal_messages'][] = $message;
200 // Log fatal messages away
201 debug_report_bug($message);
202 logDebugMessage($F, $L, " message={$message}");
205 // Getter for total fatal message count
206 function getTotalFatalErrors () {
210 // Do we have at least the first entry?
211 if (!empty($GLOBALS['fatal_messages'][0])) {
213 $count = count($GLOBALS['fatal_messages']);
220 // Load a template file and return it's content (only it's name; do not use ' or ")
221 function loadTemplate ($template, $return=false, $content=array()) {
222 // @TODO Remove this sanity-check if all is fine
223 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
225 // @TODO Try to rewrite all $DATA to $content
229 if (!isset($GLOBALS['template_eval'][$template])) {
230 // Add more variables which you want to use in your template files
231 $username = getUsername();
233 // Make all template names lowercase
234 $template = strtolower($template);
236 // Count the template load
237 incrementConfigEntry('num_templates');
241 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
243 // Generate date/time string
244 $date_time = generateDateTime(time(), '1');
246 // Is content an array
247 if (is_array($content)) $content['date_time'] = $date_time;
249 // @DEPRECATED Try to rewrite the if() condition
250 if ($template == 'member_support_form') {
251 // Support request of a member
252 $result = SQL_QUERY_ESC("SELECT `userid`, `gender`, `surname`, `family`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
253 array(getUserId()), __FUNCTION__, __LINE__);
255 // Is content an array?
256 if (is_array($content)) {
258 $content = merge_array($content, SQL_FETCHARRAY($result));
261 $content['gender'] = translateGender($content['gender']);
264 // @TODO Find all templates which are using these direct variables and rewrite them.
265 // @TODO After this step is done, this else-block is history
266 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
269 $gender = translateGender($gender);
270 logDebugMessage(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
274 SQL_FREERESULT($result);
278 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
281 // Check for admin/guest/member templates
282 if (substr($template, 0, 6) == 'admin_') {
283 // Admin template found
285 } elseif (substr($template, 0, 6) == 'guest_') {
286 // Guest template found
288 } elseif (substr($template, 0, 7) == 'member_') {
289 // Member template found
291 } elseif (substr($template, 0, 8) == 'install_') {
292 // Installation template found
294 } elseif (substr($template, 0, 4) == 'ext_') {
295 // Extension template found
297 } elseif (substr($template, 0, 3) == 'la_') {
298 // 'Logical-area' template found
300 } elseif (substr($template, 0, 3) == 'js_') {
301 // JavaScript template found
303 } elseif (substr($template, 0, 5) == 'menu_') {
304 // Menu template found
307 // Test for extension
308 $test = substr($template, 0, strpos($template, '_'));
310 // Probe for valid extension name
311 if (isExtensionNameValid($test)) {
312 // Set extra path to extension's name
317 ////////////////////////
318 // Generate file name //
319 ////////////////////////
320 $FQFN = $basePath . $mode . $template . '.tpl';
322 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
323 // Select what depended header/footer template file for admin/guest/member area
324 $file2 = sprintf("%s%s%s_%s.tpl",
332 if (isFileReadable($file2)) $FQFN = $file2;
334 // Remove variable from memory
338 // Does the special template exists?
339 if (!isFileReadable($FQFN)) {
340 // Reset to default template
341 $FQFN = $basePath . $template . '.tpl';
344 // Now does the final template exists?
345 if (isFileReadable($FQFN)) {
346 // The local file does exists so we load it. :)
347 $GLOBALS['tpl_content'] = readFromFile($FQFN);
349 // Replace ' to our own chars to preventing them being quoted
350 while (strpos($GLOBALS['tpl_content'], "'") !== false) { $GLOBALS['tpl_content'] = str_replace("'", '{QUOT}', $GLOBALS['tpl_content']); }
352 // Do we have to compile the code?
354 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
355 // Normal HTML output?
356 if ($GLOBALS['output_mode'] == 0) {
357 // Add surrounding HTML comments to help finding bugs faster
358 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
360 // Prepare eval() command
361 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
363 // Prepare eval() command
364 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
367 // Add surrounding HTML comments to help finding bugs faster
368 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
369 $eval = '$ret = "' . smartAddSlashes($ret) . '";';
372 // Cache the eval() command here
373 $GLOBALS['template_eval'][$template] = $eval;
376 eval($GLOBALS['template_eval'][$template]);
379 $GLOBALS['template_eval'][$template] = '404';
381 } elseif (((isAdmin()) || ((isInstalling()) && (!isInstalled()))) && ($GLOBALS['template_eval'][$template] == '404')) {
382 // Only admins shall see this warning or when installation mode is active
383 $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
384 (' . $template . ')<br />
386 {--TEMPLATE_CONTENT--}
387 <pre>' . print_r($content, true) . '</pre>
389 <pre>' . print_r($DATA, true) . '</pre>
393 eval($GLOBALS['template_eval'][$template]);
396 // Do we have some content to output or return?
398 // Not empty so let's put it out! ;)
399 if ($return === true) {
400 // Return the HTML code
406 } elseif (isDebugModeEnabled()) {
407 // Warning, empty output!
408 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
412 // Loads an email template and compiles it
413 function loadEmailTemplate ($template, $content = array(), $UID = '0') {
416 // Our configuration is kept non-global here
417 $_CONFIG = getConfigArray();
419 // Make sure all template names are lowercase!
420 $template = strtolower($template);
422 // Default 'nickname' if extension is not installed
425 // Prepare IP number and User Agent
426 $REMOTE_ADDR = detectRemoteAddr();
427 $HTTP_USER_AGENT = detectUserAgent();
430 $ADMIN = getConfig('MAIN_TITLE');
432 // Is the admin logged in?
435 $adminId = getCurrentAdminId();
438 $ADMIN = getAdminEmail($adminId);
441 // Neutral email address is default
442 $email = getConfig('WEBMASTER');
444 // Expiration in a nice output format
445 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
446 if (getConfig('auto_purge') == 0) {
447 // Will never expire!
448 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
450 // Create nice date string
451 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
454 // Is content an array?
455 if (is_array($content)) {
456 // Add expiration to array, $EXPIRATION is now deprecated!
457 $content['expiration'] = $EXPIRATION;
461 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />");
462 if (($UID > 0) && (is_array($content))) {
463 // If nickname extension is installed, fetch nickname as well
464 if (isExtensionActive('nickname')) {
465 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
467 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email`, `nickname` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
468 array(bigintval($UID)), __FUNCTION__, __LINE__);
470 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
472 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
473 array(bigintval($UID)), __FUNCTION__, __LINE__);
476 // Fetch and merge data
477 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
478 $content = merge_array($content, SQL_FETCHARRAY($result));
479 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
482 SQL_FREERESULT($result);
485 // Translate M to male or F to female if present
486 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
488 // Overwrite email from data if present
489 if (isset($content['email'])) $email = $content['email'];
491 // Store email for some functions in global data array
492 $DATA['email'] = $email;
495 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
497 // Check for admin/guest/member templates
498 if (substr($template, 0, 6) == 'admin_') {
499 // Admin template found
500 $FQFN = $basePath.'admin/' . $template.'.tpl';
501 } elseif (substr($template, 0, 6) == 'guest_') {
502 // Guest template found
503 $FQFN = $basePath.'guest/' . $template.'.tpl';
504 } elseif (substr($template, 0, 7) == 'member_') {
505 // Member template found
506 $FQFN = $basePath.'member/' . $template.'.tpl';
508 // Test for extension
509 $test = substr($template, 0, strpos($template, '_'));
510 if (isExtensionNameValid($test)) {
511 // Set extra path to extension's name
512 $FQFN = $basePath . $test.'/' . $template.'.tpl';
514 // No special filename
515 $FQFN = $basePath . $template.'.tpl';
519 // Does the special template exists?
520 if (!isFileReadable($FQFN)) {
521 // Reset to default template
522 $FQFN = $basePath . $template.'.tpl';
525 // Now does the final template exists?
527 if (isFileReadable($FQFN)) {
528 // The local file does exists so we load it. :)
529 $GLOBALS['tpl_content'] = readFromFile($FQFN);
530 $GLOBALS['tpl_content'] = SQL_ESCAPE($GLOBALS['tpl_content']);
533 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode($GLOBALS['tpl_content'])."\");";
534 eval($GLOBALS['tpl_content']);
535 } elseif (!empty($template)) {
536 // Template file not found!
537 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
538 {--TEMPLATE_CONTENT--}
539 <pre>".print_r($content, true)."</pre>
541 <pre>".print_r($DATA, true)."</pre>
544 // Debug mode not active? Then remove the HTML tags
545 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
547 // No template name supplied!
548 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
551 // Is there some content?
552 if (empty($newContent)) {
554 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
555 // Add last error if the required function exists
556 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
559 // Remove content and data
563 // Compile the code and eval it
564 $eval = '$newContent = "' . compileCode(addSmartSlashes($newContent)) . '";';
571 // Send mail out to an email address
572 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
573 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
575 // Compile subject line (for POINTS constant etc.)
576 eval("\$subject = decodeEntities(\"".compileCode(smartAddSlashes($subject))."\");");
579 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
580 // Value detected, is the message extension installed?
581 // @TODO Extension 'msg' does not exist
582 if (isExtensionActive('msg')) {
583 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
586 // Load email address
587 $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
588 array(bigintval($toEmail)), __FUNCTION__, __LINE__);
589 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />");
591 // Does the user exist?
592 if (SQL_NUMROWS($result_email)) {
593 // Load email address
594 list($toEmail) = SQL_FETCHROW($result_email);
597 $toEmail = getConfig('WEBMASTER');
601 SQL_FREERESULT($result_email);
603 } elseif ($toEmail == '0') {
605 $toEmail = getConfig('WEBMASTER');
607 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
609 // Check for PHPMailer or debug-mode
610 if (!checkPhpMailerUsage()) {
611 // Not in PHPMailer-Mode
612 if (empty($mailHeader)) {
613 // Load email header template
614 $mailHeader = loadEmailTemplate('header');
617 $mailHeader .= loadEmailTemplate('header');
619 } elseif (isDebugModeEnabled()) {
620 if (empty($mailHeader)) {
621 // Load email header template
622 $mailHeader = loadEmailTemplate('header');
625 $mailHeader .= loadEmailTemplate('header');
630 eval("\$toEmail = \"".compileCode(smartAddSlashes($toEmail))."\";");
633 eval("\$message = \"".compileCode(smartAddSlashes($message))."\";");
635 // Fix HTML parameter (default is no!)
636 if (empty($isHtml)) $isHtml = 'N';
637 if (isDebugModeEnabled()) {
638 // In debug mode we want to display the mail instead of sending it away so we can debug this part
640 ".htmlentities(trim($mailHeader))."
642 Subject : " . $subject."
643 Message : " . $message."
645 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
646 // Send mail as HTML away
647 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
648 } elseif (!empty($toEmail)) {
650 sendRawEmail($toEmail, $subject, $message, $mailHeader);
651 } elseif ($isHtml != 'Y') {
653 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
657 // Check if legacy or PHPMailer command
658 // @TODO Rewrite this to an extension 'smtp'
660 function checkPhpMailerUsage() {
661 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
664 // Send out a raw email with PHPMailer class or legacy mail() command
665 function sendRawEmail ($toEmail, $subject, $message, $from) {
666 // Shall we use PHPMailer class or legacy mode?
667 if (checkPhpMailerUsage()) {
668 // Use PHPMailer class with SMTP enabled
669 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
670 loadIncludeOnce('inc/phpmailer/class.smtp.php');
673 $mail = new PHPMailer();
674 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
677 $mail->SMTPAuth = true;
678 $mail->Host = getConfig('SMTP_HOSTNAME');
680 $mail->Username = getConfig('SMTP_USER');
681 $mail->Password = getConfig('SMTP_PASSWORD');
683 $mail->From = getConfig('WEBMASTER');
687 $mail->FromName = getConfig('MAIN_TITLE');
688 $mail->Subject = $subject;
689 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
690 $mail->Body = $message;
691 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
692 $mail->WordWrap = 70;
695 $mail->Body = decodeEntities($message);
697 $mail->AddAddress($toEmail, '');
698 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
699 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
700 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
703 // Use legacy mail() command
704 mail($toEmail, $subject, decodeEntities($message), $from);
708 // Generate a password in a specified length or use default password length
709 function generatePassword ($length = 0) {
710 // Auto-fix invalid length of zero
711 if ($length == 0) $length = getConfig('pass_len');
713 // Initialize array with all allowed chars
714 $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,-,+,_,/,.');
716 // Start creating password
718 for ($i = 0; $i < $length; $i++) {
719 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
722 // When the size is below 40 we can also add additional security by scrambling
723 // it. Otherwise we may corrupt hashes
724 if (strlen($PASS) <= 40) {
725 // Also scramble the password
726 $PASS = scrambleString($PASS);
729 // Return the password
733 // Generates a human-readable timestamp from the Uni* stamp
734 function generateDateTime ($time, $mode = '0') {
735 // Filter out numbers
736 $time = bigintval($time);
738 // If the stamp is zero it mostly didn't "happen"
741 return getMessage('NEVER_HAPPENED');
744 switch (getLanguage()) {
745 case 'de': // German date / time format
747 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
748 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
749 case '2': $ret = date('d.m.Y|H:i', $time); break;
750 case '3': $ret = date('d.m.Y', $time); break;
752 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
757 default: // Default is the US date / time format!
759 case '0': $ret = date('r', $time); break;
760 case '1': $ret = date('Y-m-d - g:i A', $time); break;
761 case '2': $ret = date('y-m-d|H:i', $time); break;
762 case '3': $ret = date('y-m-d', $time); break;
764 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
773 // Translates Y/N to yes/no
774 function translateYesNo ($yn) {
776 $translated = '??? (' . $yn . ')';
778 case 'Y': $translated = getMessage('YES'); break;
779 case 'N': $translated = getMessage('NO'); break;
782 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
790 // Translates the "pool type" into human-readable
791 function translatePoolType ($type) {
792 // Default?type is unknown
793 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
796 $constName = sprintf("POOL_TYPE_%s", $type);
799 if (isMessageIdValid($constName)) {
801 $translated = getMessage($constName);
804 // Return "translation"
808 // Translates the american decimal dot into a german comma
809 function translateComma ($dotted, $cut = true, $max = 0) {
810 // Default is 3 you can change this in admin area "Misc -> Misc Options"
811 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
813 // Use from config is default
814 $maxComma = getConfig('max_comma');
816 // Use from parameter?
817 if ($max > 0) $maxComma = $max;
820 if (($cut === true) && ($max == 0)) {
821 // Test for commata if in cut-mode
822 $com = explode('.', $dotted);
823 if (count($com) < 2) {
824 // Don't display commatas even if there are none... ;-)
830 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
833 switch (getLanguage()) {
834 case 'de': // German language
835 $dotted = number_format($dotted, $maxComma, ',', '.');
838 default: // All others
839 $dotted = number_format($dotted, $maxComma, '.', ',');
843 // Return translated value
847 // Translate Uni*-like gender to human-readable
848 function translateGender ($gender) {
850 $ret = '!' . $gender . '!';
852 // Male/female or company?
854 case 'M': $ret = getMessage('GENDER_M'); break;
855 case 'F': $ret = getMessage('GENDER_F'); break;
856 case 'C': $ret = getMessage('GENDER_C'); break;
858 // Log unknown gender
859 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
863 // Return translated gender
867 // "Translates" the user status
868 function translateUserStatus ($status) {
869 // Generate message depending on status
874 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
879 $ret = getMessage('ACCOUNT_DELETED');
883 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
884 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
892 // Generates an URL for the dereferer
893 function generateDerefererUrl ($URL) {
894 // Don't de-refer our own links!
895 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
896 // De-refer this link
897 $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
904 // Generates an URL for the frametester
905 function generateFrametesterUrl ($URL) {
906 // Prepare frametester URL
907 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
908 encodeString(compileUriCode($URL))
911 // Return the new URL
912 return $frametesterUrl;
915 // Count entries from e.g. a selection box
916 function countSelection ($array) {
918 if (!is_array($array)) {
920 debug_report_bug(__FUNCTION__.': No array provided.');
927 foreach ($array as $key => $selected) {
929 if (!empty($selected)) $ret++;
932 // Return counted selections
936 // Generate XHTML code for the CAPTCHA
937 function generateCaptchaCode ($code, $type, $DATA, $userid) {
938 return '<IMG border="0" alt="Code" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
941 // Generates a timestamp (some wrapper for mktime())
942 function makeTime ($H, $M, $S, $stamp) {
943 // Extract day, month and year from given timestamp
944 $day = date('d', $stamp);
945 $month = date('m', $stamp);
946 $year = date('Y', $stamp);
948 // Create timestamp for wished time which depends on extracted date
949 return mktime($H, $M, $S, $month, $day, $year);
952 // Redirects to an URL and if neccessarry extends it with own base URL
953 function redirectToUrl ($URL) {
954 // Compile out URI codes
955 $URL = compileUriCode($URL);
957 // Check if http(s):// is there
958 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
959 // Make all URLs full-qualified
960 $URL = getConfig('URL') . '/' . $URL;
963 // Three different debug ways...
964 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
965 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $URL);
966 //* DEBUG: */ die($URL);
968 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
969 $rel = ' rel="external"';
971 // Do we have internal or external URL?
972 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
973 // Own (=internal) URL
978 $GLOBALS['output'] = ob_get_contents();
980 // Clear it only if there is content
981 if (!empty($GLOBALS['output'])) {
985 // Simple probe for bots/spiders from search engines
986 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
987 // Secure the URL against bad things such als HTML insertions and so on...
988 $URL = secureString($URL);
990 // Output new location link as anchor
991 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
992 } elseif (!headers_sent()) {
993 // Load URL when headers are not sent
994 //* DEBUG: */ debug_report_bug("URL={$URL}");
995 sendHeader('Location: '.str_replace('&', '&', $URL));
997 // Output error message
998 loadInclude('inc/header.php');
999 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
1000 loadInclude('inc/footer.php');
1003 // Shut the mailer down here
1007 // Wrapper for redirectToUrl but URL comes from a configuration entry
1008 function redirectToConfiguredUrl ($configEntry) {
1010 $URL = getConfig($configEntry);
1013 if (is_null($URL)) {
1015 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1019 redirectToUrl($URL);
1022 // Compiles the given HTML/mail code
1023 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1024 // Is the code a string?
1025 if (!is_string($code)) {
1026 // Silently return it
1030 // Init replacement-array with full security characters
1031 $secChars = $GLOBALS['security_chars'];
1033 // Select smaller set of chars to replace when we e.g. want to compile URLs
1034 if ($full === false) $secChars = $GLOBALS['url_chars'];
1036 // Compile more through a filter
1037 $code = runFilterChain('compile_code', $code);
1039 // Compile constants
1040 if ($constants === true) {
1041 // BEFORE 0.2.1 : Language and data constants
1042 // WITH 0.2.1+ : Only language constants
1043 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1045 // BEFORE 0.2.1 : Not used
1046 // WITH 0.2.1+ : Data constants
1047 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1050 // Compile QUOT and other non-HTML codes
1051 foreach ($secChars['to'] as $k => $to) {
1052 // Do the reversed thing as in inc/libs/security_functions.php
1053 $code = str_replace($to, $secChars['from'][$k], $code);
1056 // But shall I keep simple quotes for later use?
1057 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1059 // Find $content[bla][blub] entries
1060 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1062 // Are some matches found?
1063 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1064 // Replace all matches
1065 $matchesFound = array();
1066 foreach ($matches[0] as $key => $match) {
1067 // Fuzzy look has failed by default
1068 $fuzzyFound = false;
1070 // Fuzzy look on match if already found
1071 foreach ($matchesFound as $found => $set) {
1073 $test = substr($found, 0, strlen($match));
1075 // Does this entry exist?
1076 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1077 if ($test == $match) {
1079 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1086 if ($fuzzyFound === true) continue;
1088 // Take all string elements
1089 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1090 // Replace it in the code
1091 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1092 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1093 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1094 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1095 $matchesFound[$match] = 1;
1096 } elseif (!isset($matchesFound[$match])) {
1097 // Not yet replaced!
1098 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1099 $code = str_replace($match, "\"." . $match.".\"", $code);
1100 $matchesFound[$match] = 1;
1105 // Return compiled code
1109 /************************************************************************
1111 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1112 * $a_sort sortiert: *
1114 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1115 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1116 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1117 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1118 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1120 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1121 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1122 * Sie, dass es doch nicht so schwer ist! :-) *
1124 ************************************************************************/
1125 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1127 while ($primary_key < count($a_sort)) {
1128 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1129 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1131 if ($nums === false) {
1132 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1133 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1134 } elseif ($key != $key2) {
1135 // Sort numbers (E.g.: 9 < 10)
1136 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1137 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1141 // We have found two different values, so let's sort whole array
1142 foreach ($dummy as $sort_key => $sort_val) {
1143 $t = $dummy[$sort_key][$key];
1144 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1145 $dummy[$sort_key][$key2] = $t;
1156 // Write back sorted array
1161 function addSelectionBox ($type, $default, $prefix = '', $id = '0') {
1164 if ($type == 'yn') {
1165 // This is a yes/no selection only!
1166 if ($id > 0) $prefix .= "[" . $id."]";
1167 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1169 // Begin with regular selection box here
1170 if (!empty($prefix)) $prefix .= "_";
1172 if ($id > 0) $type2 .= "[" . $id."]";
1173 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1178 for ($idx = 1; $idx < 32; $idx++) {
1179 $OUT .= "<option value=\"" . $idx."\"";
1180 if ($default == $idx) $OUT .= ' selected="selected"';
1181 $OUT .= ">" . $idx."</option>\n";
1185 case 'month': // Month
1186 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1187 $OUT .= "<option value=\"" . $month."\"";
1188 if ($default == $month) $OUT .= ' selected="selected"';
1189 $OUT .= ">" . $descr."</option>\n";
1193 case 'year': // Year
1195 $year = date('Y', time());
1197 // Use configured min age or fixed?
1198 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1200 $startYear = $year - getConfig('min_age');
1203 $startYear = $year - 16;
1206 // Calculate earliest year (100 years old people can still enter Internet???)
1207 $minYear = $year - 100;
1209 // Check if the default value is larger than minimum and bigger than actual year
1210 if (($default > $minYear) && ($default >= $year)) {
1211 for ($idx = $year; $idx < ($year + 11); $idx++) {
1212 $OUT .= "<option value=\"" . $idx."\"";
1213 if ($default == $idx) $OUT .= ' selected="selected"';
1214 $OUT .= ">" . $idx."</option>\n";
1216 } elseif ($default == -1) {
1217 // Current year minus 1
1218 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1220 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1223 // Get current year and subtract the configured minimum age
1224 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1225 // Calculate earliest year depending on extension version
1226 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1227 // Use configured minimum age
1228 $year = date('Y', time()) - getConfig('min_age');
1230 // Use fixed 16 years age
1231 $year = date('Y', time()) - 16;
1234 // Construct year selection list
1235 for ($idx = $minYear; $idx <= $year; $idx++) {
1236 $OUT .= "<option value=\"" . $idx."\"";
1237 if ($default == $idx) $OUT .= ' selected="selected"';
1238 $OUT .= ">" . $idx."</option>\n";
1245 for ($idx = 0; $idx < 60; $idx+=5) {
1246 if (strlen($idx) == 1) $idx = '0' . $idx;
1247 $OUT .= "<option value=\"" . $idx."\"";
1248 if ($default == $idx) $OUT .= ' selected="selected"';
1249 $OUT .= ">" . $idx."</option>\n";
1254 for ($idx = 0; $idx < 24; $idx++) {
1255 if (strlen($idx) == 1) $idx = '0' . $idx;
1256 $OUT .= "<option value=\"" . $idx."\"";
1257 if ($default == $idx) $OUT .= ' selected="selected"';
1258 $OUT .= ">" . $idx."</option>\n";
1263 $OUT .= "<option value=\"Y\"";
1264 if ($default == 'Y') $OUT .= ' selected="selected"';
1265 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1266 if ($default != 'Y') $OUT .= ' selected="selected"';
1267 $OUT .= ">{--NO--}</option>\n";
1270 $OUT .= " </select>\n";
1275 // Deprecated : $length
1278 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1279 // Build server string
1280 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1283 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1284 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1285 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1286 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1287 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1289 // Build string from misc data
1290 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1292 // Add more additional data
1293 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1295 // Add referal id, language, theme and userid
1296 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1297 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1298 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1299 $data .= getConfig('ENCRYPT_SEPERATOR') . getUserId();
1301 // Calculate number for generating the code
1302 $a = $code + getConfig('_ADD') - 1;
1304 if (isConfigEntrySet('master_hash')) {
1305 // Generate hash with master salt from modula of number with the prime number and other data
1306 $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'));
1308 // Create number from hash
1309 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1311 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1312 $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));
1314 // Create number from hash
1315 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1318 // At least 10 numbers shall be secure enought!
1319 $len = getConfig('code_length');
1320 if ($len == 0) $len = $length;
1321 if ($len == 0) $len = 10;
1323 // Cut off requested counts of number
1324 $return = substr(str_replace('.', '', $rcode), 0, $len);
1326 // Done building code
1330 // Does only allow numbers
1331 function bigintval ($num, $castValue = true) {
1332 // Filter all numbers out
1333 $ret = preg_replace('/[^0123456789]/', '', $num);
1336 if ($castValue) $ret = (double)$ret;
1338 // Has the whole value changed?
1339 // @TODO Remove this if() block if all is working fine
1340 if ('' . $ret . '' != '' . $num . '') {
1342 //debug_report_bug("{$ret}<>{$num}");
1349 // Insert the code in $img_code into jpeg or PNG image
1350 function generateImageOrCode ($img_code, $headerSent=true) {
1351 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1352 // Stop execution of function here because of over-sized code length
1354 } elseif ($headerSent === false) {
1355 // Return in an HTML code code
1356 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1360 $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
1361 if (isFileReadable($img)) {
1362 // Switch image type
1363 switch (getConfig('img_type'))
1366 // Okay, load image and hide all errors
1367 $image = imagecreatefromjpeg($img);
1371 // Okay, load image and hide all errors
1372 $image = imagecreatefrompng($img);
1376 // Exit function here
1377 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1381 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1382 $text_color = imagecolorallocate($image, 0, 0, 0);
1384 // Insert code into image
1385 imagestring($image, 5, 14, 2, $img_code, $text_color);
1387 // Return to browser
1388 sendHeader('Content-Type: image/' . getConfig('img_type'));
1390 // Output image with matching image factory
1391 switch (getConfig('img_type')) {
1392 case 'jpg': imagejpeg($image); break;
1393 case 'png': imagepng($image); break;
1396 // Remove image from memory
1397 imagedestroy($image);
1399 // Create selection box or array of splitted timestamp
1400 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1401 // Calculate 2-seconds timestamp
1402 $stamp = round($timestamp);
1403 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1405 // Do we have a leap year?
1407 $TEST = date('Y', time()) / 4;
1408 $M1 = date('m', time());
1409 $M2 = date('m', (time() + $timestamp));
1411 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1412 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1414 // First of all years...
1415 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1416 //* DEBUG: */ print("Y={$Y}<br />");
1418 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1419 //* DEBUG: */ print("M={$M}<br />");
1421 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1422 //* DEBUG: */ print("W={$W}<br />");
1424 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1425 //* DEBUG: */ print("D={$D}<br />");
1427 $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));
1428 //* DEBUG: */ print("h={$h}<br />");
1430 $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));
1431 //* DEBUG: */ print("m={$m}<br />");
1432 // And at last seconds...
1433 $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));
1434 //* DEBUG: */ print("s={$s}<br />");
1436 // Is seconds zero and time is < 60 seconds?
1437 if (($s == 0) && ($timestamp < 60)) {
1439 $s = round($timestamp);
1443 // Now we convert them in seconds...
1445 if ($return_array) {
1446 // Just put all data in an array for later use
1458 $OUT = "<div align=\"" . $align."\">\n";
1459 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1462 if (ereg('Y', $display) || (empty($display))) {
1463 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1466 if (ereg('M', $display) || (empty($display))) {
1467 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1470 if (ereg("W", $display) || (empty($display))) {
1471 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1474 if (ereg("D", $display) || (empty($display))) {
1475 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1478 if (ereg("h", $display) || (empty($display))) {
1479 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1482 if (ereg('m', $display) || (empty($display))) {
1483 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1486 if (ereg("s", $display) || (empty($display))) {
1487 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1493 if (ereg('Y', $display) || (empty($display))) {
1494 // Generate year selection
1495 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1496 for ($idx = 0; $idx <= 10; $idx++) {
1497 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1498 if ($idx == $Y) $OUT .= ' selected="selected"';
1499 $OUT .= ">" . $idx."</option>\n";
1501 $OUT .= " </select></td>\n";
1503 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1506 if (ereg('M', $display) || (empty($display))) {
1507 // Generate month selection
1508 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1509 for ($idx = 0; $idx <= 11; $idx++)
1511 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1512 if ($idx == $M) $OUT .= ' selected="selected"';
1513 $OUT .= ">" . $idx."</option>\n";
1515 $OUT .= " </select></td>\n";
1517 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1520 if (ereg("W", $display) || (empty($display))) {
1521 // Generate week selection
1522 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1523 for ($idx = 0; $idx <= 4; $idx++) {
1524 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1525 if ($idx == $W) $OUT .= ' selected="selected"';
1526 $OUT .= ">" . $idx."</option>\n";
1528 $OUT .= " </select></td>\n";
1530 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1533 if (ereg("D", $display) || (empty($display))) {
1534 // Generate day selection
1535 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1536 for ($idx = 0; $idx <= 31; $idx++) {
1537 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1538 if ($idx == $D) $OUT .= ' selected="selected"';
1539 $OUT .= ">" . $idx."</option>\n";
1541 $OUT .= " </select></td>\n";
1543 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1546 if (ereg("h", $display) || (empty($display))) {
1547 // Generate hour selection
1548 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1549 for ($idx = 0; $idx <= 23; $idx++) {
1550 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1551 if ($idx == $h) $OUT .= ' selected="selected"';
1552 $OUT .= ">" . $idx."</option>\n";
1554 $OUT .= " </select></td>\n";
1556 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1559 if (ereg('m', $display) || (empty($display))) {
1560 // Generate minute selection
1561 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1562 for ($idx = 0; $idx <= 59; $idx++) {
1563 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1564 if ($idx == $m) $OUT .= ' selected="selected"';
1565 $OUT .= ">" . $idx."</option>\n";
1567 $OUT .= " </select></td>\n";
1569 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1572 if (ereg("s", $display) || (empty($display))) {
1573 // Generate second selection
1574 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1575 for ($idx = 0; $idx <= 59; $idx++) {
1576 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1577 if ($idx == $s) $OUT .= ' selected="selected"';
1578 $OUT .= ">" . $idx."</option>\n";
1580 $OUT .= " </select></td>\n";
1582 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1585 $OUT .= "</table>\n";
1587 // Return generated HTML code
1593 function createTimestampFromSelections ($prefix, $postData) {
1594 // Initial return value
1597 // Do we have a leap year?
1599 $TEST = date('Y', time()) / 4;
1600 $M1 = date('m', time());
1601 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1602 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1603 // First add years...
1604 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1606 $ret += $postData[$prefix."_mo"] * 2628000;
1608 $ret += $postData[$prefix."_we"] * 604800;
1610 $ret += $postData[$prefix."_da"] * 86400;
1612 $ret += $postData[$prefix."_ho"] * 3600;
1614 $ret += $postData[$prefix."_mi"] * 60;
1615 // And at last seconds...
1616 $ret += $postData[$prefix."_se"];
1617 // Return calculated value
1621 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1622 function createFancyTime ($stamp) {
1623 // Get data array with years/months/weeks/days/...
1624 $data = createTimeSelections($stamp, '', '', '', true);
1626 foreach($data as $k => $v) {
1628 // Value is greater than 0 "eval" data to return string
1629 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1634 // Do we have something there?
1635 if (strlen($ret) > 0) {
1636 // Remove leading commata and space
1637 $ret = substr($ret, 2);
1640 $ret = "0 {--_SECONDS--}";
1643 // Return fancy time string
1647 // Generates a navigation row for listing emails
1648 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1649 $SEP = ''; $TOP = '';
1650 if ($show_form === false) {
1652 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1656 for ($page = 1; $page <= $PAGES; $page++) {
1657 // Is the page currently selected or shall we generate a link to it?
1658 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
1659 // Is currently selected, so only highlight it
1660 $NAV .= '<strong>-';
1662 // Open anchor tag and add base URL
1663 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1665 // Add userid when we shall show all mails from a single member
1666 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1668 // Close open anchor tag
1672 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
1673 // Is currently selected, so only highlight it
1674 $NAV .= '-</strong>';
1680 // Add seperator if we have not yet reached total pages
1681 if ($page < $PAGES) $NAV .= ' | ';
1684 // Define constants only once
1685 $content['nav'] = $NAV;
1686 $content['span'] = $colspan;
1687 $content['top'] = $TOP;
1688 $content['sep'] = $SEP;
1690 // Load navigation template
1691 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1693 if ($return === true) {
1694 // Return generated HTML-Code
1702 // Extract host from script name
1703 function extractHostnameFromUrl (&$script) {
1704 // Use default SERVER_URL by default... ;) So?
1705 $url = getConfig('SERVER_URL');
1707 // Is this URL valid?
1708 if (substr($script, 0, 7) == 'http://') {
1709 // Use the hostname from script URL as new hostname
1710 $url = substr($script, 7);
1711 $extract = explode('/', $url);
1713 // Done extracting the URL :)
1716 // Extract host name
1717 $host = str_replace('http://', '', $url);
1718 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1720 // Generate relative URL
1721 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1722 if (substr(strtolower($script), 0, 7) == 'http://') {
1723 // But only if http:// is in front!
1724 $script = substr($script, (strlen($url) + 7));
1725 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1727 $script = substr($script, (strlen($url) + 8));
1730 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1731 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1737 // Send a GET request
1738 function sendGetRequest ($script) {
1739 // Extract host name from script
1740 $host = extractHostnameFromUrl($script);
1742 // Generate GET request header
1743 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1744 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1745 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1746 if (isConfigEntrySet('FULL_VERSION')) {
1747 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1749 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1751 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1752 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1753 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1755 // Send the raw request
1756 $response = sendRawRequest($host, $request);
1758 // Return the result to the caller function
1762 // Send a POST request
1763 function sendPostRequest ($script, $postData) {
1764 // Is postData an array?
1765 if (!is_array($postData)) {
1767 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1768 return array('', '', '');
1771 // Compile the script name
1772 $script = compileCode($script);
1774 // Extract host name from script
1775 $host = extractHostnameFromUrl($script);
1777 // Construct request
1778 $data = http_build_query($postData, '','&');
1780 // Generate POST request header
1781 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1782 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1783 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1784 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1785 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1786 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1787 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1788 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1791 // Send the raw request
1792 $response = sendRawRequest($host, $request);
1794 // Return the result to the caller function
1798 // Sends a raw request to another host
1799 function sendRawRequest ($host, $request) {
1800 // Init errno and errdesc with 'all fine' values
1801 $errno = 0; $errdesc = '';
1804 $response = array('', '', '');
1806 // Default is not to use proxy
1809 // Are proxy settins set?
1810 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1816 //* DEBUG: */ die("SCRIPT=" . $script."<br />");
1817 if ($useProxy === true) {
1818 // Connect to host through proxy connection
1819 $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1821 // Connect to host directly
1822 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1826 if (!is_resource($fp)) {
1832 if ($useProxy === true) {
1833 // Generate CONNECT request header
1834 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1835 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1837 // Use login data to proxy? (username at least!)
1838 if (getConfig('proxy_username') != '') {
1840 $encodedAuth = base64_encode(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
1841 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1844 // Add last new-line
1845 $proxyTunnel .= getConfig('HTTP_EOL');
1846 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1849 fputs($fp, $proxyTunnel);
1853 // No response received
1857 // Read the first line
1858 $resp = trim(fgets($fp, 10240));
1859 $respArray = explode(' ', $resp);
1860 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1861 // Invalid response!
1867 fputs($fp, $request);
1870 while (!feof($fp)) {
1871 $response[] = trim(fgets($fp, 1024));
1877 // Skip first empty lines
1879 foreach ($resp as $idx => $line) {
1881 $line = trim($line);
1883 // Is this line empty?
1886 array_shift($response);
1888 // Abort on first non-empty line
1893 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1895 // Proxy agent found?
1896 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1897 // Proxy header detected, so remove two lines
1898 array_shift($response);
1899 array_shift($response);
1902 // Was the request successfull?
1903 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1904 // Not found / access forbidden
1905 $response = array('', '', '');
1912 // Taken from www.php.net eregi() user comments
1913 function isEmailValid ($email) {
1915 $email = compileCode($email);
1917 // Check first part of email address
1918 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1921 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1924 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1926 // Return check result
1927 return preg_match($regex, $email);
1930 // Function taken from user comments on www.php.net / function eregi()
1931 function isUrlValid ($URL, $compile=true) {
1932 // Trim URL a little
1933 $URL = trim(urldecode($URL));
1934 //* DEBUG: */ outputHtml($URL."<br />");
1936 // Compile some chars out...
1937 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1938 //* DEBUG: */ outputHtml($URL."<br />");
1940 // Check for the extension filter
1941 if (isExtensionActive('filter')) {
1942 // Use the extension's filter set
1943 return FILTER_VALIDATE_URL($URL, false);
1946 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1947 // https:// in front of the URLs
1948 return isUrlValidSimple($URL);
1951 // Generate a list of administrative links to a given userid
1952 function generateMemberAdminActionLinks ($userid, $status = '') {
1953 // Make sure userid is a number
1954 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1956 // Define all main targets
1957 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1959 // Begin of navigation links
1962 foreach ($targetArray as $tar) {
1963 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1964 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1965 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1966 // Locked accounts shall be unlocked
1967 $OUT .= 'UNLOCK_USER';
1969 // All other status is fine
1970 $OUT .= strtoupper($tar);
1972 $OUT .= "_TITLE--}\">{--ADMIN_";
1973 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1974 // Locked accounts shall be unlocked
1975 $OUT .= 'UNLOCK_USER';
1977 // All other status is fine
1978 $OUT .= strtoupper($tar);
1980 $OUT .= "--}</a></span> | ";
1983 // Finish navigation link
1984 $OUT = substr($OUT, 0, -7) . ']';
1990 // Generate an email link
1991 function generateEmailLink ($email, $table = 'admins') {
1992 // Default email link (INSECURE! Spammer can read this by harvester programs)
1993 $EMAIL = 'mailto:' . $email;
1995 // Check for several extensions
1996 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1997 // Create email link for contacting admin in guest area
1998 $EMAIL = generateAdminEmailLink($email);
1999 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2000 // Create email link for contacting a member within admin area (or later in other areas, too?)
2001 $EMAIL = generateUserEmailLink($email, 'admin');
2002 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2003 // Create email link to contact sponsor within admin area (or like the link above?)
2004 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2007 // Shall I close the link when there is no admin?
2008 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2010 // Return email link
2014 // Generate a hash for extra-security for all passwords
2015 function generateHash ($plainText, $salt = '') {
2016 // Is the required extension 'sql_patches' there and a salt is not given?
2017 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches'))) && (empty($salt))) {
2018 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2019 return md5($plainText);
2022 // Do we miss an arry element here?
2023 if (!isConfigEntrySet('file_hash')) {
2025 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2028 // When the salt is empty build a new one, else use the first x configured characters as the salt
2030 // Build server string (inc/databases.php is no longer updated with every commit)
2031 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2034 $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');
2037 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2039 // Calculate number for generating the code
2040 $a = time() + getConfig('_ADD') - 1;
2042 // Generate SHA1 sum from modula of number and the prime number
2043 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2044 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2045 $sha1 = scrambleString($sha1);
2046 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2047 //* DEBUG: */ $sha1b = descrambleString($sha1);
2048 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2050 // Generate the password salt string
2051 $salt = substr($sha1, 0, getConfig('salt_length'));
2052 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2055 $salt = substr($salt, 0, getConfig('salt_length'));
2056 //* DEBUG: */ outputHtml("GIVEN={$salt}<br />");
2060 return $salt.sha1($salt . $plainText);
2063 // Scramble a string
2064 function scrambleString($str) {
2068 // Final check, in case of failture it will return unscrambled string
2069 if (strlen($str) > 40) {
2070 // The string is to long
2072 } elseif (strlen($str) == 40) {
2074 $scrambleNums = explode(':', getConfig('pass_scramble'));
2076 // Generate new numbers
2077 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2080 // Scramble string here
2081 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2082 for ($idx = 0; $idx < strlen($str); $idx++) {
2083 // Get char on scrambled position
2084 $char = substr($str, $scrambleNums[$idx], 1);
2086 // Add it to final output string
2087 $scrambled .= $char;
2090 // Return scrambled string
2091 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2095 // De-scramble a string scrambled by scrambleString()
2096 function descrambleString($str) {
2097 // Scramble only 40 chars long strings
2098 if (strlen($str) != 40) return $str;
2100 // Load numbers from config
2101 $scrambleNums = explode(':', getConfig('pass_scramble'));
2104 if (count($scrambleNums) != 40) return $str;
2106 // Begin descrambling
2107 $orig = str_repeat(' ', 40);
2108 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2109 for ($idx = 0; $idx < 40; $idx++) {
2110 $char = substr($str, $idx, 1);
2111 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2114 // Return scrambled string
2115 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2119 // Generated a "string" for scrambling
2120 function genScrambleString ($len) {
2121 // Prepare array for the numbers
2122 $scrambleNumbers = array();
2124 // First we need to setup randomized numbers from 0 to 31
2125 for ($idx = 0; $idx < $len; $idx++) {
2127 $rand = mt_rand(0, ($len -1));
2129 // Check for it by creating more numbers
2130 while (array_key_exists($rand, $scrambleNumbers)) {
2131 $rand = mt_rand(0, ($len -1));
2135 $scrambleNumbers[$rand] = $rand;
2138 // So let's create the string for storing it in database
2139 $scrambleString = implode(':', $scrambleNumbers);
2140 return $scrambleString;
2143 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2144 function generatePassString ($passHash) {
2145 // Return vanilla password hash
2148 // Is a secret key and master salt already initialized?
2149 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2150 // Only calculate when the secret key is generated
2151 $newHash = ''; $start = 9;
2152 for ($idx = 0; $idx < 10; $idx++) {
2153 $part1 = hexdec(substr($passHash, $start, 4));
2154 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2155 $mod = dechex($idx);
2156 if ($part1 > $part2) {
2157 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2158 } elseif ($part2 > $part1) {
2159 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2161 $mod = substr(round($mod), 0, 4);
2162 $mod = str_repeat('0', 4-strlen($mod)) . $mod;
2163 //* DEBUG: */ outputHtml("*" . $start.'=' . $mod."*<br />");
2168 //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
2169 $ret = generateHash($newHash, getConfig('master_salt'));
2170 //* DEBUG: */ print($ret."<br />");
2173 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2174 $ret = md5($passHash);
2175 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2182 // Fix "deleted" cookies
2183 function fixDeletedCookies ($cookies) {
2184 // Is this an array with entries?
2185 if ((is_array($cookies)) && (count($cookies) > 0)) {
2186 // Then check all cookies if they are marked as deleted!
2187 foreach ($cookies as $cookieName) {
2188 // Is the cookie set to "deleted"?
2189 if (getSession($cookieName) == 'deleted') {
2190 setSession($cookieName, '');
2196 // Output error messages in a fasioned way and die...
2197 function app_die ($F, $L, $message) {
2198 // Check if Script is already dieing and not let it kill itself another 1000 times
2199 if (!isset($GLOBALS['app_died'])) {
2200 // Make sure, that the script realy realy diese here and now
2201 $GLOBALS['app_died'] = true;
2204 loadIncludeOnce('inc/header.php');
2206 // Rewrite message for output
2207 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2209 // Better log this message away
2210 logDebugMessage($F, $L, $message);
2212 // Load the message template
2213 loadTemplate('admin_settings_saved', false, $message);
2216 loadIncludeOnce('inc/footer.php');
2218 // Script tried to kill itself twice
2219 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2223 // Display parsing time and number of SQL queries in footer
2224 function displayParsingTime() {
2225 // Is the timer started?
2226 if (!isset($GLOBALS['startTime'])) {
2232 $endTime = microtime(true);
2234 // "Explode" both times
2235 $start = explode(' ', $GLOBALS['startTime']);
2236 $end = explode(' ', $endTime);
2237 $runTime = $end[0] - $start[0];
2238 if ($runTime < 0) $runTime = 0;
2242 'runtime' => translateComma($runTime),
2243 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2246 // Load the template
2247 loadTemplate('show_timings', false, $content);
2250 // Check wether a boolean constant is set
2251 // Taken from user comments in PHP documentation for function constant()
2252 function isBooleanConstantAndTrue ($constName) { // : Boolean
2253 // Failed by default
2257 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2259 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2260 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2263 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2264 if (defined($constName)) {
2266 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2267 $res = (constant($constName) === true);
2271 $GLOBALS['cache_array']['const'][$constName] = $res;
2273 //* DEBUG: */ var_dump($res);
2279 // Checks if a given apache module is loaded
2280 function isApacheModuleLoaded ($apacheModule) {
2281 // Check it and return result
2282 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2285 // Get current theme name
2286 function getCurrentTheme () {
2287 // The default theme is 'default'... ;-)
2290 // Load default theme if not empty from configuration
2291 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2293 if (!isSessionVariableSet('mxchange_theme')) {
2294 // Set default theme
2296 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2297 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2298 // Get theme from cookie
2299 $ret = getSession('mxchange_theme');
2302 if (getThemeId($ret) == 0) {
2303 // Fix it to default
2306 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2307 // Prepare FQFN for checking
2308 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2310 // Installation mode active
2311 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2312 // Set cookie from URL data
2313 setTheme(getRequestElement('theme'));
2314 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2315 // Set cookie from posted data
2316 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2320 $ret = getSession('mxchange_theme');
2322 // Invalid design, reset cookie
2326 // Return theme value
2330 // Setter for theme in session
2331 function setTheme ($newTheme) {
2332 setSession('mxchange_theme', $newTheme);
2335 // Get id from theme
2336 // @TODO Try to move this to inc/libs/theme_functions.php
2337 function getThemeId ($name) {
2338 // Is the extension 'theme' installed?
2339 if (!isExtensionActive('theme')) {
2347 // Is the cache entry there?
2348 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2349 // Get the version from cache
2350 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2353 incrementStatsEntry('cache_hits');
2354 } elseif (getExtensionVersion('cache') != '0.1.8') {
2355 // Check if current theme is already imported or not
2356 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2357 array($name), __FUNCTION__, __LINE__);
2360 if (SQL_NUMROWS($result) == 1) {
2362 list($id) = SQL_FETCHROW($result);
2366 SQL_FREERESULT($result);
2373 // Generates an error code from given account status
2374 function generateErrorCodeFromUserStatus ($status) {
2375 // @TODO The status should never be empty
2376 if (empty($status)) {
2377 // Something really bad happend here
2378 debug_report_bug(__FUNCTION__ . ': status is empty.');
2381 // Default error code if unknown account status
2382 $errorCode = getCode('UNKNOWN_STATUS');
2384 // Generate constant name
2385 $constantName = sprintf("ID_%s", $status);
2387 // Is the constant there?
2388 if (isCodeSet($constantName)) {
2390 $errorCode = getCode($constantName);
2393 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2396 // Return error code
2400 // Function to search for the last modifified file
2401 function searchDirsRecursive ($dir, &$last_changed) {
2403 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />");
2404 // Does it match what we are looking for? (We skip a lot files already!)
2405 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2406 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2407 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2408 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />");
2410 // Walk through all entries
2411 foreach ($ds as $d) {
2412 // Generate proper FQFN
2413 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2415 // Is it a file and readable?
2416 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2417 if (isDirectory($FQFN)) {
2418 // $FQFN is a directory so also crawl into this directory
2420 if (!empty($dir)) $newDir = $dir . '/'. $d;
2421 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />");
2422 searchDirsRecursive($newDir, $last_changed);
2423 } elseif (isFileReadable($FQFN)) {
2424 // $FQFN is a filename and no directory
2425 $time = filemtime($FQFN);
2426 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2427 if ($last_changed['time'] < $time) {
2428 // This file is newer as the file before
2429 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2430 $last_changed['path_name'] = $FQFN;
2431 $last_changed['time'] = $time;
2437 // "Getter" for revision/version data
2438 function getActualVersion ($type = 'Revision') {
2439 // By default nothing is new... ;-)
2442 // Is the cache entry there?
2443 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2444 // Found so increase cache hit
2445 incrementStatsEntry('cache_hits');
2448 return $GLOBALS['cache_array']['revision'][$type][0];
2450 // FQFN of revision file
2451 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2453 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2454 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2455 // Forced rebuild of .revision file
2458 // Check for revision file
2459 if (!isFileReadable($FQFN)) {
2460 // Not found, so we need to create it
2463 // Revision file found
2464 $ins_vers = explode("\n", readFromFile($FQFN));
2466 // Get array for mapping information
2467 $mapper = array_flip(getSearchFor());
2468 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2470 // Is the content valid?
2471 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2472 // File needs update!
2475 // Generate fake cache entry
2476 foreach ($mapper as $map=>$idx) {
2477 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2480 // Return found value
2481 return trim($ins_vers[$mapper[$type]]);
2486 // Has it been updated?
2487 if ($new === true) {
2489 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2491 // ... and call recursive
2492 return getActualVersion($type);
2497 // Repares an array we are looking for
2498 // 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
2499 function getSearchFor () {
2500 // Add Revision, Date, Tag and Author
2501 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2503 // Return the created array
2507 // @TODO Please describe this function
2508 function getArrayFromActualVersion () {
2512 // Directory to start with search
2513 $last_changed = array(
2518 // Init return array
2519 $akt_vers = array();
2521 // Init value for counting the founded keywords
2524 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2525 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2528 $last_file = readFromFile($last_changed['path_name']);
2530 // Get all the keywords to search for
2531 $searchFor = getSearchFor();
2533 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2534 foreach ($searchFor as $search) {
2535 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2536 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2537 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2538 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2541 // Save the last-changed filename for debugging
2542 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2544 // at least 3 keyword-Tags are needed for propper values
2545 if ($res && $res >= 3
2546 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2547 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2548 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2549 // Prepare content witch need special treadment
2551 // Prepare timestamp for date
2552 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2553 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2555 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2556 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2557 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2561 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2562 $version = sendGetRequest('check-updates3.php');
2565 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2566 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2567 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2568 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2569 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2570 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2573 // Return prepared array
2574 return $GLOBALS['cache_array']['revision'];
2577 // Back-ported from the new ship-simu engine. :-)
2578 function debug_get_printable_backtrace () {
2580 $backtrace = "<ol>\n";
2582 // Get and prepare backtrace for output
2583 $backtraceArray = debug_backtrace();
2584 foreach ($backtraceArray as $key => $trace) {
2585 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2586 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2587 if (!isset($trace['args'])) $trace['args'] = array();
2588 $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";
2592 $backtrace .= "</ol>\n";
2594 // Return the backtrace
2598 // Output a debug backtrace to the user
2599 function debug_report_bug ($message = '') {
2603 // Is the optional message set?
2604 if (!empty($message)) {
2606 $debug = sprintf("Note: %s<br />\n",
2610 // @TODO Add a little more infos here
2611 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2615 $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>";
2616 $debug .= debug_get_printable_backtrace();
2617 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2618 $debug .= "Thank you for finding bugs.";
2621 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2625 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2626 function generateSeed () {
2627 list($usec, $sec) = explode(' ', microtime());
2628 $microTime = (((float)$sec + (float)$usec)) * 100000;
2632 // Converts a message code to a human-readable message
2633 function getMessageFromErrorCode ($code) {
2637 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2638 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2639 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2640 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2641 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2642 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2643 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2644 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2645 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2646 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2647 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2648 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2649 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2650 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2651 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2652 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2653 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2654 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2655 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2656 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2657 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), '0'); break;
2658 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2659 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2660 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2661 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2662 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2663 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2664 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2666 case getCode('ERROR_MAILID'):
2667 if (isExtensionActive('mailid', true)) {
2668 $message = getMessage('ERROR_CONFIRMING_MAIL');
2670 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2674 case getCode('EXTENSION_PROBLEM'):
2675 if (isGetRequestElementSet('ext')) {
2676 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2678 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2682 case getCode('URL_TLOCK'):
2683 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2684 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2686 // Load timestamp from last order
2687 list($timestamp) = SQL_FETCHROW($result);
2688 $timestamp = generateDateTime($timestamp, '1');
2691 SQL_FREERESULT($result);
2693 // Calculate hours...
2694 $STD = round(getConfig('url_tlock') / 60 / 60);
2697 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2700 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2702 // Finally contruct the message
2703 // @TODO Rewrite this old lost code to a template
2704 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2705 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2706 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2710 // Missing/invalid code
2711 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2714 logDebugMessage(__FUNCTION__, __LINE__, $message);
2718 // Return the message
2722 // Generate a "link" for the given admin id (admin_id)
2723 function generateAdminLink ($adminId) {
2724 // No assigned admin is default
2725 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2727 // Zero? = Not assigned
2728 if (bigintval($adminId) > 0) {
2729 // Load admin's login
2730 $login = getAdminLogin($adminId);
2732 // Is the login valid?
2733 if ($login != '***') {
2734 // Is the extension there?
2735 if (isExtensionActive('admins')) {
2737 $admin = "<a href=\"".generateEmailLink(getAdminEmail($adminId), 'admins')."\">" . $login."</a>";
2739 // Extension not found
2740 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2744 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $adminId)."</div>";
2752 // Compile characters which are allowed in URLs
2753 function compileUriCode ($code, $simple = true) {
2754 // Compile constants
2755 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2757 // Compile QUOT and other non-HTML codes
2758 $code = str_replace('{DOT}', '.',
2759 str_replace('{SLASH}', '/',
2760 str_replace('{QUOT}', "'",
2761 str_replace('{DOLLAR}', '$',
2762 str_replace('{OPEN_ANCHOR}', '(',
2763 str_replace('{CLOSE_ANCHOR}', ')',
2764 str_replace('{OPEN_SQR}', '[',
2765 str_replace('{CLOSE_SQR}', ']',
2766 str_replace('{PER}', '%',
2770 // Return compiled code
2774 // Function taken from user comments on www.php.net / function eregi()
2775 function isUrlValidSimple ($url) {
2777 $url = secureString(str_replace("\\", '', compileCode(urldecode($url))));
2779 // Allows http and https
2780 $http = "(http|https)+(:\/\/)";
2782 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2783 // Test double-domains (e.g. .de.vu)
2784 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2786 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2788 $dir = "((/)+([-_\.[:alnum:]])+)*";
2790 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2791 // ... and the string after and including question character
2792 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2793 // Pattern for URLs like http://url/dir/doc.html?var=value
2794 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2795 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2796 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2797 // Pattern for URLs like http://url/dir/?var=value
2798 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2799 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2800 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2801 // Pattern for URLs like http://url/dir/page.ext
2802 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2803 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2804 $pattern['ipdp'] = $http . $ip . $dir . $page;
2805 // Pattern for URLs like http://url/dir
2806 $pattern['d1d'] = $http . $domain1 . $dir;
2807 $pattern['d2d'] = $http . $domain2 . $dir;
2808 $pattern['ipd'] = $http . $ip . $dir;
2809 // Pattern for URLs like http://url/?var=value
2810 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2811 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2812 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2813 // Pattern for URLs like http://url?var=value
2814 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2815 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2816 $pattern['ipg12'] = $http . $ip . $getstring1;
2817 // Test all patterns
2819 foreach ($pattern as $key => $pat) {
2821 if (isDebugRegExpressionEnabled()) {
2822 // @TODO Are these convertions still required?
2823 $pat = str_replace('.', "\.", $pat);
2824 $pat = str_replace('@', "\@", $pat);
2825 //* DEBUG: */ outputHtml($key."= " . $pat . "<br />");
2828 // Check if expression matches
2829 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2832 if ($reg === true) break;
2835 // Return true/false
2839 // Wtites data to a config.php-style file
2840 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2841 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2842 // Initialize some variables
2848 // Is the file there and read-/write-able?
2849 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2850 $search = 'CFG: ' . $comment;
2851 $tmp = $FQFN . '.tmp';
2853 // Open the source file
2854 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2856 // Is the resource valid?
2857 if (is_resource($fp)) {
2858 // Open temporary file
2859 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2861 // Is the resource again valid?
2862 if (is_resource($fp_tmp)) {
2863 // Mark temporary file as readable
2864 $GLOBALS['file_readable'][$tmp] = true;
2867 while (!feof($fp)) {
2868 // Read from source file
2869 $line = fgets ($fp, 1024);
2871 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2874 if ($next === $seek) {
2876 $line = $prefix . $DATA . $suffix . "\n";
2882 // Write to temp file
2883 fputs($fp_tmp, $line);
2889 // Finished writing tmp file
2893 // Close source file
2896 if (($done === true) && ($found === true)) {
2897 // Copy back tmp file and delete tmp :-)
2898 copyFileVerified($tmp, $FQFN, 0644);
2899 return removeFile($tmp);
2900 } elseif ($found === false) {
2901 outputHtml('<strong>CHANGE:</strong> 404!');
2903 outputHtml('<strong>TMP:</strong> UNDONE!');
2907 // File not found, not readable or writeable
2908 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2911 // An error was detected!
2914 // Send notification to admin
2915 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2916 if (getExtensionVersion('admins') >= '0.4.1') {
2918 sendAdminsEmails($subject, $templateName, $content, $userid);
2920 // Send out out-dated way
2921 $message = loadEmailTemplate($templateName, $content, $userid);
2922 sendAdminEmails($subject, $message);
2926 // Debug message logger
2927 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2928 // Is debug mode enabled?
2929 if ((isDebugModeEnabled()) || ($force === true)) {
2931 $message = str_replace("\r", '', str_replace("\n", '', $message));
2933 // Log this message away, we better don't call app_die() here to prevent an endless loop
2934 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2935 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2940 // Handle extra values
2941 function handleExtraValues ($filterFunction, $value, $extraValue) {
2942 // Default is the value itself
2945 // Do we have a special filter function?
2946 if (!empty($filterFunction)) {
2947 // Does the filter function exist?
2948 if (function_exists($filterFunction)) {
2949 // Do we have extra parameters here?
2950 if (!empty($extraValue)) {
2951 // Put both parameters in one new array by default
2952 $args = array($value, $extraValue);
2954 // If we have an array simply use it and pre-extend it with our value
2955 if (is_array($extraValue)) {
2956 // Make the new args array
2957 $args = merge_array(array($value), $extraValue);
2960 // Call the multi-parameter call-back
2961 $ret = call_user_func_array($filterFunction, $args);
2963 // One parameter call
2964 $ret = call_user_func($filterFunction, $value);
2973 // Converts timestamp selections into a timestamp
2974 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2975 // Init test variable
2978 // Get last three chars
2979 $test = substr($id, -3);
2981 // Improved way of checking! :-)
2982 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2983 // Found a multi-selection for timings?
2984 $test = substr($id, 0, -3);
2985 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)) {
2986 // Generate timestamp
2987 $postData[$test] = createTimestampFromSelections($test, $postData);
2988 $DATA[] = sprintf("%s='%s'", $test, $postData[$test]);
2990 // Remove data from array
2991 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2992 unset($postData[$test.'_' . $rem]);
2996 unset($id); $skip = true; $test2 = $test;
2999 // Process this entry
3005 // Reverts the german decimal comma into Computer decimal dot
3006 function convertCommaToDot ($str) {
3007 // Default float is not a float... ;-)
3010 // Which language is selected?
3011 switch (getLanguage()) {
3012 case 'de': // German language
3013 // Remove german thousand dots first
3014 $str = str_replace('.', '', $str);
3016 // Replace german commata with decimal dot and cast it
3017 $float = (float)str_replace(',', '.', $str);
3020 default: // US and so on
3021 // Remove thousand dots first and cast
3022 $float = (float)str_replace(',', '', $str);
3030 // Handle menu-depending failed logins and return the rendered content
3031 function handleLoginFailtures ($accessLevel) {
3032 // Default output is empty ;-)
3035 // Is the session data set?
3036 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3037 // Ignore zero values
3038 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3039 // Non-guest has login failures found, get both data and prepare it for template
3040 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3042 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3043 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), '2')
3047 $OUT = loadTemplate('login_failures', true, $content);
3050 // Reset session data
3051 setSession('mxchange_' . $accessLevel.'_failures', '');
3052 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3055 // Return rendered content
3060 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3062 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3064 // Shall I remove the cache file?
3065 if (isCacheInstanceValid()) {
3067 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3069 $GLOBALS['cache_instance']->removeCacheFile($force);
3072 // Include file given?
3075 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3077 // Is the include there?
3078 if (isIncludeReadable($inc)) {
3079 // And rebuild it from scratch
3080 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3083 // Include not found!
3084 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3090 // Determines the real remote address
3091 function determineRealRemoteAddress () {
3092 // Is a proxy in use?
3093 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3095 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3096 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3097 // Yet, another proxy
3098 $address = $_SERVER['HTTP_CLIENT_IP'];
3100 // The regular address when no proxy was used
3101 $address = $_SERVER['REMOTE_ADDR'];
3104 // This strips out the real address from proxy output
3105 if (strstr($address, ',')) {
3106 $addressArray = explode(',', $address);
3107 $address = $addressArray[0];
3110 // Return the result
3114 // Adds a bonus mail to the queue
3115 // This is a high-level function!
3116 function addNewBonusMail ($data, $mode = '', $output=true) {
3117 // Use mode from data if not set and availble ;-)
3118 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3120 // Generate receiver list
3121 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3124 if (!empty($RECEIVER)) {
3125 // Add bonus mail to queue
3126 addBonusMailToQueue(
3138 // Mail inserted into bonus pool
3139 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3140 } elseif ($output) {
3141 // More entered than can be reached!
3142 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3145 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3149 // Determines referal id and sets it
3150 function determineReferalId () {
3151 // Skip this in non-html-mode
3152 if (getOutputMode() != '0') return false;
3154 // Check if refid is set
3155 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3157 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3158 // The variable user comes from the click-counter script click.php and we only accept this here
3159 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3160 } elseif (isPostRequestElementSet('refid')) {
3161 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3162 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3163 } elseif (isGetRequestElementSet('refid')) {
3164 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3165 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3166 } elseif (isGetRequestElementSet('ref')) {
3167 // Set refid=ref (the referal link uses such variable)
3168 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3169 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3170 // Set session refid als global
3171 $GLOBALS['refid'] = bigintval(getSession('refid'));
3172 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3173 // Select a random user which has confirmed enougth mails
3174 $GLOBALS['refid'] = determineRandomReferalId();
3175 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3176 // Set default refid as refid in URL
3177 $GLOBALS['refid'] = getConfig('def_refid');
3179 // No default ID when sql_patches is not installed or none set
3180 $GLOBALS['refid'] = 0;
3183 // Set cookie when default refid > 0
3184 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3186 setSession('refid', $GLOBALS['refid']);
3189 // Return determined refid
3190 return $GLOBALS['refid'];
3193 // Enables the reset mode and runs it
3194 function doReset () {
3195 // Enable the reset mode
3196 $GLOBALS['reset_enabled'] = true;
3199 runFilterChain('reset');
3202 // Our shutdown-function
3203 function shutdown () {
3204 // Call the filter chain 'shutdown'
3205 runFilterChain('shutdown', null);
3207 if (SQL_IS_LINK_UP()) {
3209 SQL_CLOSE(__FILE__, __LINE__);
3210 } elseif (!isInstallationPhase()) {
3212 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3215 // Stop executing here
3219 // Setter for userid
3220 function setUserId ($userid) {
3221 $GLOBALS['userid'] = bigintval($userid);
3224 // Getter for userid or returns zero
3225 function getUserId () {
3229 // Is the userid set?
3230 if (isUserIdSet()) {
3232 $userid = $GLOBALS['userid'];
3239 // Checks ether the userid is set
3240 function isUserIdSet () {
3241 return (isset($GLOBALS['userid']));
3244 // Handle message codes from URL
3245 function handleCodeMessage () {
3246 if (isGetRequestElementSet('code')) {
3247 // Default extension is 'unknown'
3250 // Is extension given?
3251 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3253 // Convert the 'code' parameter from URL to a human-readable message
3254 $message = getMessageFromErrorCode(getRequestElement('code'));
3256 // Load message template
3257 loadTemplate('message', false, $message);
3261 // Setter for extra title
3262 function setExtraTitle ($extraTitle) {
3263 $GLOBALS['extra_title'] = $extraTitle;
3266 // Getter for extra title
3267 function getExtraTitle () {
3268 // Is the extra title set?
3269 if (!isExtraTitleSet()) {
3270 // No, then abort here
3271 debug_report_bug('extra_title is not set!');
3275 return $GLOBALS['extra_title'];
3278 // Checks if the extra title is set
3279 function isExtraTitleSet () {
3280 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3283 // Generates a 'extension foo inactive' message
3284 function generateExtensionInactiveMessage ($ext_name) {
3285 // Is the extension empty?
3286 if (empty($ext_name)) {
3287 // This should not happen
3288 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3292 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3294 // Is an admin logged in?
3296 // Then output admin message
3297 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3300 // Return prepared message
3304 // Generates a 'extension foo not installed' message
3305 function generateExtensionNotInstalledMessage ($ext_name) {
3306 // Is the extension empty?
3307 if (empty($ext_name)) {
3308 // This should not happen
3309 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3313 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3315 // Is an admin logged in?
3317 // Then output admin message
3318 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3321 // Return prepared message
3325 // Generates a message depending on if the extension is not installed or not
3327 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3331 // Is the extension not installed or just deactivated?
3332 switch (isExtensionInstalled($ext_name)) {
3333 case true; // Deactivated!
3334 $message = generateExtensionInactiveMessage($ext_name);
3337 case false; // Not installed!
3338 $message = generateExtensionNotInstalledMessage($ext_name);
3341 default: // Should not happen!
3342 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3343 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3347 // Return the message
3351 // Reads a directory recursively by default and searches for files not matching
3352 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3353 // a whole directory.
3354 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3355 // Add default entries we should exclude
3356 $excludeArray[] = '.';
3357 $excludeArray[] = '..';
3358 $excludeArray[] = '.svn';
3359 $excludeArray[] = '.htaccess';
3361 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3366 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3369 while ($baseFile = readdir($dirPointer)) {
3370 // Exclude '.', '..' and entries in $excludeArray automatically
3371 if (in_array($baseFile, $excludeArray, true)) {
3373 //* DEBUG: */ outputHtml('excluded=' . $baseFile . "<br />");
3377 // Construct include filename and FQFN
3378 $fileName = $baseDir . $baseFile;
3379 $FQFN = getConfig('PATH') . $fileName;
3381 // Remove double slashes
3382 $FQFN = str_replace('//', '/', $FQFN);
3384 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3385 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3386 // These Lines are only for debugging!!
3387 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . "<br />");
3388 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . "<br />");
3389 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . "<br />");
3395 // Skip also files with non-matching prefix genericly
3396 if (($recursive === true) && (isDirectory($FQFN))) {
3397 // Is a redirectory so read it as well
3398 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3400 // And skip further processing
3402 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3404 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3406 } elseif (!isFileReadable($FQFN)) {
3407 // Not readable so skip it
3408 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3412 // Is the file a PHP script or other?
3413 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3414 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3415 // Is this a valid include file?
3416 if ($extension == '.php') {
3417 // Remove both for extension name
3418 $extName = substr($baseFile, strlen($prefix), -4);
3420 // Is the extension valid and active?
3421 if (isExtensionNameValid($extName)) {
3422 // Then add this file
3423 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3424 $files[] = $fileName;
3426 // Add non-extension files as well
3427 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3428 if ($addBaseDir === true) {
3429 $files[] = $fileName;
3431 $files[] = $baseFile;
3435 // We found .php file but should not search for them, why?
3436 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3438 } elseif (substr($baseFile, -4, 4) == $extension) {
3439 // Other, generic file found
3440 $files[] = $fileName;
3445 closedir($dirPointer);
3450 // Return array with include files
3451 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3455 // Maps a module name into a database table name
3456 function mapModuleToTable ($moduleName) {
3457 // Map only these, still lame code...
3458 switch ($moduleName) {
3459 // 'index' is the guest's menu
3460 case 'index': $moduleName = 'guest'; break;
3461 // ... and 'login' the member's menu
3462 case 'login': $moduleName = 'member'; break;
3463 // Anything else will not be mapped, silently.
3470 // Add SQL debug data to array for later output
3471 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3472 // Don't execute anything here if we don't need
3473 if (getConfig('display_debug_sqls') != 'Y') return;
3477 'num_rows' => SQL_NUMROWS($result),
3478 'affected' => SQL_AFFECTEDROWS(),
3479 'sql_str' => $sqlString,
3480 'timing' => $timing,
3481 'file' => basename($F),
3486 $GLOBALS['debug_sqls'][] = $record;
3489 // Initializes the cache instance
3490 function initCacheInstance () {
3491 // Load include for CacheSystem class
3492 loadIncludeOnce('inc/classes/cachesystem.class.php');
3494 // Initialize cache system only when it's needed
3495 $GLOBALS['cache_instance'] = new CacheSystem();
3496 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3497 // Failed to initialize cache sustem
3498 addFatalMessage(__FILE__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_CANNOT_INITIALIZE'));
3502 // Getter for message from array or raw message
3503 function getMessageFromIndexedArray ($message, $pos, $array) {
3504 // Check if the requested message was found in array
3505 if (isset($array[$pos])) {
3506 // ... if yes then use it!
3507 $ret = $array[$pos];
3509 // ... else use default message
3517 // Handles fatal errors
3518 function handleFatalErrors () {
3519 // Do we have errors to handle and right output mode?
3520 if ((getTotalFatalErrors() == 0) || (getOutputMode() != 0)) {
3521 // Abort executing here
3526 setContentType('text/html');
3529 loadIncludeOnce('inc/load_config.php');
3531 // Set unset variable
3532 if (empty($check)) $check = '';
3537 // Installation phase or regular mode?
3538 if ((isInstallationPhase())) {
3539 // While we are installing ouput other header than while it is installed... :-)
3541 foreach (getFatalArray() as $key => $value) {
3542 // Prepare content for the template
3544 'key' => ($key + 1),
3548 // Load row template
3549 $OUT .= loadTemplate('install_fatal_row', true, $content);
3552 // Load main template
3553 $content = loadTemplate('install_fatal_table', true, $OUT);
3554 } elseif (isInstalled()) {
3555 // Display all runtime fatal errors
3557 foreach (getFatalArray() as $key => $value) {
3558 // Prepare content for the template
3560 'key' => ($key + 1),
3564 // Load row template
3565 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
3568 // Load main template
3569 $content = loadTemplate('runtime_fatal_table', true, $OUT);
3572 // Message to regular users (non-admin)
3573 $CORR = getMessage('FATAL_REPORT_ERRORS');
3575 // PHP warnings fixed
3576 if ($check == 'done') {
3577 if (isAdmin()) $CORR = getMessage('FATAL_CORRECT_ERRORS');
3580 // Remember all in array
3587 loadIncludeOnce('inc/header.php');
3589 // Load main template
3590 loadTemplate('fatal_errors', false, $content);
3592 // Delete all to prevent double-display
3593 initFatalMessages();
3596 loadIncludeOnce('inc/footer.php');
3602 //////////////////////////////////////////////////
3603 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3604 //////////////////////////////////////////////////
3606 if (!function_exists('html_entity_decode')) {
3607 // Taken from documentation on www.php.net
3608 function html_entity_decode ($string) {
3609 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3610 $trans_tbl = array_flip($trans_tbl);
3611 return strtr($string, $trans_tbl);