2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/25/2003 *
4 * =============== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
44 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
45 function outputHtml ($htmlCode, $newLine = true) {
47 $username = getMessage('USERNAME_UNKNOWN');
48 if (isset($GLOBALS['username'])) $username = getUsername();
50 // Do we have HTML-Code here?
51 if (!empty($htmlCode)) {
52 // Yes, so we handle it as you have configured
53 switch (getConfig('OUTPUT_MODE')) {
55 // That's why you don't need any \n at the end of your HTML code... :-)
56 if (getPhpCaching() == 'on') {
57 // Output into PHP's internal buffer
58 outputRawCode($htmlCode);
60 // That's why you don't need any \n at the end of your HTML code... :-)
61 if ($newLine === true) print("\n");
63 // Render mode for old or lame servers...
64 $GLOBALS['output'] .= $htmlCode;
66 // That's why you don't need any \n at the end of your HTML code... :-)
67 if ($newLine === true) $GLOBALS['output'] .= "\n";
72 // If we are switching from render to direct output rendered code
73 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
75 // The same as above... ^
76 outputRawCode($htmlCode);
77 if ($newLine) print("\n");
81 // Huh, something goes wrong or maybe you have edited config.php ???
82 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
85 } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
86 // Headers already sent?
89 logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
91 // Trigger an user error
92 debug_report_bug('Headers are already sent!');
95 // Output cached HTML code
96 $GLOBALS['output'] = ob_get_contents();
98 // Clear output buffer for later output if output is found
99 if (!empty($GLOBALS['output'])) {
104 sendHeader('HTTP/1.1 200');
107 $now = gmdate('D, d M Y H:i:s') . ' GMT';
109 // General headers for no caching
110 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
111 sendHeader('Last-Modified: ' . $now);
112 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
113 sendHeader('Pragma: no-cache'); // HTTP/1.0
114 sendHeader('Connection: Close');
115 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
116 sendHeader('Content-language: ' . getLanguage());
118 // Extension 'rewrite' installed?
119 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
120 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
126 // Compile and run finished rendered HTML code
127 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
128 // Prepare the content and eval() it...
133 $eval = "\$newContent = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";";
136 // Was that eval okay?
137 if (empty($newContent)) {
138 // Something went wrong!
139 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>');
141 $GLOBALS['output'] = $newContent;
147 // Output code here, DO NOT REMOVE! ;-)
148 outputRawCode($GLOBALS['output']);
149 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
150 // Rewrite links when rewrite extension is active
151 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
152 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
155 // Compile and run finished rendered HTML code
156 while (strpos($GLOBALS['output'], '{!') > 0) {
157 eval("\$GLOBALS['output'] = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";");
160 // Output code here, DO NOT REMOVE! ;-)
161 outputRawCode($GLOBALS['output']);
165 // Output the raw HTML code
166 function outputRawCode ($htmlCode) {
167 // Output stripped HTML code to avoid broken JavaScript code, etc.
168 print(stripslashes(stripslashes($htmlCode)));
170 // Flush the output if only getPhpCaching() is not 'on'
171 if (getPhpCaching() != 'on') {
177 // Init fatal message array
178 function initFatalMessages () {
179 $GLOBALS['fatal_messages'] = array();
182 // Getter for whole fatal error messages
183 function getFatalArray () {
184 return $GLOBALS['fatal_messages'];
187 // Add a fatal error message to the queue array
188 function addFatalMessage ($F, $L, $message, $extra='') {
189 if (is_array($extra)) {
190 // Multiple extras for a message with masks
191 $message = call_user_func_array('sprintf', $extra);
192 } elseif (!empty($extra)) {
193 // $message is text with a mask plus extras to insert into the text
194 $message = sprintf($message, $extra);
197 // Add message to $GLOBALS['fatal_messages']
198 $GLOBALS['fatal_messages'][] = $message;
200 // Log fatal messages away
201 debug_report_bug($message);
202 logDebugMessage($F, $L, " message={$message}");
205 // Getter for total fatal message count
206 function getTotalFatalErrors () {
210 // Do we have at least the first entry?
211 if (!empty($GLOBALS['fatal_messages'][0])) {
213 $count = count($GLOBALS['fatal_messages']);
220 // Load a template file and return it's content (only it's name; do not use ' or ")
221 function loadTemplate ($template, $return=false, $content=array()) {
222 // @TODO Remove this sanity-check if all is fine
223 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
225 // @TODO Try to rewrite all $DATA to $content
229 if (!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 (getOutputMode() == 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);
532 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode(smartAddSlashes($GLOBALS['tpl_content']))."\");";
533 eval($GLOBALS['tpl_content']);
534 } elseif (!empty($template)) {
535 // Template file not found!
536 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
537 {--TEMPLATE_CONTENT--}
538 <pre>".print_r($content, true)."</pre>
540 <pre>".print_r($DATA, true)."</pre>
543 // Debug mode not active? Then remove the HTML tags
544 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
546 // No template name supplied!
547 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
550 // Is there some content?
551 if (empty($newContent)) {
553 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
554 // Add last error if the required function exists
555 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
558 // Remove content and data
562 // Compile the code and eval it
563 $eval = '$newContent = "' . compileCode(smartAddSlashes($newContent)) . '";';
570 // Send mail out to an email address
571 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
572 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
574 // Compile subject line (for POINTS constant etc.)
575 eval("\$subject = decodeEntities(\"".compileCode(smartAddSlashes($subject))."\");");
578 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
579 // Value detected, is the message extension installed?
580 // @TODO Extension 'msg' does not exist
581 if (isExtensionActive('msg')) {
582 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
585 // Load email address
586 $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
587 array(bigintval($toEmail)), __FUNCTION__, __LINE__);
588 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email).'<br />');
590 // Does the user exist?
591 if (SQL_NUMROWS($result_email)) {
592 // Load email address
593 list($toEmail) = SQL_FETCHROW($result_email);
596 $toEmail = getConfig('WEBMASTER');
600 SQL_FREERESULT($result_email);
602 } elseif ($toEmail == '0') {
604 $toEmail = getConfig('WEBMASTER');
606 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
608 // Check for PHPMailer or debug-mode
609 if (!checkPhpMailerUsage()) {
610 // Not in PHPMailer-Mode
611 if (empty($mailHeader)) {
612 // Load email header template
613 $mailHeader = loadEmailTemplate('header');
616 $mailHeader .= loadEmailTemplate('header');
618 } elseif (isDebugModeEnabled()) {
619 if (empty($mailHeader)) {
620 // Load email header template
621 $mailHeader = loadEmailTemplate('header');
624 $mailHeader .= loadEmailTemplate('header');
629 eval("\$toEmail = \"".compileCode(smartAddSlashes($toEmail))."\";");
632 eval("\$message = \"".compileCode(smartAddSlashes($message))."\";");
634 // Fix HTML parameter (default is no!)
635 if (empty($isHtml)) $isHtml = 'N';
636 if (isDebugModeEnabled()) {
637 // In debug mode we want to display the mail instead of sending it away so we can debug this part
639 Headers : ' . str_replace('<', '<', str_replace('>', '>', htmlentities(trim($mailHeader)))) . '
640 To : ' . $toEmail . '
641 Subject : ' . $subject . '
642 Message : ' . $message . '
644 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
645 // Send mail as HTML away
646 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
647 } elseif (!empty($toEmail)) {
649 sendRawEmail($toEmail, $subject, $message, $mailHeader);
650 } elseif ($isHtml != 'Y') {
652 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
656 // Check if legacy or PHPMailer command
657 // @TODO Rewrite this to an extension 'smtp'
659 function checkPhpMailerUsage() {
660 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
663 // Send out a raw email with PHPMailer class or legacy mail() command
664 function sendRawEmail ($toEmail, $subject, $message, $from) {
665 // Shall we use PHPMailer class or legacy mode?
666 if (checkPhpMailerUsage()) {
667 // Use PHPMailer class with SMTP enabled
668 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
669 loadIncludeOnce('inc/phpmailer/class.smtp.php');
672 $mail = new PHPMailer();
674 // Set charset to UTF-8
675 $mail->CharSet('UTF-8');
677 // Path for PHPMailer
678 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
681 $mail->SMTPAuth = true;
682 $mail->Host = getConfig('SMTP_HOSTNAME');
684 $mail->Username = getConfig('SMTP_USER');
685 $mail->Password = getConfig('SMTP_PASSWORD');
687 $mail->From = getConfig('WEBMASTER');
691 $mail->FromName = getConfig('MAIN_TITLE');
692 $mail->Subject = $subject;
693 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
694 $mail->Body = $message;
695 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
696 $mail->WordWrap = 70;
699 $mail->Body = decodeEntities($message);
701 $mail->AddAddress($toEmail, '');
702 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
703 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
704 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
707 // Use legacy mail() command
708 mail($toEmail, $subject, decodeEntities($message), $from);
712 // Generate a password in a specified length or use default password length
713 function generatePassword ($length = 0) {
714 // Auto-fix invalid length of zero
715 if ($length == 0) $length = getConfig('pass_len');
717 // Initialize array with all allowed chars
718 $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,-,+,_,/,.');
720 // Start creating password
722 for ($i = 0; $i < $length; $i++) {
723 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
726 // When the size is below 40 we can also add additional security by scrambling
727 // it. Otherwise we may corrupt hashes
728 if (strlen($PASS) <= 40) {
729 // Also scramble the password
730 $PASS = scrambleString($PASS);
733 // Return the password
737 // Generates a human-readable timestamp from the Uni* stamp
738 function generateDateTime ($time, $mode = 0) {
739 // Filter out numbers
740 $time = bigintval($time);
742 // If the stamp is zero it mostly didn't "happen"
745 return getMessage('NEVER_HAPPENED');
748 switch (getLanguage()) {
749 case 'de': // German date / time format
751 case 0: $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
752 case 1: $ret = strtolower(date('d.m.Y - H:i', $time)); break;
753 case 2: $ret = date('d.m.Y|H:i', $time); break;
754 case 3: $ret = date('d.m.Y', $time); break;
756 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
761 default: // Default is the US date / time format!
763 case 0: $ret = date('r', $time); break;
764 case 1: $ret = date('Y-m-d - g:i A', $time); break;
765 case 2: $ret = date('y-m-d|H:i', $time); break;
766 case 3: $ret = date('y-m-d', $time); break;
768 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
777 // Translates Y/N to yes/no
778 function translateYesNo ($yn) {
780 $translated = '??? (' . $yn . ')';
782 case 'Y': $translated = getMessage('YES'); break;
783 case 'N': $translated = getMessage('NO'); break;
786 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
794 // Translates the "pool type" into human-readable
795 function translatePoolType ($type) {
796 // Default?type is unknown
797 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
800 $constName = sprintf("POOL_TYPE_%s", $type);
803 if (isMessageIdValid($constName)) {
805 $translated = getMessage($constName);
808 // Return "translation"
812 // Translates the american decimal dot into a german comma
813 function translateComma ($dotted, $cut = true, $max = 0) {
814 // Default is 3 you can change this in admin area "Misc -> Misc Options"
815 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
817 // Use from config is default
818 $maxComma = getConfig('max_comma');
820 // Use from parameter?
821 if ($max > 0) $maxComma = $max;
824 if (($cut === true) && ($max == 0)) {
825 // Test for commata if in cut-mode
826 $com = explode('.', $dotted);
827 if (count($com) < 2) {
828 // Don't display commatas even if there are none... ;-)
834 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
837 switch (getLanguage()) {
838 case 'de': // German language
839 $dotted = number_format($dotted, $maxComma, ',', '.');
842 default: // All others
843 $dotted = number_format($dotted, $maxComma, '.', ',');
847 // Return translated value
851 // Translate Uni*-like gender to human-readable
852 function translateGender ($gender) {
854 $ret = '!' . $gender . '!';
856 // Male/female or company?
858 case 'M': $ret = getMessage('GENDER_M'); break;
859 case 'F': $ret = getMessage('GENDER_F'); break;
860 case 'C': $ret = getMessage('GENDER_C'); break;
862 // Log unknown gender
863 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
867 // Return translated gender
871 // "Translates" the user status
872 function translateUserStatus ($status) {
873 // Generate message depending on status
878 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
883 $ret = getMessage('ACCOUNT_DELETED');
887 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
888 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
896 // Generates an URL for the dereferer
897 function generateDerefererUrl ($URL) {
898 // Don't de-refer our own links!
899 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
900 // De-refer this link
901 $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
908 // Generates an URL for the frametester
909 function generateFrametesterUrl ($URL) {
910 // Prepare frametester URL
911 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
912 encodeString(compileUriCode($URL))
915 // Return the new URL
916 return $frametesterUrl;
919 // Count entries from e.g. a selection box
920 function countSelection ($array) {
922 if (!is_array($array)) {
924 debug_report_bug(__FUNCTION__.': No array provided.');
931 foreach ($array as $key => $selected) {
933 if (!empty($selected)) $ret++;
936 // Return counted selections
940 // Generate XHTML code for the CAPTCHA
941 function generateCaptchaCode ($code, $type, $DATA, $userid) {
942 return '<img border="0" alt="Code ' . $code . '" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
945 // Generates a timestamp (some wrapper for mktime())
946 function makeTime ($hours, $minutes, $seconds, $stamp) {
947 // Extract day, month and year from given timestamp
948 $days = date('d', $stamp);
949 $months = date('m', $stamp);
950 $years = date('Y', $stamp);
952 // Create timestamp for wished time which depends on extracted date
963 // Redirects to an URL and if neccessarry extends it with own base URL
964 function redirectToUrl ($URL) {
965 // Compile out URI codes
966 $URL = compileUriCode($URL);
968 // Check if http(s):// is there
969 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
970 // Make all URLs full-qualified
971 $URL = getConfig('URL') . '/' . $URL;
974 // Three different debug ways...
975 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
976 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $URL);
977 //* DEBUG: */ die($URL);
979 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
980 $rel = ' rel="external"';
982 // Do we have internal or external URL?
983 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
984 // Own (=internal) URL
989 $GLOBALS['output'] = ob_get_contents();
991 // Clear it only if there is content
992 if (!empty($GLOBALS['output'])) {
996 // Simple probe for bots/spiders from search engines
997 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
998 // Secure the URL against bad things such als HTML insertions and so on...
999 $URL = secureString($URL);
1001 // Output new location link as anchor
1002 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
1003 } elseif (!headers_sent()) {
1004 // Load URL when headers are not sent
1005 //* DEBUG: */ debug_report_bug("URL={$URL}");
1006 sendHeader('Location: '.str_replace('&', '&', $URL));
1008 // Output error message
1009 loadInclude('inc/header.php');
1010 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
1011 loadInclude('inc/footer.php');
1014 // Shut the mailer down here
1018 // Wrapper for redirectToUrl but URL comes from a configuration entry
1019 function redirectToConfiguredUrl ($configEntry) {
1021 $URL = getConfig($configEntry);
1024 if (is_null($URL)) {
1026 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1030 redirectToUrl($URL);
1033 // Compiles the given HTML/mail code
1034 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1035 // Is the code a string?
1036 if (!is_string($code)) {
1037 // Silently return it
1041 // Init replacement-array with full security characters
1042 $secChars = $GLOBALS['security_chars'];
1044 // Select smaller set of chars to replace when we e.g. want to compile URLs
1045 if ($full === false) $secChars = $GLOBALS['url_chars'];
1047 // Compile more through a filter
1048 $code = runFilterChain('compile_code', $code);
1050 // Compile constants
1051 if ($constants === true) {
1052 // BEFORE 0.2.1 : Language and data constants
1053 // WITH 0.2.1+ : Only language constants
1054 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1056 // BEFORE 0.2.1 : Not used
1057 // WITH 0.2.1+ : Data constants
1058 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1061 // Compile QUOT and other non-HTML codes
1062 foreach ($secChars['to'] as $k => $to) {
1063 // Do the reversed thing as in inc/libs/security_functions.php
1064 $code = str_replace($to, $secChars['from'][$k], $code);
1067 // But shall I keep simple quotes for later use?
1068 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1070 // Find $content[bla][blub] entries
1071 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1073 // Are some matches found?
1074 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1075 // Replace all matches
1076 $matchesFound = array();
1077 foreach ($matches[0] as $key => $match) {
1078 // Fuzzy look has failed by default
1079 $fuzzyFound = false;
1081 // Fuzzy look on match if already found
1082 foreach ($matchesFound as $found => $set) {
1084 $test = substr($found, 0, strlen($match));
1086 // Does this entry exist?
1087 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1088 if ($test == $match) {
1090 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1097 if ($fuzzyFound === true) continue;
1099 // Take all string elements
1100 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1101 // Replace it in the code
1102 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1103 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1104 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1105 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1106 $matchesFound[$match] = 1;
1107 } elseif (!isset($matchesFound[$match])) {
1108 // Not yet replaced!
1109 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1110 $code = str_replace($match, "\"." . $match.".\"", $code);
1111 $matchesFound[$match] = 1;
1116 // Return compiled code
1120 /************************************************************************
1122 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1123 * $a_sort sortiert: *
1125 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1126 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1127 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1128 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1129 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1131 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1132 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1133 * Sie, dass es doch nicht so schwer ist! :-) *
1135 ************************************************************************/
1136 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1138 while ($primary_key < count($a_sort)) {
1139 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1140 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1142 if ($nums === false) {
1143 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1144 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1145 } elseif ($key != $key2) {
1146 // Sort numbers (E.g.: 9 < 10)
1147 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1148 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1152 // We have found two different values, so let's sort whole array
1153 foreach ($dummy as $sort_key => $sort_val) {
1154 $t = $dummy[$sort_key][$key];
1155 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1156 $dummy[$sort_key][$key2] = $t;
1167 // Write back sorted array
1172 function addSelectionBox ($type, $default, $prefix = '', $id = 0) {
1175 if ($type == 'yn') {
1176 // This is a yes/no selection only!
1177 if ($id > 0) $prefix .= "[" . $id."]";
1178 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1180 // Begin with regular selection box here
1181 if (!empty($prefix)) $prefix .= "_";
1183 if ($id > 0) $type2 .= "[" . $id."]";
1184 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1189 for ($idx = 1; $idx < 32; $idx++) {
1190 $OUT .= "<option value=\"" . $idx."\"";
1191 if ($default == $idx) $OUT .= ' selected="selected"';
1192 $OUT .= ">" . $idx."</option>\n";
1196 case 'month': // Month
1197 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1198 $OUT .= "<option value=\"" . $month."\"";
1199 if ($default == $month) $OUT .= ' selected="selected"';
1200 $OUT .= ">" . $descr."</option>\n";
1204 case 'year': // Year
1206 $year = date('Y', time());
1208 // Use configured min age or fixed?
1209 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1211 $startYear = $year - getConfig('min_age');
1214 $startYear = $year - 16;
1217 // Calculate earliest year (100 years old people can still enter Internet???)
1218 $minYear = $year - 100;
1220 // Check if the default value is larger than minimum and bigger than actual year
1221 if (($default > $minYear) && ($default >= $year)) {
1222 for ($idx = $year; $idx < ($year + 11); $idx++) {
1223 $OUT .= "<option value=\"" . $idx."\"";
1224 if ($default == $idx) $OUT .= ' selected="selected"';
1225 $OUT .= ">" . $idx."</option>\n";
1227 } elseif ($default == -1) {
1228 // Current year minus 1
1229 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1231 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1234 // Get current year and subtract the configured minimum age
1235 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1236 // Calculate earliest year depending on extension version
1237 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1238 // Use configured minimum age
1239 $year = date('Y', time()) - getConfig('min_age');
1241 // Use fixed 16 years age
1242 $year = date('Y', time()) - 16;
1245 // Construct year selection list
1246 for ($idx = $minYear; $idx <= $year; $idx++) {
1247 $OUT .= "<option value=\"" . $idx."\"";
1248 if ($default == $idx) $OUT .= ' selected="selected"';
1249 $OUT .= ">" . $idx."</option>\n";
1256 for ($idx = 0; $idx < 60; $idx+=5) {
1257 if (strlen($idx) == 1) $idx = 0 . $idx;
1258 $OUT .= "<option value=\"" . $idx."\"";
1259 if ($default == $idx) $OUT .= ' selected="selected"';
1260 $OUT .= ">" . $idx."</option>\n";
1265 for ($idx = 0; $idx < 24; $idx++) {
1266 if (strlen($idx) == 1) $idx = 0 . $idx;
1267 $OUT .= "<option value=\"" . $idx."\"";
1268 if ($default == $idx) $OUT .= ' selected="selected"';
1269 $OUT .= ">" . $idx."</option>\n";
1274 $OUT .= "<option value=\"Y\"";
1275 if ($default == 'Y') $OUT .= ' selected="selected"';
1276 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1277 if ($default != 'Y') $OUT .= ' selected="selected"';
1278 $OUT .= ">{--NO--}</option>\n";
1281 $OUT .= " </select>\n";
1286 // Deprecated : $length
1289 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1290 // Build server string
1291 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1294 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1295 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1296 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1297 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1298 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1300 // Build string from misc data
1301 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1303 // Add more additional data
1304 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1306 // Add referal id, language, theme and userid
1307 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1308 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1309 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1310 $data .= getConfig('ENCRYPT_SEPERATOR') . getUserId();
1312 // Calculate number for generating the code
1313 $a = $code + getConfig('_ADD') - 1;
1315 if (isConfigEntrySet('master_salt')) {
1316 // Generate hash with master salt from modula of number with the prime number and other data
1317 $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'));
1319 // Create number from hash
1320 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1322 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1323 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, getConfig('salt_length')));
1325 // Create number from hash
1326 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1329 // At least 10 numbers shall be secure enought!
1330 $len = getConfig('code_length');
1331 if ($len == 0) $len = $length;
1332 if ($len == 0) $len = 10;
1334 // Cut off requested counts of number
1335 $return = substr(str_replace('.', '', $rcode), 0, $len);
1337 // Done building code
1341 // Does only allow numbers
1342 function bigintval ($num, $castValue = true) {
1343 // Filter all numbers out
1344 $ret = preg_replace('/[^0123456789]/', '', $num);
1347 if ($castValue) $ret = (double)$ret;
1349 // Has the whole value changed?
1350 // @TODO Remove this if() block if all is working fine
1351 if ('' . $ret . '' != '' . $num . '') {
1353 //debug_report_bug("{$ret}<>{$num}");
1360 // Insert the code in $img_code into jpeg or PNG image
1361 function generateImageOrCode ($img_code, $headerSent=true) {
1362 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1363 // Stop execution of function here because of over-sized code length
1365 } elseif ($headerSent === false) {
1366 // Return in an HTML code code
1367 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1371 $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
1372 if (isFileReadable($img)) {
1373 // Switch image type
1374 switch (getConfig('img_type'))
1377 // Okay, load image and hide all errors
1378 $image = imagecreatefromjpeg($img);
1382 // Okay, load image and hide all errors
1383 $image = imagecreatefrompng($img);
1387 // Exit function here
1388 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1392 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1393 $text_color = imagecolorallocate($image, 0, 0, 0);
1395 // Insert code into image
1396 imagestring($image, 5, 14, 2, $img_code, $text_color);
1398 // Return to browser
1399 sendHeader('Content-Type: image/' . getConfig('img_type'));
1401 // Output image with matching image factory
1402 switch (getConfig('img_type')) {
1403 case 'jpg': imagejpeg($image); break;
1404 case 'png': imagepng($image); break;
1407 // Remove image from memory
1408 imagedestroy($image);
1410 // Create selection box or array of splitted timestamp
1411 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1412 // Calculate 2-seconds timestamp
1413 $stamp = round($timestamp);
1414 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1416 // Do we have a leap year?
1418 $TEST = date('Y', time()) / 4;
1419 $M1 = date('m', time());
1420 $M2 = date('m', (time() + $timestamp));
1422 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1423 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1425 // First of all years...
1426 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1427 //* DEBUG: */ print("Y={$Y}<br />");
1429 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1430 //* DEBUG: */ print("M={$M}<br />");
1432 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1433 //* DEBUG: */ print("W={$W}<br />");
1435 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1436 //* DEBUG: */ print("D={$D}<br />");
1438 $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));
1439 //* DEBUG: */ print("h={$h}<br />");
1441 $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));
1442 //* DEBUG: */ print("m={$m}<br />");
1443 // And at last seconds...
1444 $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));
1445 //* DEBUG: */ print("s={$s}<br />");
1447 // Is seconds zero and time is < 60 seconds?
1448 if (($s == 0) && ($timestamp < 60)) {
1450 $s = round($timestamp);
1454 // Now we convert them in seconds...
1456 if ($return_array) {
1457 // Just put all data in an array for later use
1469 $OUT = "<div align=\"" . $align."\">\n";
1470 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1473 if (ereg('Y', $display) || (empty($display))) {
1474 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1477 if (ereg('M', $display) || (empty($display))) {
1478 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1481 if (ereg("W", $display) || (empty($display))) {
1482 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1485 if (ereg("D", $display) || (empty($display))) {
1486 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1489 if (ereg("h", $display) || (empty($display))) {
1490 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1493 if (ereg('m', $display) || (empty($display))) {
1494 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1497 if (ereg("s", $display) || (empty($display))) {
1498 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1504 if (ereg('Y', $display) || (empty($display))) {
1505 // Generate year selection
1506 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1507 for ($idx = 0; $idx <= 10; $idx++) {
1508 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1509 if ($idx == $Y) $OUT .= ' selected="selected"';
1510 $OUT .= ">" . $idx."</option>\n";
1512 $OUT .= " </select></td>\n";
1514 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1517 if (ereg('M', $display) || (empty($display))) {
1518 // Generate month selection
1519 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1520 for ($idx = 0; $idx <= 11; $idx++)
1522 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1523 if ($idx == $M) $OUT .= ' selected="selected"';
1524 $OUT .= ">" . $idx."</option>\n";
1526 $OUT .= " </select></td>\n";
1528 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1531 if (ereg("W", $display) || (empty($display))) {
1532 // Generate week selection
1533 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1534 for ($idx = 0; $idx <= 4; $idx++) {
1535 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1536 if ($idx == $W) $OUT .= ' selected="selected"';
1537 $OUT .= ">" . $idx."</option>\n";
1539 $OUT .= " </select></td>\n";
1541 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1544 if (ereg("D", $display) || (empty($display))) {
1545 // Generate day selection
1546 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1547 for ($idx = 0; $idx <= 31; $idx++) {
1548 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1549 if ($idx == $D) $OUT .= ' selected="selected"';
1550 $OUT .= ">" . $idx."</option>\n";
1552 $OUT .= " </select></td>\n";
1554 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1557 if (ereg("h", $display) || (empty($display))) {
1558 // Generate hour selection
1559 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1560 for ($idx = 0; $idx <= 23; $idx++) {
1561 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1562 if ($idx == $h) $OUT .= ' selected="selected"';
1563 $OUT .= ">" . $idx."</option>\n";
1565 $OUT .= " </select></td>\n";
1567 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1570 if (ereg('m', $display) || (empty($display))) {
1571 // Generate minute selection
1572 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1573 for ($idx = 0; $idx <= 59; $idx++) {
1574 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1575 if ($idx == $m) $OUT .= ' selected="selected"';
1576 $OUT .= ">" . $idx."</option>\n";
1578 $OUT .= " </select></td>\n";
1580 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1583 if (ereg("s", $display) || (empty($display))) {
1584 // Generate second selection
1585 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1586 for ($idx = 0; $idx <= 59; $idx++) {
1587 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1588 if ($idx == $s) $OUT .= ' selected="selected"';
1589 $OUT .= ">" . $idx."</option>\n";
1591 $OUT .= " </select></td>\n";
1593 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1596 $OUT .= "</table>\n";
1598 // Return generated HTML code
1604 function createTimestampFromSelections ($prefix, $postData) {
1605 // Initial return value
1608 // Do we have a leap year?
1610 $TEST = date('Y', time()) / 4;
1611 $M1 = date('m', time());
1612 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1613 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1614 // First add years...
1615 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1617 $ret += $postData[$prefix."_mo"] * 2628000;
1619 $ret += $postData[$prefix."_we"] * 604800;
1621 $ret += $postData[$prefix."_da"] * 86400;
1623 $ret += $postData[$prefix."_ho"] * 3600;
1625 $ret += $postData[$prefix."_mi"] * 60;
1626 // And at last seconds...
1627 $ret += $postData[$prefix."_se"];
1628 // Return calculated value
1632 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1633 function createFancyTime ($stamp) {
1634 // Get data array with years/months/weeks/days/...
1635 $data = createTimeSelections($stamp, '', '', '', true);
1637 foreach($data as $k => $v) {
1639 // Value is greater than 0 "eval" data to return string
1640 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1645 // Do we have something there?
1646 if (strlen($ret) > 0) {
1647 // Remove leading commata and space
1648 $ret = substr($ret, 2);
1651 $ret = "0 {--_SECONDS--}";
1654 // Return fancy time string
1658 // Generates a navigation row for listing emails
1659 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1660 $SEP = ''; $TOP = '';
1661 if ($show_form === false) {
1663 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1667 for ($page = 1; $page <= $PAGES; $page++) {
1668 // Is the page currently selected or shall we generate a link to it?
1669 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1670 // Is currently selected, so only highlight it
1671 $NAV .= '<strong>-';
1673 // Open anchor tag and add base URL
1674 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1676 // Add userid when we shall show all mails from a single member
1677 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1679 // Close open anchor tag
1683 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1684 // Is currently selected, so only highlight it
1685 $NAV .= '-</strong>';
1691 // Add seperator if we have not yet reached total pages
1692 if ($page < $PAGES) $NAV .= ' | ';
1695 // Define constants only once
1696 $content['nav'] = $NAV;
1697 $content['span'] = $colspan;
1698 $content['top'] = $TOP;
1699 $content['sep'] = $SEP;
1701 // Load navigation template
1702 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1704 if ($return === true) {
1705 // Return generated HTML-Code
1713 // Extract host from script name
1714 function extractHostnameFromUrl (&$script) {
1715 // Use default SERVER_URL by default... ;) So?
1716 $url = getConfig('SERVER_URL');
1718 // Is this URL valid?
1719 if (substr($script, 0, 7) == 'http://') {
1720 // Use the hostname from script URL as new hostname
1721 $url = substr($script, 7);
1722 $extract = explode('/', $url);
1724 // Done extracting the URL :)
1727 // Extract host name
1728 $host = str_replace('http://', '', $url);
1729 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1731 // Generate relative URL
1732 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1733 if (substr(strtolower($script), 0, 7) == 'http://') {
1734 // But only if http:// is in front!
1735 $script = substr($script, (strlen($url) + 7));
1736 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1738 $script = substr($script, (strlen($url) + 8));
1741 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1742 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1748 // Send a GET request
1749 function sendGetRequest ($script, $data = array()) {
1750 // Extract host name from script
1751 $host = extractHostnameFromUrl($script);
1754 $scriptData = http_build_query($data, '', '&');
1756 // Do we have a question-mark in the script?
1757 if (strpos($script, '?') === false) {
1758 // No, so first char must be question mark
1759 $scriptData = '?' . $scriptData;
1762 $scriptData = '&' . $scriptData;
1766 $script .= $scriptData;
1768 // Generate GET request header
1769 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1770 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1771 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1772 if (isConfigEntrySet('FULL_VERSION')) {
1773 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1775 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1777 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1778 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1779 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1781 // Send the raw request
1782 $response = sendRawRequest($host, $request);
1784 // Return the result to the caller function
1788 // Send a POST request
1789 function sendPostRequest ($script, $postData) {
1790 // Is postData an array?
1791 if (!is_array($postData)) {
1793 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1794 return array('', '', '');
1797 // Compile the script name
1798 $script = compileCode($script);
1800 // Extract host name from script
1801 $host = extractHostnameFromUrl($script);
1803 // Construct request
1804 $data = http_build_query($postData, '', '&');
1806 // Generate POST request header
1807 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1808 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1809 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1810 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1811 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1812 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1813 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1814 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1817 // Send the raw request
1818 $response = sendRawRequest($host, $request);
1820 // Return the result to the caller function
1824 // Sends a raw request to another host
1825 function sendRawRequest ($host, $request) {
1826 // Init errno and errdesc with 'all fine' values
1827 $errno = 0; $errdesc = '';
1830 $response = array('', '', '');
1832 // Default is not to use proxy
1835 // Are proxy settins set?
1836 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1842 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1843 if ($useProxy === true) {
1844 // Connect to host through proxy connection
1845 $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1847 // Connect to host directly
1848 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1852 if (!is_resource($fp)) {
1858 if ($useProxy === true) {
1859 // Generate CONNECT request header
1860 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1861 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1863 // Use login data to proxy? (username at least!)
1864 if (getConfig('proxy_username') != '') {
1866 $encodedAuth = base64_encode(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
1867 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1870 // Add last new-line
1871 $proxyTunnel .= getConfig('HTTP_EOL');
1872 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1875 fputs($fp, $proxyTunnel);
1879 // No response received
1883 // Read the first line
1884 $resp = trim(fgets($fp, 10240));
1885 $respArray = explode(' ', $resp);
1886 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1887 // Invalid response!
1893 fputs($fp, $request);
1896 while (!feof($fp)) {
1897 $response[] = trim(fgets($fp, 1024));
1903 // Skip first empty lines
1905 foreach ($resp as $idx => $line) {
1907 $line = trim($line);
1909 // Is this line empty?
1912 array_shift($response);
1914 // Abort on first non-empty line
1919 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1921 // Proxy agent found?
1922 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1923 // Proxy header detected, so remove two lines
1924 array_shift($response);
1925 array_shift($response);
1928 // Was the request successfull?
1929 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1930 // Not found / access forbidden
1931 $response = array('', '', '');
1938 // Taken from www.php.net eregi() user comments
1939 function isEmailValid ($email) {
1941 $email = compileCode($email);
1943 // Check first part of email address
1944 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1947 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1950 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1952 // Return check result
1953 return preg_match($regex, $email);
1956 // Function taken from user comments on www.php.net / function eregi()
1957 function isUrlValid ($URL, $compile=true) {
1958 // Trim URL a little
1959 $URL = trim(urldecode($URL));
1960 //* DEBUG: */ outputHtml($URL.'<br />');
1962 // Compile some chars out...
1963 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1964 //* DEBUG: */ outputHtml($URL.'<br />');
1966 // Check for the extension filter
1967 if (isExtensionActive('filter')) {
1968 // Use the extension's filter set
1969 return FILTER_VALIDATE_URL($URL, false);
1972 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1973 // https:// in front of the URLs
1974 return isUrlValidSimple($URL);
1977 // Generate a list of administrative links to a given userid
1978 function generateMemberAdminActionLinks ($userid, $status = '') {
1979 // Make sure userid is a number
1980 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1982 // Define all main targets
1983 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1985 // Begin of navigation links
1988 foreach ($targetArray as $tar) {
1989 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1990 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1991 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1992 // Locked accounts shall be unlocked
1993 $OUT .= 'UNLOCK_USER';
1995 // All other status is fine
1996 $OUT .= strtoupper($tar);
1998 $OUT .= "_TITLE--}\">{--ADMIN_";
1999 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2000 // Locked accounts shall be unlocked
2001 $OUT .= 'UNLOCK_USER';
2003 // All other status is fine
2004 $OUT .= strtoupper($tar);
2006 $OUT .= "--}</a></span> | ";
2009 // Finish navigation link
2010 $OUT = substr($OUT, 0, -7) . ']';
2016 // Generate an email link
2017 function generateEmailLink ($email, $table = 'admins') {
2018 // Default email link (INSECURE! Spammer can read this by harvester programs)
2019 $EMAIL = 'mailto:' . $email;
2021 // Check for several extensions
2022 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2023 // Create email link for contacting admin in guest area
2024 $EMAIL = generateAdminEmailLink($email);
2025 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2026 // Create email link for contacting a member within admin area (or later in other areas, too?)
2027 $EMAIL = generateUserEmailLink($email, 'admin');
2028 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2029 // Create email link to contact sponsor within admin area (or like the link above?)
2030 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2033 // Shall I close the link when there is no admin?
2034 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2036 // Return email link
2040 // Generate a hash for extra-security for all passwords
2041 function generateHash ($plainText, $salt = '') {
2042 // Is the required extension 'sql_patches' there and a salt is not given?
2043 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2044 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2045 return md5($plainText);
2048 // Do we miss an arry element here?
2049 if (!isConfigEntrySet('file_hash')) {
2051 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2054 // When the salt is empty build a new one, else use the first x configured characters as the salt
2056 // Build server string (inc/databases.php is no longer updated with every commit)
2057 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2060 $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');
2063 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2065 // Calculate number for generating the code
2066 $a = time() + getConfig('_ADD') - 1;
2068 // Generate SHA1 sum from modula of number and the prime number
2069 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2070 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2071 $sha1 = scrambleString($sha1);
2072 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2073 //* DEBUG: */ $sha1b = descrambleString($sha1);
2074 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2076 // Generate the password salt string
2077 $salt = substr($sha1, 0, getConfig('salt_length'));
2078 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2081 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2082 $salt = substr($salt, 0, getConfig('salt_length'));
2083 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2085 // Sanity check on salt
2086 if (strlen($salt) != getConfig('salt_length')) {
2088 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2093 return $salt.sha1($salt . $plainText);
2096 // Scramble a string
2097 function scrambleString($str) {
2101 // Final check, in case of failture it will return unscrambled string
2102 if (strlen($str) > 40) {
2103 // The string is to long
2105 } elseif (strlen($str) == 40) {
2107 $scrambleNums = explode(':', getConfig('pass_scramble'));
2109 // Generate new numbers
2110 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2113 // Scramble string here
2114 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2115 for ($idx = 0; $idx < strlen($str); $idx++) {
2116 // Get char on scrambled position
2117 $char = substr($str, $scrambleNums[$idx], 1);
2119 // Add it to final output string
2120 $scrambled .= $char;
2123 // Return scrambled string
2124 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2128 // De-scramble a string scrambled by scrambleString()
2129 function descrambleString($str) {
2130 // Scramble only 40 chars long strings
2131 if (strlen($str) != 40) return $str;
2133 // Load numbers from config
2134 $scrambleNums = explode(':', getConfig('pass_scramble'));
2137 if (count($scrambleNums) != 40) return $str;
2139 // Begin descrambling
2140 $orig = str_repeat(' ', 40);
2141 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2142 for ($idx = 0; $idx < 40; $idx++) {
2143 $char = substr($str, $idx, 1);
2144 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2147 // Return scrambled string
2148 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2152 // Generated a "string" for scrambling
2153 function genScrambleString ($len) {
2154 // Prepare array for the numbers
2155 $scrambleNumbers = array();
2157 // First we need to setup randomized numbers from 0 to 31
2158 for ($idx = 0; $idx < $len; $idx++) {
2160 $rand = mt_rand(0, ($len -1));
2162 // Check for it by creating more numbers
2163 while (array_key_exists($rand, $scrambleNumbers)) {
2164 $rand = mt_rand(0, ($len -1));
2168 $scrambleNumbers[$rand] = $rand;
2171 // So let's create the string for storing it in database
2172 $scrambleString = implode(':', $scrambleNumbers);
2173 return $scrambleString;
2176 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2177 function generatePassString ($passHash) {
2178 // Return vanilla password hash
2181 // Is a secret key and master salt already initialized?
2182 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2183 // Only calculate when the secret key is generated
2184 $newHash = ''; $start = 9;
2185 for ($idx = 0; $idx < 10; $idx++) {
2186 $part1 = hexdec(substr($passHash, $start, 4));
2187 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2188 $mod = dechex($idx);
2189 if ($part1 > $part2) {
2190 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2191 } elseif ($part2 > $part1) {
2192 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2194 $mod = substr($mod, 0, 4);
2195 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2196 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2197 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2202 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2203 $ret = generateHash($newHash, getConfig('master_salt'));
2204 //* DEBUG: */ print('ret='.$ret.'<br />');
2207 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2208 $ret = md5($passHash);
2209 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2216 // Fix "deleted" cookies
2217 function fixDeletedCookies ($cookies) {
2218 // Is this an array with entries?
2219 if ((is_array($cookies)) && (count($cookies) > 0)) {
2220 // Then check all cookies if they are marked as deleted!
2221 foreach ($cookies as $cookieName) {
2222 // Is the cookie set to "deleted"?
2223 if (getSession($cookieName) == 'deleted') {
2224 setSession($cookieName, '');
2230 // Output error messages in a fasioned way and die...
2231 function app_die ($F, $L, $message) {
2232 // Check if Script is already dieing and not let it kill itself another 1000 times
2233 if (!isset($GLOBALS['app_died'])) {
2234 // Make sure, that the script realy realy diese here and now
2235 $GLOBALS['app_died'] = true;
2238 loadIncludeOnce('inc/header.php');
2240 // Rewrite message for output
2241 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2243 // Better log this message away
2244 logDebugMessage($F, $L, $message);
2246 // Load the message template
2247 loadTemplate('admin_settings_saved', false, $message);
2250 loadIncludeOnce('inc/footer.php');
2252 // Script tried to kill itself twice
2253 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2257 // Display parsing time and number of SQL queries in footer
2258 function displayParsingTime() {
2259 // Is the timer started?
2260 if (!isset($GLOBALS['startTime'])) {
2266 $endTime = microtime(true);
2268 // "Explode" both times
2269 $start = explode(' ', $GLOBALS['startTime']);
2270 $end = explode(' ', $endTime);
2271 $runTime = $end[0] - $start[0];
2272 if ($runTime < 0) $runTime = 0;
2276 'runtime' => translateComma($runTime),
2277 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2280 // Load the template
2281 loadTemplate('show_timings', false, $content);
2284 // Check wether a boolean constant is set
2285 // Taken from user comments in PHP documentation for function constant()
2286 function isBooleanConstantAndTrue ($constName) { // : Boolean
2287 // Failed by default
2291 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2293 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2294 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2297 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2298 if (defined($constName)) {
2300 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2301 $res = (constant($constName) === true);
2305 $GLOBALS['cache_array']['const'][$constName] = $res;
2307 //* DEBUG: */ var_dump($res);
2313 // Checks if a given apache module is loaded
2314 function isApacheModuleLoaded ($apacheModule) {
2315 // Check it and return result
2316 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2319 // Get current theme name
2320 function getCurrentTheme () {
2321 // The default theme is 'default'... ;-)
2324 // Load default theme if not empty from configuration
2325 if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
2327 if (!isSessionVariableSet('mxchange_theme')) {
2328 // Set default theme
2330 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2331 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2332 // Get theme from cookie
2333 $ret = getSession('mxchange_theme');
2336 if (getThemeId($ret) == 0) {
2337 // Fix it to default
2340 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2341 // Prepare FQFN for checking
2342 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2344 // Installation mode active
2345 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2346 // Set cookie from URL data
2347 setTheme(getRequestElement('theme'));
2348 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2349 // Set cookie from posted data
2350 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2354 $ret = getSession('mxchange_theme');
2356 // Invalid design, reset cookie
2360 // Return theme value
2364 // Setter for theme in session
2365 function setTheme ($newTheme) {
2366 setSession('mxchange_theme', $newTheme);
2369 // Get id from theme
2370 // @TODO Try to move this to inc/libs/theme_functions.php
2371 function getThemeId ($name) {
2372 // Is the extension 'theme' installed?
2373 if (!isExtensionActive('theme')) {
2381 // Is the cache entry there?
2382 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2383 // Get the version from cache
2384 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2387 incrementStatsEntry('cache_hits');
2388 } elseif (getExtensionVersion('cache') != '0.1.8') {
2389 // Check if current theme is already imported or not
2390 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2391 array($name), __FUNCTION__, __LINE__);
2394 if (SQL_NUMROWS($result) == 1) {
2396 list($id) = SQL_FETCHROW($result);
2400 SQL_FREERESULT($result);
2407 // Generates an error code from given account status
2408 function generateErrorCodeFromUserStatus ($status) {
2409 // @TODO The status should never be empty
2410 if (empty($status)) {
2411 // Something really bad happend here
2412 debug_report_bug(__FUNCTION__ . ': status is empty.');
2415 // Default error code if unknown account status
2416 $errorCode = getCode('UNKNOWN_STATUS');
2418 // Generate constant name
2419 $constantName = sprintf("ID_%s", $status);
2421 // Is the constant there?
2422 if (isCodeSet($constantName)) {
2424 $errorCode = getCode($constantName);
2427 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2430 // Return error code
2434 // Function to search for the last modifified file
2435 function searchDirsRecursive ($dir, &$last_changed) {
2437 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2438 // Does it match what we are looking for? (We skip a lot files already!)
2439 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2440 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2441 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2442 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2444 // Walk through all entries
2445 foreach ($ds as $d) {
2446 // Generate proper FQFN
2447 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2449 // Is it a file and readable?
2450 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2451 if (isDirectory($FQFN)) {
2452 // $FQFN is a directory so also crawl into this directory
2454 if (!empty($dir)) $newDir = $dir . '/'. $d;
2455 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2456 searchDirsRecursive($newDir, $last_changed);
2457 } elseif (isFileReadable($FQFN)) {
2458 // $FQFN is a filename and no directory
2459 $time = filemtime($FQFN);
2460 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2461 if ($last_changed['time'] < $time) {
2462 // This file is newer as the file before
2463 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2464 $last_changed['path_name'] = $FQFN;
2465 $last_changed['time'] = $time;
2471 // "Getter" for revision/version data
2472 function getActualVersion ($type = 'Revision') {
2473 // By default nothing is new... ;-)
2476 // Is the cache entry there?
2477 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2478 // Found so increase cache hit
2479 incrementStatsEntry('cache_hits');
2482 return $GLOBALS['cache_array']['revision'][$type][0];
2484 // FQFN of revision file
2485 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2487 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2488 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2489 // Forced rebuild of .revision file
2492 // Check for revision file
2493 if (!isFileReadable($FQFN)) {
2494 // Not found, so we need to create it
2497 // Revision file found
2498 $ins_vers = explode("\n", readFromFile($FQFN));
2500 // Get array for mapping information
2501 $mapper = array_flip(getSearchFor());
2502 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2504 // Is the content valid?
2505 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2506 // File needs update!
2509 // Generate fake cache entry
2510 foreach ($mapper as $map=>$idx) {
2511 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2514 // Return found value
2515 return trim($ins_vers[$mapper[$type]]);
2520 // Has it been updated?
2521 if ($new === true) {
2523 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2525 // ... and call recursive
2526 return getActualVersion($type);
2531 // Repares an array we are looking for
2532 // 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
2533 function getSearchFor () {
2534 // Add Revision, Date, Tag and Author
2535 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2537 // Return the created array
2541 // @TODO Please describe this function
2542 function getArrayFromActualVersion () {
2546 // Directory to start with search
2547 $last_changed = array(
2552 // Init return array
2553 $akt_vers = array();
2555 // Init value for counting the founded keywords
2558 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2559 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2562 $last_file = readFromFile($last_changed['path_name']);
2564 // Get all the keywords to search for
2565 $searchFor = getSearchFor();
2567 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2568 foreach ($searchFor as $search) {
2569 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2570 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2571 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2572 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2575 // Save the last-changed filename for debugging
2576 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2578 // at least 3 keyword-Tags are needed for propper values
2579 if ($res && $res >= 3
2580 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2581 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2582 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2583 // Prepare content witch need special treadment
2585 // Prepare timestamp for date
2586 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2587 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2589 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2590 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2591 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2595 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2596 $version = sendGetRequest('check-updates3.php');
2599 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2600 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2601 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2602 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2603 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2604 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2607 // Return prepared array
2608 return $GLOBALS['cache_array']['revision'];
2611 // Back-ported from the new ship-simu engine. :-)
2612 function debug_get_printable_backtrace () {
2614 $backtrace = "<ol>\n";
2616 // Get and prepare backtrace for output
2617 $backtraceArray = debug_backtrace();
2618 foreach ($backtraceArray as $key => $trace) {
2619 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2620 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2621 if (!isset($trace['args'])) $trace['args'] = array();
2622 $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";
2626 $backtrace .= "</ol>\n";
2628 // Return the backtrace
2632 // Output a debug backtrace to the user
2633 function debug_report_bug ($message = '') {
2634 // Is this already called?
2635 if (isset($GLOBALS[__FUNCTION__])) {
2637 print 'Message:'.$message.'<br />Backtrace:<pre>';
2638 debug_print_backtrace();
2642 // Set this function as called
2643 $GLOBALS[__FUNCTION__] = true;
2648 // Is the optional message set?
2649 if (!empty($message)) {
2651 $debug = sprintf("Note: %s<br />\n",
2655 // @TODO Add a little more infos here
2656 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2660 $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>";
2661 $debug .= debug_get_printable_backtrace();
2662 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2663 $debug .= "Thank you for finding bugs.";
2666 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2670 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2671 function generateSeed () {
2672 list($usec, $sec) = explode(' ', microtime());
2673 $microTime = (((float)$sec + (float)$usec)) * 100000;
2677 // Converts a message code to a human-readable message
2678 function getMessageFromErrorCode ($code) {
2682 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2683 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2684 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2685 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2686 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2687 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2688 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2689 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2690 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2691 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2692 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2693 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2694 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2695 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2696 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2697 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2698 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2699 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2700 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2701 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2702 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2703 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2704 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2705 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2706 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2707 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2708 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2709 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2711 case getCode('ERROR_MAILID'):
2712 if (isExtensionActive('mailid', true)) {
2713 $message = getMessage('ERROR_CONFIRMING_MAIL');
2715 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2719 case getCode('EXTENSION_PROBLEM'):
2720 if (isGetRequestElementSet('ext')) {
2721 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2723 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2727 case getCode('URL_TLOCK'):
2728 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2729 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2731 // Load timestamp from last order
2732 list($timestamp) = SQL_FETCHROW($result);
2733 $timestamp = generateDateTime($timestamp, 1);
2736 SQL_FREERESULT($result);
2738 // Calculate hours...
2739 $STD = round(getConfig('url_tlock') / 60 / 60);
2742 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2745 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2747 // Finally contruct the message
2748 // @TODO Rewrite this old lost code to a template
2749 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2750 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2751 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2755 // Missing/invalid code
2756 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2759 logDebugMessage(__FUNCTION__, __LINE__, $message);
2763 // Return the message
2767 // Generate a "link" for the given admin id (admin_id)
2768 function generateAdminLink ($adminId) {
2769 // No assigned admin is default
2770 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2772 // Zero? = Not assigned
2773 if (bigintval($adminId) > 0) {
2774 // Load admin's login
2775 $login = getAdminLogin($adminId);
2777 // Is the login valid?
2778 if ($login != '***') {
2779 // Is the extension there?
2780 if (isExtensionActive('admins')) {
2782 $admin = "<a href=\"".generateEmailLink(getAdminEmail($adminId), 'admins')."\">" . $login."</a>";
2784 // Extension not found
2785 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2789 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $adminId)."</div>";
2797 // Compile characters which are allowed in URLs
2798 function compileUriCode ($code, $simple = true) {
2799 // Compile constants
2800 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2802 // Compile QUOT and other non-HTML codes
2803 $code = str_replace('{DOT}', '.',
2804 str_replace('{SLASH}', '/',
2805 str_replace('{QUOT}', "'",
2806 str_replace('{DOLLAR}', '$',
2807 str_replace('{OPEN_ANCHOR}', '(',
2808 str_replace('{CLOSE_ANCHOR}', ')',
2809 str_replace('{OPEN_SQR}', '[',
2810 str_replace('{CLOSE_SQR}', ']',
2811 str_replace('{PER}', '%',
2815 // Return compiled code
2819 // Function taken from user comments on www.php.net / function eregi()
2820 function isUrlValidSimple ($url) {
2822 $url = secureString(str_replace("\\", '', compileCode(urldecode($url))));
2824 // Allows http and https
2825 $http = "(http|https)+(:\/\/)";
2827 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2828 // Test double-domains (e.g. .de.vu)
2829 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2831 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2833 $dir = "((/)+([-_\.[:alnum:]])+)*";
2835 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2836 // ... and the string after and including question character
2837 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2838 // Pattern for URLs like http://url/dir/doc.html?var=value
2839 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2840 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2841 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2842 // Pattern for URLs like http://url/dir/?var=value
2843 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2844 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2845 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2846 // Pattern for URLs like http://url/dir/page.ext
2847 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2848 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2849 $pattern['ipdp'] = $http . $ip . $dir . $page;
2850 // Pattern for URLs like http://url/dir
2851 $pattern['d1d'] = $http . $domain1 . $dir;
2852 $pattern['d2d'] = $http . $domain2 . $dir;
2853 $pattern['ipd'] = $http . $ip . $dir;
2854 // Pattern for URLs like http://url/?var=value
2855 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2856 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2857 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2858 // Pattern for URLs like http://url?var=value
2859 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2860 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2861 $pattern['ipg12'] = $http . $ip . $getstring1;
2862 // Test all patterns
2864 foreach ($pattern as $key => $pat) {
2866 if (isDebugRegExpressionEnabled()) {
2867 // @TODO Are these convertions still required?
2868 $pat = str_replace('.', "\.", $pat);
2869 $pat = str_replace('@', "\@", $pat);
2870 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2873 // Check if expression matches
2874 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2877 if ($reg === true) break;
2880 // Return true/false
2884 // Wtites data to a config.php-style file
2885 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2886 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2887 // Initialize some variables
2893 // Is the file there and read-/write-able?
2894 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2895 $search = 'CFG: ' . $comment;
2896 $tmp = $FQFN . '.tmp';
2898 // Open the source file
2899 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2901 // Is the resource valid?
2902 if (is_resource($fp)) {
2903 // Open temporary file
2904 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2906 // Is the resource again valid?
2907 if (is_resource($fp_tmp)) {
2908 // Mark temporary file as readable
2909 $GLOBALS['file_readable'][$tmp] = true;
2912 while (!feof($fp)) {
2913 // Read from source file
2914 $line = fgets ($fp, 1024);
2916 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2919 if ($next === $seek) {
2921 $line = $prefix . $DATA . $suffix . "\n";
2927 // Write to temp file
2928 fputs($fp_tmp, $line);
2934 // Finished writing tmp file
2938 // Close source file
2941 if (($done === true) && ($found === true)) {
2942 // Copy back tmp file and delete tmp :-)
2943 copyFileVerified($tmp, $FQFN, 0644);
2944 return removeFile($tmp);
2945 } elseif ($found === false) {
2946 outputHtml('<strong>CHANGE:</strong> 404!');
2948 outputHtml('<strong>TMP:</strong> UNDONE!');
2952 // File not found, not readable or writeable
2953 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2956 // An error was detected!
2959 // Send notification to admin
2960 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = 0) {
2961 if (getExtensionVersion('admins') >= '0.4.1') {
2963 sendAdminsEmails($subject, $templateName, $content, $userid);
2965 // Send out out-dated way
2966 $message = loadEmailTemplate($templateName, $content, $userid);
2967 sendAdminEmails($subject, $message);
2971 // Debug message logger
2972 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2973 // Is debug mode enabled?
2974 if ((isDebugModeEnabled()) || ($force === true)) {
2976 $message = str_replace("\r", '', str_replace("\n", '', $message));
2978 // Log this message away, we better don't call app_die() here to prevent an endless loop
2979 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2980 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2985 // Handle extra values
2986 function handleExtraValues ($filterFunction, $value, $extraValue) {
2987 // Default is the value itself
2990 // Do we have a special filter function?
2991 if (!empty($filterFunction)) {
2992 // Does the filter function exist?
2993 if (function_exists($filterFunction)) {
2994 // Do we have extra parameters here?
2995 if (!empty($extraValue)) {
2996 // Put both parameters in one new array by default
2997 $args = array($value, $extraValue);
2999 // If we have an array simply use it and pre-extend it with our value
3000 if (is_array($extraValue)) {
3001 // Make the new args array
3002 $args = merge_array(array($value), $extraValue);
3005 // Call the multi-parameter call-back
3006 $ret = call_user_func_array($filterFunction, $args);
3008 // One parameter call
3009 $ret = call_user_func($filterFunction, $value);
3018 // Converts timestamp selections into a timestamp
3019 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
3020 // Init test variable
3024 // Get last three chars
3025 $test = substr($id, -3);
3027 // Improved way of checking! :-)
3028 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3029 // Found a multi-selection for timings?
3030 $test = substr($id, 0, -3);
3031 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)) {
3032 // Generate timestamp
3033 $postData[$test] = createTimestampFromSelections($test, $postData);
3034 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
3035 $GLOBALS['skip_config'][$test] = true;
3037 // Remove data from array
3038 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3039 unset($postData[$test . '_' . $rem]);
3050 // Reverts the german decimal comma into Computer decimal dot
3051 function convertCommaToDot ($str) {
3052 // Default float is not a float... ;-)
3055 // Which language is selected?
3056 switch (getLanguage()) {
3057 case 'de': // German language
3058 // Remove german thousand dots first
3059 $str = str_replace('.', '', $str);
3061 // Replace german commata with decimal dot and cast it
3062 $float = (float)str_replace(',', '.', $str);
3065 default: // US and so on
3066 // Remove thousand dots first and cast
3067 $float = (float)str_replace(',', '', $str);
3075 // Handle menu-depending failed logins and return the rendered content
3076 function handleLoginFailtures ($accessLevel) {
3077 // Default output is empty ;-)
3080 // Is the session data set?
3081 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3082 // Ignore zero values
3083 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3084 // Non-guest has login failures found, get both data and prepare it for template
3085 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3087 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3088 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3092 $OUT = loadTemplate('login_failures', true, $content);
3095 // Reset session data
3096 setSession('mxchange_' . $accessLevel.'_failures', '');
3097 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3100 // Return rendered content
3105 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3107 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3109 // Shall I remove the cache file?
3110 if (isCacheInstanceValid()) {
3112 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3114 $GLOBALS['cache_instance']->removeCacheFile($force);
3117 // Include file given?
3120 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3122 // Is the include there?
3123 if (isIncludeReadable($inc)) {
3124 // And rebuild it from scratch
3125 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3128 // Include not found!
3129 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3135 // Determines the real remote address
3136 function determineRealRemoteAddress () {
3137 // Is a proxy in use?
3138 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3140 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3141 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3142 // Yet, another proxy
3143 $address = $_SERVER['HTTP_CLIENT_IP'];
3145 // The regular address when no proxy was used
3146 $address = $_SERVER['REMOTE_ADDR'];
3149 // This strips out the real address from proxy output
3150 if (strstr($address, ',')) {
3151 $addressArray = explode(',', $address);
3152 $address = $addressArray[0];
3155 // Return the result
3159 // Adds a bonus mail to the queue
3160 // This is a high-level function!
3161 function addNewBonusMail ($data, $mode = '', $output=true) {
3162 // Use mode from data if not set and availble ;-)
3163 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3165 // Generate receiver list
3166 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3169 if (!empty($RECEIVER)) {
3170 // Add bonus mail to queue
3171 addBonusMailToQueue(
3183 // Mail inserted into bonus pool
3184 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3185 } elseif ($output) {
3186 // More entered than can be reached!
3187 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3190 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3194 // Determines referal id and sets it
3195 function determineReferalId () {
3196 // Skip this in non-html-mode
3197 if (getOutputMode() != 0) return false;
3199 // Check if refid is set
3200 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3202 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3203 // The variable user comes from the click-counter script click.php and we only accept this here
3204 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3205 } elseif (isPostRequestElementSet('refid')) {
3206 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3207 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3208 } elseif (isGetRequestElementSet('refid')) {
3209 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3210 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3211 } elseif (isGetRequestElementSet('ref')) {
3212 // Set refid=ref (the referal link uses such variable)
3213 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3214 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3215 // Set session refid als global
3216 $GLOBALS['refid'] = bigintval(getSession('refid'));
3217 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3218 // Select a random user which has confirmed enougth mails
3219 $GLOBALS['refid'] = determineRandomReferalId();
3220 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3221 // Set default refid as refid in URL
3222 $GLOBALS['refid'] = getConfig('def_refid');
3224 // No default ID when sql_patches is not installed or none set
3225 $GLOBALS['refid'] = 0;
3228 // Set cookie when default refid > 0
3229 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == 0) && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3231 setSession('refid', $GLOBALS['refid']);
3234 // Return determined refid
3235 return $GLOBALS['refid'];
3238 // Enables the reset mode and runs it
3239 function doReset () {
3240 // Enable the reset mode
3241 $GLOBALS['reset_enabled'] = true;
3244 runFilterChain('reset');
3247 // Our shutdown-function
3248 function shutdown () {
3249 // Call the filter chain 'shutdown'
3250 runFilterChain('shutdown', null);
3252 if (SQL_IS_LINK_UP()) {
3254 SQL_CLOSE(__FILE__, __LINE__);
3255 } elseif (!isInstallationPhase()) {
3257 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3260 // Stop executing here
3264 // Setter for userid
3265 function setUserId ($userid) {
3266 $GLOBALS['userid'] = bigintval($userid);
3269 // Getter for userid or returns zero
3270 function getUserId () {
3274 // Is the userid set?
3275 if (isUserIdSet()) {
3277 $userid = $GLOBALS['userid'];
3284 // Checks ether the userid is set
3285 function isUserIdSet () {
3286 return (isset($GLOBALS['userid']));
3289 // Handle message codes from URL
3290 function handleCodeMessage () {
3291 if (isGetRequestElementSet('code')) {
3292 // Default extension is 'unknown'
3295 // Is extension given?
3296 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3298 // Convert the 'code' parameter from URL to a human-readable message
3299 $message = getMessageFromErrorCode(getRequestElement('code'));
3301 // Load message template
3302 loadTemplate('message', false, $message);
3306 // Setter for extra title
3307 function setExtraTitle ($extraTitle) {
3308 $GLOBALS['extra_title'] = $extraTitle;
3311 // Getter for extra title
3312 function getExtraTitle () {
3313 // Is the extra title set?
3314 if (!isExtraTitleSet()) {
3315 // No, then abort here
3316 debug_report_bug('extra_title is not set!');
3320 return $GLOBALS['extra_title'];
3323 // Checks if the extra title is set
3324 function isExtraTitleSet () {
3325 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3328 // Generates a 'extension foo inactive' message
3329 function generateExtensionInactiveMessage ($ext_name) {
3330 // Is the extension empty?
3331 if (empty($ext_name)) {
3332 // This should not happen
3333 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3337 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3339 // Is an admin logged in?
3341 // Then output admin message
3342 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3345 // Return prepared message
3349 // Generates a 'extension foo not installed' message
3350 function generateExtensionNotInstalledMessage ($ext_name) {
3351 // Is the extension empty?
3352 if (empty($ext_name)) {
3353 // This should not happen
3354 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3358 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3360 // Is an admin logged in?
3362 // Then output admin message
3363 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3366 // Return prepared message
3370 // Generates a message depending on if the extension is not installed or not
3372 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3376 // Is the extension not installed or just deactivated?
3377 switch (isExtensionInstalled($ext_name)) {
3378 case true; // Deactivated!
3379 $message = generateExtensionInactiveMessage($ext_name);
3382 case false; // Not installed!
3383 $message = generateExtensionNotInstalledMessage($ext_name);
3386 default: // Should not happen!
3387 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3388 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3392 // Return the message
3396 // Reads a directory recursively by default and searches for files not matching
3397 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3398 // a whole directory.
3399 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3400 // Add default entries we should exclude
3401 $excludeArray[] = '.';
3402 $excludeArray[] = '..';
3403 $excludeArray[] = '.svn';
3404 $excludeArray[] = '.htaccess';
3406 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3411 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3414 while ($baseFile = readdir($dirPointer)) {
3415 // Exclude '.', '..' and entries in $excludeArray automatically
3416 if (in_array($baseFile, $excludeArray, true)) {
3418 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3422 // Construct include filename and FQFN
3423 $fileName = $baseDir . $baseFile;
3424 $FQFN = getConfig('PATH') . $fileName;
3426 // Remove double slashes
3427 $FQFN = str_replace('//', '/', $FQFN);
3429 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3430 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3431 // These Lines are only for debugging!!
3432 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3433 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3434 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3440 // Skip also files with non-matching prefix genericly
3441 if (($recursive === true) && (isDirectory($FQFN))) {
3442 // Is a redirectory so read it as well
3443 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3445 // And skip further processing
3447 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3449 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3451 } elseif (!isFileReadable($FQFN)) {
3452 // Not readable so skip it
3453 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3457 // Is the file a PHP script or other?
3458 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3459 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3460 // Is this a valid include file?
3461 if ($extension == '.php') {
3462 // Remove both for extension name
3463 $extName = substr($baseFile, strlen($prefix), -4);
3465 // Is the extension valid and active?
3466 if (isExtensionNameValid($extName)) {
3467 // Then add this file
3468 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3469 $files[] = $fileName;
3471 // Add non-extension files as well
3472 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3473 if ($addBaseDir === true) {
3474 $files[] = $fileName;
3476 $files[] = $baseFile;
3480 // We found .php file but should not search for them, why?
3481 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3483 } elseif (substr($baseFile, -4, 4) == $extension) {
3484 // Other, generic file found
3485 $files[] = $fileName;
3490 closedir($dirPointer);
3495 // Return array with include files
3496 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3500 // Maps a module name into a database table name
3501 function mapModuleToTable ($moduleName) {
3502 // Map only these, still lame code...
3503 switch ($moduleName) {
3504 // 'index' is the guest's menu
3505 case 'index': $moduleName = 'guest'; break;
3506 // ... and 'login' the member's menu
3507 case 'login': $moduleName = 'member'; break;
3508 // Anything else will not be mapped, silently.
3515 // Add SQL debug data to array for later output
3516 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3517 // Already executed?
3518 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3519 // Then abort here, we don't need to profile a query twice
3523 // Remeber this as profiled (or not, but we don't care here)
3524 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3526 // Do we have cache?
3527 if (!isset($GLOBALS['debug_sql_available'])) {
3528 // Check it and cache it in $GLOBALS
3529 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3532 // Don't execute anything here if we don't need or ext-other is missing
3533 if ($GLOBALS['debug_sql_available'] === false) {
3539 'num_rows' => SQL_NUMROWS($result),
3540 'affected' => SQL_AFFECTEDROWS(),
3541 'sql_str' => $sqlString,
3542 'timing' => $timing,
3543 'file' => basename($F),
3548 $GLOBALS['debug_sqls'][] = $record;
3551 // Initializes the cache instance
3552 function initCacheInstance () {
3553 // Load include for CacheSystem class
3554 loadIncludeOnce('inc/classes/cachesystem.class.php');
3556 // Initialize cache system only when it's needed
3557 $GLOBALS['cache_instance'] = new CacheSystem();
3558 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3559 // Failed to initialize cache sustem
3560 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3564 // Getter for message from array or raw message
3565 function getMessageFromIndexedArray ($message, $pos, $array) {
3566 // Check if the requested message was found in array
3567 if (isset($array[$pos])) {
3568 // ... if yes then use it!
3569 $ret = $array[$pos];
3571 // ... else use default message
3579 // Print code with line numbers
3580 function linenumberCode ($code) {
3581 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3582 $count_lines = count($codeE);
3584 $r = 'Line | Code:<br />';
3585 foreach($codeE as $line => $c) {
3586 $r .= '<div class="line"><span class="linenum">';
3587 if ($count_lines == 1) {
3590 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3595 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3598 return '<div class="code">' . $r . '</div>';
3601 // Convert ';' to ', ' for e.g. receiver list
3602 function convertReceivers ($old) {
3603 return str_replace(';', ', ', $old);
3606 //////////////////////////////////////////////////
3607 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3608 //////////////////////////////////////////////////
3610 if (!function_exists('html_entity_decode')) {
3611 // Taken from documentation on www.php.net
3612 function html_entity_decode ($string) {
3613 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3614 $trans_tbl = array_flip($trans_tbl);
3615 return strtr($string, $trans_tbl);
3619 if (!function_exists('http_build_query')) {
3620 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3621 function http_build_query($data, $prefix='', $sep='', $key='') {
3623 foreach ((array)$data as $k => $v) {
3624 if (is_int($k) && $prefix != null) {
3625 $k = urlencode($prefix . $k);
3628 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3630 if (is_array($v) || is_object($v)) {
3631 array_push($ret, http_build_query($v, '', $sep, $k));
3633 array_push($ret, $k.'='.urlencode($v));
3637 if (empty($sep)) $sep = ini_get('arg_separator.output');
3639 return implode($sep, $ret);