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 ($GLOBALS['output_mode'] == 0) {
357 // Add surrounding HTML comments to help finding bugs faster
358 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
360 // Prepare eval() command
361 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
363 // Prepare eval() command
364 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
367 // Add surrounding HTML comments to help finding bugs faster
368 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
369 $eval = '$ret = "' . smartAddSlashes($ret) . '";';
372 // Cache the eval() command here
373 $GLOBALS['template_eval'][$template] = $eval;
376 eval($GLOBALS['template_eval'][$template]);
379 $GLOBALS['template_eval'][$template] = '404';
381 } elseif (((isAdmin()) || ((isInstalling()) && (!isInstalled()))) && ($GLOBALS['template_eval'][$template] == '404')) {
382 // Only admins shall see this warning or when installation mode is active
383 $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
384 (' . $template . ')<br />
386 {--TEMPLATE_CONTENT--}
387 <pre>' . print_r($content, true) . '</pre>
389 <pre>' . print_r($DATA, true) . '</pre>
393 eval($GLOBALS['template_eval'][$template]);
396 // Do we have some content to output or return?
398 // Not empty so let's put it out! ;)
399 if ($return === true) {
400 // Return the HTML code
406 } elseif (isDebugModeEnabled()) {
407 // Warning, empty output!
408 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
412 // Loads an email template and compiles it
413 function loadEmailTemplate ($template, $content = array(), $UID = 0) {
416 // Our configuration is kept non-global here
417 $_CONFIG = getConfigArray();
419 // Make sure all template names are lowercase!
420 $template = strtolower($template);
422 // Default 'nickname' if extension is not installed
425 // Prepare IP number and User Agent
426 $REMOTE_ADDR = detectRemoteAddr();
427 $HTTP_USER_AGENT = detectUserAgent();
430 $ADMIN = getConfig('MAIN_TITLE');
432 // Is the admin logged in?
435 $adminId = getCurrentAdminId();
438 $ADMIN = getAdminEmail($adminId);
441 // Neutral email address is default
442 $email = getConfig('WEBMASTER');
444 // Expiration in a nice output format
445 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
446 if (getConfig('auto_purge') == 0) {
447 // Will never expire!
448 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
450 // Create nice date string
451 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
454 // Is content an array?
455 if (is_array($content)) {
456 // Add expiration to array, $EXPIRATION is now deprecated!
457 $content['expiration'] = $EXPIRATION;
461 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />");
462 if (($UID > 0) && (is_array($content))) {
463 // If nickname extension is installed, fetch nickname as well
464 if (isExtensionActive('nickname')) {
465 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
467 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email`, `nickname` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
468 array(bigintval($UID)), __FUNCTION__, __LINE__);
470 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
472 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
473 array(bigintval($UID)), __FUNCTION__, __LINE__);
476 // Fetch and merge data
477 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
478 $content = merge_array($content, SQL_FETCHARRAY($result));
479 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
482 SQL_FREERESULT($result);
485 // Translate M to male or F to female if present
486 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
488 // Overwrite email from data if present
489 if (isset($content['email'])) $email = $content['email'];
491 // Store email for some functions in global data array
492 $DATA['email'] = $email;
495 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
497 // Check for admin/guest/member templates
498 if (substr($template, 0, 6) == 'admin_') {
499 // Admin template found
500 $FQFN = $basePath.'admin/' . $template.'.tpl';
501 } elseif (substr($template, 0, 6) == 'guest_') {
502 // Guest template found
503 $FQFN = $basePath.'guest/' . $template.'.tpl';
504 } elseif (substr($template, 0, 7) == 'member_') {
505 // Member template found
506 $FQFN = $basePath.'member/' . $template.'.tpl';
508 // Test for extension
509 $test = substr($template, 0, strpos($template, '_'));
510 if (isExtensionNameValid($test)) {
511 // Set extra path to extension's name
512 $FQFN = $basePath . $test.'/' . $template.'.tpl';
514 // No special filename
515 $FQFN = $basePath . $template.'.tpl';
519 // Does the special template exists?
520 if (!isFileReadable($FQFN)) {
521 // Reset to default template
522 $FQFN = $basePath . $template.'.tpl';
525 // Now does the final template exists?
527 if (isFileReadable($FQFN)) {
528 // The local file does exists so we load it. :)
529 $GLOBALS['tpl_content'] = readFromFile($FQFN);
530 $GLOBALS['tpl_content'] = SQL_ESCAPE($GLOBALS['tpl_content']);
533 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode($GLOBALS['tpl_content'])."\");";
534 eval($GLOBALS['tpl_content']);
535 } elseif (!empty($template)) {
536 // Template file not found!
537 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
538 {--TEMPLATE_CONTENT--}
539 <pre>".print_r($content, true)."</pre>
541 <pre>".print_r($DATA, true)."</pre>
544 // Debug mode not active? Then remove the HTML tags
545 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
547 // No template name supplied!
548 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
551 // Is there some content?
552 if (empty($newContent)) {
554 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
555 // Add last error if the required function exists
556 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
559 // Remove content and data
563 // Compile the code and eval it
564 $eval = '$newContent = "' . compileCode(smartAddSlashes($newContent)) . '";';
571 // Send mail out to an email address
572 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
573 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
575 // Compile subject line (for POINTS constant etc.)
576 eval("\$subject = decodeEntities(\"".compileCode(smartAddSlashes($subject))."\");");
579 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
580 // Value detected, is the message extension installed?
581 // @TODO Extension 'msg' does not exist
582 if (isExtensionActive('msg')) {
583 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
586 // Load email address
587 $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
588 array(bigintval($toEmail)), __FUNCTION__, __LINE__);
589 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />");
591 // Does the user exist?
592 if (SQL_NUMROWS($result_email)) {
593 // Load email address
594 list($toEmail) = SQL_FETCHROW($result_email);
597 $toEmail = getConfig('WEBMASTER');
601 SQL_FREERESULT($result_email);
603 } elseif ($toEmail == 0) {
605 $toEmail = getConfig('WEBMASTER');
607 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
609 // Check for PHPMailer or debug-mode
610 if (!checkPhpMailerUsage()) {
611 // Not in PHPMailer-Mode
612 if (empty($mailHeader)) {
613 // Load email header template
614 $mailHeader = loadEmailTemplate('header');
617 $mailHeader .= loadEmailTemplate('header');
619 } elseif (isDebugModeEnabled()) {
620 if (empty($mailHeader)) {
621 // Load email header template
622 $mailHeader = loadEmailTemplate('header');
625 $mailHeader .= loadEmailTemplate('header');
630 eval("\$toEmail = \"".compileCode(smartAddSlashes($toEmail))."\";");
633 eval("\$message = \"".compileCode(smartAddSlashes($message))."\";");
635 // Fix HTML parameter (default is no!)
636 if (empty($isHtml)) $isHtml = 'N';
637 if (isDebugModeEnabled()) {
638 // In debug mode we want to display the mail instead of sending it away so we can debug this part
640 Headers : ' . htmlentities(trim($mailHeader)) . '
641 To : ' . $toEmail . '
642 Subject : ' . $subject . '
643 Message : ' . $message . '
645 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
646 // Send mail as HTML away
647 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
648 } elseif (!empty($toEmail)) {
650 sendRawEmail($toEmail, $subject, $message, $mailHeader);
651 } elseif ($isHtml != 'Y') {
653 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
657 // Check if legacy or PHPMailer command
658 // @TODO Rewrite this to an extension 'smtp'
660 function checkPhpMailerUsage() {
661 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
664 // Send out a raw email with PHPMailer class or legacy mail() command
665 function sendRawEmail ($toEmail, $subject, $message, $from) {
666 // Shall we use PHPMailer class or legacy mode?
667 if (checkPhpMailerUsage()) {
668 // Use PHPMailer class with SMTP enabled
669 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
670 loadIncludeOnce('inc/phpmailer/class.smtp.php');
673 $mail = new PHPMailer();
674 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
677 $mail->SMTPAuth = true;
678 $mail->Host = getConfig('SMTP_HOSTNAME');
680 $mail->Username = getConfig('SMTP_USER');
681 $mail->Password = getConfig('SMTP_PASSWORD');
683 $mail->From = getConfig('WEBMASTER');
687 $mail->FromName = getConfig('MAIN_TITLE');
688 $mail->Subject = $subject;
689 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
690 $mail->Body = $message;
691 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
692 $mail->WordWrap = 70;
695 $mail->Body = decodeEntities($message);
697 $mail->AddAddress($toEmail, '');
698 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
699 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
700 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
703 // Use legacy mail() command
704 mail($toEmail, $subject, decodeEntities($message), $from);
708 // Generate a password in a specified length or use default password length
709 function generatePassword ($length = 0) {
710 // Auto-fix invalid length of zero
711 if ($length == 0) $length = getConfig('pass_len');
713 // Initialize array with all allowed chars
714 $ABC = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,-,+,_,/,.');
716 // Start creating password
718 for ($i = 0; $i < $length; $i++) {
719 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
722 // When the size is below 40 we can also add additional security by scrambling
723 // it. Otherwise we may corrupt hashes
724 if (strlen($PASS) <= 40) {
725 // Also scramble the password
726 $PASS = scrambleString($PASS);
729 // Return the password
733 // Generates a human-readable timestamp from the Uni* stamp
734 function generateDateTime ($time, $mode = 0) {
735 // Filter out numbers
736 $time = bigintval($time);
738 // If the stamp is zero it mostly didn't "happen"
741 return getMessage('NEVER_HAPPENED');
744 switch (getLanguage()) {
745 case 'de': // German date / time format
747 case 0: $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
748 case 1: $ret = strtolower(date('d.m.Y - H:i', $time)); break;
749 case 2: $ret = date('d.m.Y|H:i', $time); break;
750 case 3: $ret = date('d.m.Y', $time); break;
752 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
757 default: // Default is the US date / time format!
759 case 0: $ret = date('r', $time); break;
760 case 1: $ret = date('Y-m-d - g:i A', $time); break;
761 case 2: $ret = date('y-m-d|H:i', $time); break;
762 case 3: $ret = date('y-m-d', $time); break;
764 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
773 // Translates Y/N to yes/no
774 function translateYesNo ($yn) {
776 $translated = '??? (' . $yn . ')';
778 case 'Y': $translated = getMessage('YES'); break;
779 case 'N': $translated = getMessage('NO'); break;
782 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
790 // Translates the "pool type" into human-readable
791 function translatePoolType ($type) {
792 // Default?type is unknown
793 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
796 $constName = sprintf("POOL_TYPE_%s", $type);
799 if (isMessageIdValid($constName)) {
801 $translated = getMessage($constName);
804 // Return "translation"
808 // Translates the american decimal dot into a german comma
809 function translateComma ($dotted, $cut = true, $max = 0) {
810 // Default is 3 you can change this in admin area "Misc -> Misc Options"
811 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
813 // Use from config is default
814 $maxComma = getConfig('max_comma');
816 // Use from parameter?
817 if ($max > 0) $maxComma = $max;
820 if (($cut === true) && ($max == 0)) {
821 // Test for commata if in cut-mode
822 $com = explode('.', $dotted);
823 if (count($com) < 2) {
824 // Don't display commatas even if there are none... ;-)
830 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
833 switch (getLanguage()) {
834 case 'de': // German language
835 $dotted = number_format($dotted, $maxComma, ',', '.');
838 default: // All others
839 $dotted = number_format($dotted, $maxComma, '.', ',');
843 // Return translated value
847 // Translate Uni*-like gender to human-readable
848 function translateGender ($gender) {
850 $ret = '!' . $gender . '!';
852 // Male/female or company?
854 case 'M': $ret = getMessage('GENDER_M'); break;
855 case 'F': $ret = getMessage('GENDER_F'); break;
856 case 'C': $ret = getMessage('GENDER_C'); break;
858 // Log unknown gender
859 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
863 // Return translated gender
867 // "Translates" the user status
868 function translateUserStatus ($status) {
869 // Generate message depending on status
874 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
879 $ret = getMessage('ACCOUNT_DELETED');
883 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
884 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
892 // Generates an URL for the dereferer
893 function generateDerefererUrl ($URL) {
894 // Don't de-refer our own links!
895 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
896 // De-refer this link
897 $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
904 // Generates an URL for the frametester
905 function generateFrametesterUrl ($URL) {
906 // Prepare frametester URL
907 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
908 encodeString(compileUriCode($URL))
911 // Return the new URL
912 return $frametesterUrl;
915 // Count entries from e.g. a selection box
916 function countSelection ($array) {
918 if (!is_array($array)) {
920 debug_report_bug(__FUNCTION__.': No array provided.');
927 foreach ($array as $key => $selected) {
929 if (!empty($selected)) $ret++;
932 // Return counted selections
936 // Generate XHTML code for the CAPTCHA
937 function generateCaptchaCode ($code, $type, $DATA, $userid) {
938 return '<img border="0" alt="Code ' . $code . '" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
941 // Generates a timestamp (some wrapper for mktime())
942 function makeTime ($hours, $minutes, $seconds, $stamp) {
943 // Extract day, month and year from given timestamp
944 $days = date('d', $stamp);
945 $months = date('m', $stamp);
946 $years = date('Y', $stamp);
948 // Create timestamp for wished time which depends on extracted date
959 // Redirects to an URL and if neccessarry extends it with own base URL
960 function redirectToUrl ($URL) {
961 // Compile out URI codes
962 $URL = compileUriCode($URL);
964 // Check if http(s):// is there
965 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
966 // Make all URLs full-qualified
967 $URL = getConfig('URL') . '/' . $URL;
970 // Three different debug ways...
971 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
972 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $URL);
973 //* DEBUG: */ die($URL);
975 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
976 $rel = ' rel="external"';
978 // Do we have internal or external URL?
979 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
980 // Own (=internal) URL
985 $GLOBALS['output'] = ob_get_contents();
987 // Clear it only if there is content
988 if (!empty($GLOBALS['output'])) {
992 // Simple probe for bots/spiders from search engines
993 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
994 // Secure the URL against bad things such als HTML insertions and so on...
995 $URL = secureString($URL);
997 // Output new location link as anchor
998 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
999 } elseif (!headers_sent()) {
1000 // Load URL when headers are not sent
1001 //* DEBUG: */ debug_report_bug("URL={$URL}");
1002 sendHeader('Location: '.str_replace('&', '&', $URL));
1004 // Output error message
1005 loadInclude('inc/header.php');
1006 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
1007 loadInclude('inc/footer.php');
1010 // Shut the mailer down here
1014 // Wrapper for redirectToUrl but URL comes from a configuration entry
1015 function redirectToConfiguredUrl ($configEntry) {
1017 $URL = getConfig($configEntry);
1020 if (is_null($URL)) {
1022 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1026 redirectToUrl($URL);
1029 // Compiles the given HTML/mail code
1030 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1031 // Is the code a string?
1032 if (!is_string($code)) {
1033 // Silently return it
1037 // Init replacement-array with full security characters
1038 $secChars = $GLOBALS['security_chars'];
1040 // Select smaller set of chars to replace when we e.g. want to compile URLs
1041 if ($full === false) $secChars = $GLOBALS['url_chars'];
1043 // Compile more through a filter
1044 $code = runFilterChain('compile_code', $code);
1046 // Compile constants
1047 if ($constants === true) {
1048 // BEFORE 0.2.1 : Language and data constants
1049 // WITH 0.2.1+ : Only language constants
1050 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1052 // BEFORE 0.2.1 : Not used
1053 // WITH 0.2.1+ : Data constants
1054 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1057 // Compile QUOT and other non-HTML codes
1058 foreach ($secChars['to'] as $k => $to) {
1059 // Do the reversed thing as in inc/libs/security_functions.php
1060 $code = str_replace($to, $secChars['from'][$k], $code);
1063 // But shall I keep simple quotes for later use?
1064 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1066 // Find $content[bla][blub] entries
1067 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1069 // Are some matches found?
1070 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1071 // Replace all matches
1072 $matchesFound = array();
1073 foreach ($matches[0] as $key => $match) {
1074 // Fuzzy look has failed by default
1075 $fuzzyFound = false;
1077 // Fuzzy look on match if already found
1078 foreach ($matchesFound as $found => $set) {
1080 $test = substr($found, 0, strlen($match));
1082 // Does this entry exist?
1083 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1084 if ($test == $match) {
1086 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1093 if ($fuzzyFound === true) continue;
1095 // Take all string elements
1096 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1097 // Replace it in the code
1098 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1099 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1100 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1101 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1102 $matchesFound[$match] = 1;
1103 } elseif (!isset($matchesFound[$match])) {
1104 // Not yet replaced!
1105 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1106 $code = str_replace($match, "\"." . $match.".\"", $code);
1107 $matchesFound[$match] = 1;
1112 // Return compiled code
1116 /************************************************************************
1118 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1119 * $a_sort sortiert: *
1121 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1122 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1123 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1124 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1125 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1127 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1128 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1129 * Sie, dass es doch nicht so schwer ist! :-) *
1131 ************************************************************************/
1132 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1134 while ($primary_key < count($a_sort)) {
1135 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1136 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1138 if ($nums === false) {
1139 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1140 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1141 } elseif ($key != $key2) {
1142 // Sort numbers (E.g.: 9 < 10)
1143 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1144 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1148 // We have found two different values, so let's sort whole array
1149 foreach ($dummy as $sort_key => $sort_val) {
1150 $t = $dummy[$sort_key][$key];
1151 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1152 $dummy[$sort_key][$key2] = $t;
1163 // Write back sorted array
1168 function addSelectionBox ($type, $default, $prefix = '', $id = 0) {
1171 if ($type == 'yn') {
1172 // This is a yes/no selection only!
1173 if ($id > 0) $prefix .= "[" . $id."]";
1174 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1176 // Begin with regular selection box here
1177 if (!empty($prefix)) $prefix .= "_";
1179 if ($id > 0) $type2 .= "[" . $id."]";
1180 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1185 for ($idx = 1; $idx < 32; $idx++) {
1186 $OUT .= "<option value=\"" . $idx."\"";
1187 if ($default == $idx) $OUT .= ' selected="selected"';
1188 $OUT .= ">" . $idx."</option>\n";
1192 case 'month': // Month
1193 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1194 $OUT .= "<option value=\"" . $month."\"";
1195 if ($default == $month) $OUT .= ' selected="selected"';
1196 $OUT .= ">" . $descr."</option>\n";
1200 case 'year': // Year
1202 $year = date('Y', time());
1204 // Use configured min age or fixed?
1205 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1207 $startYear = $year - getConfig('min_age');
1210 $startYear = $year - 16;
1213 // Calculate earliest year (100 years old people can still enter Internet???)
1214 $minYear = $year - 100;
1216 // Check if the default value is larger than minimum and bigger than actual year
1217 if (($default > $minYear) && ($default >= $year)) {
1218 for ($idx = $year; $idx < ($year + 11); $idx++) {
1219 $OUT .= "<option value=\"" . $idx."\"";
1220 if ($default == $idx) $OUT .= ' selected="selected"';
1221 $OUT .= ">" . $idx."</option>\n";
1223 } elseif ($default == -1) {
1224 // Current year minus 1
1225 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1227 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1230 // Get current year and subtract the configured minimum age
1231 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1232 // Calculate earliest year depending on extension version
1233 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1234 // Use configured minimum age
1235 $year = date('Y', time()) - getConfig('min_age');
1237 // Use fixed 16 years age
1238 $year = date('Y', time()) - 16;
1241 // Construct year selection list
1242 for ($idx = $minYear; $idx <= $year; $idx++) {
1243 $OUT .= "<option value=\"" . $idx."\"";
1244 if ($default == $idx) $OUT .= ' selected="selected"';
1245 $OUT .= ">" . $idx."</option>\n";
1252 for ($idx = 0; $idx < 60; $idx+=5) {
1253 if (strlen($idx) == 1) $idx = 0 . $idx;
1254 $OUT .= "<option value=\"" . $idx."\"";
1255 if ($default == $idx) $OUT .= ' selected="selected"';
1256 $OUT .= ">" . $idx."</option>\n";
1261 for ($idx = 0; $idx < 24; $idx++) {
1262 if (strlen($idx) == 1) $idx = 0 . $idx;
1263 $OUT .= "<option value=\"" . $idx."\"";
1264 if ($default == $idx) $OUT .= ' selected="selected"';
1265 $OUT .= ">" . $idx."</option>\n";
1270 $OUT .= "<option value=\"Y\"";
1271 if ($default == 'Y') $OUT .= ' selected="selected"';
1272 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1273 if ($default != 'Y') $OUT .= ' selected="selected"';
1274 $OUT .= ">{--NO--}</option>\n";
1277 $OUT .= " </select>\n";
1282 // Deprecated : $length
1285 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1286 // Build server string
1287 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1290 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1291 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1292 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1293 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1294 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1296 // Build string from misc data
1297 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1299 // Add more additional data
1300 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1302 // Add referal id, language, theme and userid
1303 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1304 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1305 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1306 $data .= getConfig('ENCRYPT_SEPERATOR') . getUserId();
1308 // Calculate number for generating the code
1309 $a = $code + getConfig('_ADD') - 1;
1311 if (isConfigEntrySet('master_hash')) {
1312 // Generate hash with master salt from modula of number with the prime number and other data
1313 $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'));
1315 // Create number from hash
1316 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1318 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1319 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, 8));
1321 // Create number from hash
1322 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1325 // At least 10 numbers shall be secure enought!
1326 $len = getConfig('code_length');
1327 if ($len == 0) $len = $length;
1328 if ($len == 0) $len = 10;
1330 // Cut off requested counts of number
1331 $return = substr(str_replace('.', '', $rcode), 0, $len);
1333 // Done building code
1337 // Does only allow numbers
1338 function bigintval ($num, $castValue = true) {
1339 // Filter all numbers out
1340 $ret = preg_replace('/[^0123456789]/', '', $num);
1343 if ($castValue) $ret = (double)$ret;
1345 // Has the whole value changed?
1346 // @TODO Remove this if() block if all is working fine
1347 if ('' . $ret . '' != '' . $num . '') {
1349 //debug_report_bug("{$ret}<>{$num}");
1356 // Insert the code in $img_code into jpeg or PNG image
1357 function generateImageOrCode ($img_code, $headerSent=true) {
1358 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1359 // Stop execution of function here because of over-sized code length
1361 } elseif ($headerSent === false) {
1362 // Return in an HTML code code
1363 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1367 $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
1368 if (isFileReadable($img)) {
1369 // Switch image type
1370 switch (getConfig('img_type'))
1373 // Okay, load image and hide all errors
1374 $image = imagecreatefromjpeg($img);
1378 // Okay, load image and hide all errors
1379 $image = imagecreatefrompng($img);
1383 // Exit function here
1384 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1388 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1389 $text_color = imagecolorallocate($image, 0, 0, 0);
1391 // Insert code into image
1392 imagestring($image, 5, 14, 2, $img_code, $text_color);
1394 // Return to browser
1395 sendHeader('Content-Type: image/' . getConfig('img_type'));
1397 // Output image with matching image factory
1398 switch (getConfig('img_type')) {
1399 case 'jpg': imagejpeg($image); break;
1400 case 'png': imagepng($image); break;
1403 // Remove image from memory
1404 imagedestroy($image);
1406 // Create selection box or array of splitted timestamp
1407 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1408 // Calculate 2-seconds timestamp
1409 $stamp = round($timestamp);
1410 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1412 // Do we have a leap year?
1414 $TEST = date('Y', time()) / 4;
1415 $M1 = date('m', time());
1416 $M2 = date('m', (time() + $timestamp));
1418 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1419 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1421 // First of all years...
1422 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1423 //* DEBUG: */ print("Y={$Y}<br />");
1425 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1426 //* DEBUG: */ print("M={$M}<br />");
1428 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1429 //* DEBUG: */ print("W={$W}<br />");
1431 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1432 //* DEBUG: */ print("D={$D}<br />");
1434 $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));
1435 //* DEBUG: */ print("h={$h}<br />");
1437 $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));
1438 //* DEBUG: */ print("m={$m}<br />");
1439 // And at last seconds...
1440 $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));
1441 //* DEBUG: */ print("s={$s}<br />");
1443 // Is seconds zero and time is < 60 seconds?
1444 if (($s == 0) && ($timestamp < 60)) {
1446 $s = round($timestamp);
1450 // Now we convert them in seconds...
1452 if ($return_array) {
1453 // Just put all data in an array for later use
1465 $OUT = "<div align=\"" . $align."\">\n";
1466 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1469 if (ereg('Y', $display) || (empty($display))) {
1470 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1473 if (ereg('M', $display) || (empty($display))) {
1474 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1477 if (ereg("W", $display) || (empty($display))) {
1478 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1481 if (ereg("D", $display) || (empty($display))) {
1482 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1485 if (ereg("h", $display) || (empty($display))) {
1486 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1489 if (ereg('m', $display) || (empty($display))) {
1490 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1493 if (ereg("s", $display) || (empty($display))) {
1494 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1500 if (ereg('Y', $display) || (empty($display))) {
1501 // Generate year selection
1502 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1503 for ($idx = 0; $idx <= 10; $idx++) {
1504 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1505 if ($idx == $Y) $OUT .= ' selected="selected"';
1506 $OUT .= ">" . $idx."</option>\n";
1508 $OUT .= " </select></td>\n";
1510 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1513 if (ereg('M', $display) || (empty($display))) {
1514 // Generate month selection
1515 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1516 for ($idx = 0; $idx <= 11; $idx++)
1518 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1519 if ($idx == $M) $OUT .= ' selected="selected"';
1520 $OUT .= ">" . $idx."</option>\n";
1522 $OUT .= " </select></td>\n";
1524 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1527 if (ereg("W", $display) || (empty($display))) {
1528 // Generate week selection
1529 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1530 for ($idx = 0; $idx <= 4; $idx++) {
1531 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1532 if ($idx == $W) $OUT .= ' selected="selected"';
1533 $OUT .= ">" . $idx."</option>\n";
1535 $OUT .= " </select></td>\n";
1537 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1540 if (ereg("D", $display) || (empty($display))) {
1541 // Generate day selection
1542 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1543 for ($idx = 0; $idx <= 31; $idx++) {
1544 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1545 if ($idx == $D) $OUT .= ' selected="selected"';
1546 $OUT .= ">" . $idx."</option>\n";
1548 $OUT .= " </select></td>\n";
1550 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1553 if (ereg("h", $display) || (empty($display))) {
1554 // Generate hour selection
1555 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1556 for ($idx = 0; $idx <= 23; $idx++) {
1557 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1558 if ($idx == $h) $OUT .= ' selected="selected"';
1559 $OUT .= ">" . $idx."</option>\n";
1561 $OUT .= " </select></td>\n";
1563 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1566 if (ereg('m', $display) || (empty($display))) {
1567 // Generate minute selection
1568 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1569 for ($idx = 0; $idx <= 59; $idx++) {
1570 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1571 if ($idx == $m) $OUT .= ' selected="selected"';
1572 $OUT .= ">" . $idx."</option>\n";
1574 $OUT .= " </select></td>\n";
1576 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1579 if (ereg("s", $display) || (empty($display))) {
1580 // Generate second selection
1581 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1582 for ($idx = 0; $idx <= 59; $idx++) {
1583 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1584 if ($idx == $s) $OUT .= ' selected="selected"';
1585 $OUT .= ">" . $idx."</option>\n";
1587 $OUT .= " </select></td>\n";
1589 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1592 $OUT .= "</table>\n";
1594 // Return generated HTML code
1600 function createTimestampFromSelections ($prefix, $postData) {
1601 // Initial return value
1604 // Do we have a leap year?
1606 $TEST = date('Y', time()) / 4;
1607 $M1 = date('m', time());
1608 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1609 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1610 // First add years...
1611 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1613 $ret += $postData[$prefix."_mo"] * 2628000;
1615 $ret += $postData[$prefix."_we"] * 604800;
1617 $ret += $postData[$prefix."_da"] * 86400;
1619 $ret += $postData[$prefix."_ho"] * 3600;
1621 $ret += $postData[$prefix."_mi"] * 60;
1622 // And at last seconds...
1623 $ret += $postData[$prefix."_se"];
1624 // Return calculated value
1628 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1629 function createFancyTime ($stamp) {
1630 // Get data array with years/months/weeks/days/...
1631 $data = createTimeSelections($stamp, '', '', '', true);
1633 foreach($data as $k => $v) {
1635 // Value is greater than 0 "eval" data to return string
1636 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1641 // Do we have something there?
1642 if (strlen($ret) > 0) {
1643 // Remove leading commata and space
1644 $ret = substr($ret, 2);
1647 $ret = "0 {--_SECONDS--}";
1650 // Return fancy time string
1654 // Generates a navigation row for listing emails
1655 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1656 $SEP = ''; $TOP = '';
1657 if ($show_form === false) {
1659 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1663 for ($page = 1; $page <= $PAGES; $page++) {
1664 // Is the page currently selected or shall we generate a link to it?
1665 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1666 // Is currently selected, so only highlight it
1667 $NAV .= '<strong>-';
1669 // Open anchor tag and add base URL
1670 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1672 // Add userid when we shall show all mails from a single member
1673 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1675 // Close open anchor tag
1679 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1680 // Is currently selected, so only highlight it
1681 $NAV .= '-</strong>';
1687 // Add seperator if we have not yet reached total pages
1688 if ($page < $PAGES) $NAV .= ' | ';
1691 // Define constants only once
1692 $content['nav'] = $NAV;
1693 $content['span'] = $colspan;
1694 $content['top'] = $TOP;
1695 $content['sep'] = $SEP;
1697 // Load navigation template
1698 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1700 if ($return === true) {
1701 // Return generated HTML-Code
1709 // Extract host from script name
1710 function extractHostnameFromUrl (&$script) {
1711 // Use default SERVER_URL by default... ;) So?
1712 $url = getConfig('SERVER_URL');
1714 // Is this URL valid?
1715 if (substr($script, 0, 7) == 'http://') {
1716 // Use the hostname from script URL as new hostname
1717 $url = substr($script, 7);
1718 $extract = explode('/', $url);
1720 // Done extracting the URL :)
1723 // Extract host name
1724 $host = str_replace('http://', '', $url);
1725 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1727 // Generate relative URL
1728 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1729 if (substr(strtolower($script), 0, 7) == 'http://') {
1730 // But only if http:// is in front!
1731 $script = substr($script, (strlen($url) + 7));
1732 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1734 $script = substr($script, (strlen($url) + 8));
1737 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1738 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1744 // Send a GET request
1745 function sendGetRequest ($script, $data = array()) {
1746 // Extract host name from script
1747 $host = extractHostnameFromUrl($script);
1750 $scriptData = http_build_query($data, '', '&');
1752 // Do we have a question-mark in the script?
1753 if (strpos($script, '?') === false) {
1754 // No, so first char must be question mark
1755 $scriptData = '?' . $scriptData;
1758 $scriptData = '&' . $scriptData;
1762 $script .= $scriptData;
1764 // Generate GET request header
1765 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1766 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1767 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1768 if (isConfigEntrySet('FULL_VERSION')) {
1769 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1771 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1773 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1774 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1775 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1777 // Send the raw request
1778 $response = sendRawRequest($host, $request);
1780 // Return the result to the caller function
1784 // Send a POST request
1785 function sendPostRequest ($script, $postData) {
1786 // Is postData an array?
1787 if (!is_array($postData)) {
1789 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1790 return array('', '', '');
1793 // Compile the script name
1794 $script = compileCode($script);
1796 // Extract host name from script
1797 $host = extractHostnameFromUrl($script);
1799 // Construct request
1800 $data = http_build_query($postData, '', '&');
1802 // Generate POST request header
1803 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1804 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1805 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1806 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1807 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1808 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1809 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1810 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1813 // Send the raw request
1814 $response = sendRawRequest($host, $request);
1816 // Return the result to the caller function
1820 // Sends a raw request to another host
1821 function sendRawRequest ($host, $request) {
1822 // Init errno and errdesc with 'all fine' values
1823 $errno = 0; $errdesc = '';
1826 $response = array('', '', '');
1828 // Default is not to use proxy
1831 // Are proxy settins set?
1832 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1838 //* DEBUG: */ die("SCRIPT=" . $script."<br />");
1839 if ($useProxy === true) {
1840 // Connect to host through proxy connection
1841 $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1843 // Connect to host directly
1844 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1848 if (!is_resource($fp)) {
1854 if ($useProxy === true) {
1855 // Generate CONNECT request header
1856 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1857 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1859 // Use login data to proxy? (username at least!)
1860 if (getConfig('proxy_username') != '') {
1862 $encodedAuth = base64_encode(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
1863 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1866 // Add last new-line
1867 $proxyTunnel .= getConfig('HTTP_EOL');
1868 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1871 fputs($fp, $proxyTunnel);
1875 // No response received
1879 // Read the first line
1880 $resp = trim(fgets($fp, 10240));
1881 $respArray = explode(' ', $resp);
1882 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1883 // Invalid response!
1889 fputs($fp, $request);
1892 while (!feof($fp)) {
1893 $response[] = trim(fgets($fp, 1024));
1899 // Skip first empty lines
1901 foreach ($resp as $idx => $line) {
1903 $line = trim($line);
1905 // Is this line empty?
1908 array_shift($response);
1910 // Abort on first non-empty line
1915 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1917 // Proxy agent found?
1918 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1919 // Proxy header detected, so remove two lines
1920 array_shift($response);
1921 array_shift($response);
1924 // Was the request successfull?
1925 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1926 // Not found / access forbidden
1927 $response = array('', '', '');
1934 // Taken from www.php.net eregi() user comments
1935 function isEmailValid ($email) {
1937 $email = compileCode($email);
1939 // Check first part of email address
1940 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1943 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1946 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1948 // Return check result
1949 return preg_match($regex, $email);
1952 // Function taken from user comments on www.php.net / function eregi()
1953 function isUrlValid ($URL, $compile=true) {
1954 // Trim URL a little
1955 $URL = trim(urldecode($URL));
1956 //* DEBUG: */ outputHtml($URL."<br />");
1958 // Compile some chars out...
1959 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1960 //* DEBUG: */ outputHtml($URL."<br />");
1962 // Check for the extension filter
1963 if (isExtensionActive('filter')) {
1964 // Use the extension's filter set
1965 return FILTER_VALIDATE_URL($URL, false);
1968 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1969 // https:// in front of the URLs
1970 return isUrlValidSimple($URL);
1973 // Generate a list of administrative links to a given userid
1974 function generateMemberAdminActionLinks ($userid, $status = '') {
1975 // Make sure userid is a number
1976 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1978 // Define all main targets
1979 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1981 // Begin of navigation links
1984 foreach ($targetArray as $tar) {
1985 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1986 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1987 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1988 // Locked accounts shall be unlocked
1989 $OUT .= 'UNLOCK_USER';
1991 // All other status is fine
1992 $OUT .= strtoupper($tar);
1994 $OUT .= "_TITLE--}\">{--ADMIN_";
1995 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1996 // Locked accounts shall be unlocked
1997 $OUT .= 'UNLOCK_USER';
1999 // All other status is fine
2000 $OUT .= strtoupper($tar);
2002 $OUT .= "--}</a></span> | ";
2005 // Finish navigation link
2006 $OUT = substr($OUT, 0, -7) . ']';
2012 // Generate an email link
2013 function generateEmailLink ($email, $table = 'admins') {
2014 // Default email link (INSECURE! Spammer can read this by harvester programs)
2015 $EMAIL = 'mailto:' . $email;
2017 // Check for several extensions
2018 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2019 // Create email link for contacting admin in guest area
2020 $EMAIL = generateAdminEmailLink($email);
2021 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2022 // Create email link for contacting a member within admin area (or later in other areas, too?)
2023 $EMAIL = generateUserEmailLink($email, 'admin');
2024 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2025 // Create email link to contact sponsor within admin area (or like the link above?)
2026 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2029 // Shall I close the link when there is no admin?
2030 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2032 // Return email link
2036 // Generate a hash for extra-security for all passwords
2037 function generateHash ($plainText, $salt = '') {
2038 // Is the required extension 'sql_patches' there and a salt is not given?
2039 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches'))) && (empty($salt))) {
2040 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2041 return md5($plainText);
2044 // Do we miss an arry element here?
2045 if (!isConfigEntrySet('file_hash')) {
2047 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2050 // When the salt is empty build a new one, else use the first x configured characters as the salt
2052 // Build server string (inc/databases.php is no longer updated with every commit)
2053 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2056 $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');
2059 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2061 // Calculate number for generating the code
2062 $a = time() + getConfig('_ADD') - 1;
2064 // Generate SHA1 sum from modula of number and the prime number
2065 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2066 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2067 $sha1 = scrambleString($sha1);
2068 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2069 //* DEBUG: */ $sha1b = descrambleString($sha1);
2070 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2072 // Generate the password salt string
2073 $salt = substr($sha1, 0, getConfig('salt_length'));
2074 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2077 $salt = substr($salt, 0, getConfig('salt_length'));
2078 //* DEBUG: */ outputHtml("GIVEN={$salt}<br />");
2082 return $salt.sha1($salt . $plainText);
2085 // Scramble a string
2086 function scrambleString($str) {
2090 // Final check, in case of failture it will return unscrambled string
2091 if (strlen($str) > 40) {
2092 // The string is to long
2094 } elseif (strlen($str) == 40) {
2096 $scrambleNums = explode(':', getConfig('pass_scramble'));
2098 // Generate new numbers
2099 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2102 // Scramble string here
2103 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2104 for ($idx = 0; $idx < strlen($str); $idx++) {
2105 // Get char on scrambled position
2106 $char = substr($str, $scrambleNums[$idx], 1);
2108 // Add it to final output string
2109 $scrambled .= $char;
2112 // Return scrambled string
2113 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2117 // De-scramble a string scrambled by scrambleString()
2118 function descrambleString($str) {
2119 // Scramble only 40 chars long strings
2120 if (strlen($str) != 40) return $str;
2122 // Load numbers from config
2123 $scrambleNums = explode(':', getConfig('pass_scramble'));
2126 if (count($scrambleNums) != 40) return $str;
2128 // Begin descrambling
2129 $orig = str_repeat(' ', 40);
2130 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2131 for ($idx = 0; $idx < 40; $idx++) {
2132 $char = substr($str, $idx, 1);
2133 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2136 // Return scrambled string
2137 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2141 // Generated a "string" for scrambling
2142 function genScrambleString ($len) {
2143 // Prepare array for the numbers
2144 $scrambleNumbers = array();
2146 // First we need to setup randomized numbers from 0 to 31
2147 for ($idx = 0; $idx < $len; $idx++) {
2149 $rand = mt_rand(0, ($len -1));
2151 // Check for it by creating more numbers
2152 while (array_key_exists($rand, $scrambleNumbers)) {
2153 $rand = mt_rand(0, ($len -1));
2157 $scrambleNumbers[$rand] = $rand;
2160 // So let's create the string for storing it in database
2161 $scrambleString = implode(':', $scrambleNumbers);
2162 return $scrambleString;
2165 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2166 function generatePassString ($passHash) {
2167 // Return vanilla password hash
2170 // Is a secret key and master salt already initialized?
2171 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2172 // Only calculate when the secret key is generated
2173 $newHash = ''; $start = 9;
2174 for ($idx = 0; $idx < 10; $idx++) {
2175 $part1 = hexdec(substr($passHash, $start, 4));
2176 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2177 $mod = dechex($idx);
2178 if ($part1 > $part2) {
2179 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2180 } elseif ($part2 > $part1) {
2181 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2183 $mod = substr(round($mod), 0, 4);
2184 $mod = str_repeat(0, 4-strlen($mod)) . $mod;
2185 //* DEBUG: */ outputHtml("*" . $start.'=' . $mod."*<br />");
2190 //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
2191 $ret = generateHash($newHash, getConfig('master_salt'));
2192 //* DEBUG: */ print($ret."<br />");
2195 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2196 $ret = md5($passHash);
2197 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2204 // Fix "deleted" cookies
2205 function fixDeletedCookies ($cookies) {
2206 // Is this an array with entries?
2207 if ((is_array($cookies)) && (count($cookies) > 0)) {
2208 // Then check all cookies if they are marked as deleted!
2209 foreach ($cookies as $cookieName) {
2210 // Is the cookie set to "deleted"?
2211 if (getSession($cookieName) == 'deleted') {
2212 setSession($cookieName, '');
2218 // Output error messages in a fasioned way and die...
2219 function app_die ($F, $L, $message) {
2220 // Check if Script is already dieing and not let it kill itself another 1000 times
2221 if (!isset($GLOBALS['app_died'])) {
2222 // Make sure, that the script realy realy diese here and now
2223 $GLOBALS['app_died'] = true;
2226 loadIncludeOnce('inc/header.php');
2228 // Rewrite message for output
2229 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2231 // Better log this message away
2232 logDebugMessage($F, $L, $message);
2234 // Load the message template
2235 loadTemplate('admin_settings_saved', false, $message);
2238 loadIncludeOnce('inc/footer.php');
2240 // Script tried to kill itself twice
2241 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2245 // Display parsing time and number of SQL queries in footer
2246 function displayParsingTime() {
2247 // Is the timer started?
2248 if (!isset($GLOBALS['startTime'])) {
2254 $endTime = microtime(true);
2256 // "Explode" both times
2257 $start = explode(' ', $GLOBALS['startTime']);
2258 $end = explode(' ', $endTime);
2259 $runTime = $end[0] - $start[0];
2260 if ($runTime < 0) $runTime = 0;
2264 'runtime' => translateComma($runTime),
2265 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2268 // Load the template
2269 loadTemplate('show_timings', false, $content);
2272 // Check wether a boolean constant is set
2273 // Taken from user comments in PHP documentation for function constant()
2274 function isBooleanConstantAndTrue ($constName) { // : Boolean
2275 // Failed by default
2279 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2281 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2282 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2285 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2286 if (defined($constName)) {
2288 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2289 $res = (constant($constName) === true);
2293 $GLOBALS['cache_array']['const'][$constName] = $res;
2295 //* DEBUG: */ var_dump($res);
2301 // Checks if a given apache module is loaded
2302 function isApacheModuleLoaded ($apacheModule) {
2303 // Check it and return result
2304 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2307 // Get current theme name
2308 function getCurrentTheme () {
2309 // The default theme is 'default'... ;-)
2312 // Load default theme if not empty from configuration
2313 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2315 if (!isSessionVariableSet('mxchange_theme')) {
2316 // Set default theme
2318 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2319 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2320 // Get theme from cookie
2321 $ret = getSession('mxchange_theme');
2324 if (getThemeId($ret) == 0) {
2325 // Fix it to default
2328 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2329 // Prepare FQFN for checking
2330 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2332 // Installation mode active
2333 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2334 // Set cookie from URL data
2335 setTheme(getRequestElement('theme'));
2336 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2337 // Set cookie from posted data
2338 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2342 $ret = getSession('mxchange_theme');
2344 // Invalid design, reset cookie
2348 // Return theme value
2352 // Setter for theme in session
2353 function setTheme ($newTheme) {
2354 setSession('mxchange_theme', $newTheme);
2357 // Get id from theme
2358 // @TODO Try to move this to inc/libs/theme_functions.php
2359 function getThemeId ($name) {
2360 // Is the extension 'theme' installed?
2361 if (!isExtensionActive('theme')) {
2369 // Is the cache entry there?
2370 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2371 // Get the version from cache
2372 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2375 incrementStatsEntry('cache_hits');
2376 } elseif (getExtensionVersion('cache') != '0.1.8') {
2377 // Check if current theme is already imported or not
2378 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2379 array($name), __FUNCTION__, __LINE__);
2382 if (SQL_NUMROWS($result) == 1) {
2384 list($id) = SQL_FETCHROW($result);
2388 SQL_FREERESULT($result);
2395 // Generates an error code from given account status
2396 function generateErrorCodeFromUserStatus ($status) {
2397 // @TODO The status should never be empty
2398 if (empty($status)) {
2399 // Something really bad happend here
2400 debug_report_bug(__FUNCTION__ . ': status is empty.');
2403 // Default error code if unknown account status
2404 $errorCode = getCode('UNKNOWN_STATUS');
2406 // Generate constant name
2407 $constantName = sprintf("ID_%s", $status);
2409 // Is the constant there?
2410 if (isCodeSet($constantName)) {
2412 $errorCode = getCode($constantName);
2415 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2418 // Return error code
2422 // Function to search for the last modifified file
2423 function searchDirsRecursive ($dir, &$last_changed) {
2425 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />");
2426 // Does it match what we are looking for? (We skip a lot files already!)
2427 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2428 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2429 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2430 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />");
2432 // Walk through all entries
2433 foreach ($ds as $d) {
2434 // Generate proper FQFN
2435 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2437 // Is it a file and readable?
2438 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2439 if (isDirectory($FQFN)) {
2440 // $FQFN is a directory so also crawl into this directory
2442 if (!empty($dir)) $newDir = $dir . '/'. $d;
2443 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />");
2444 searchDirsRecursive($newDir, $last_changed);
2445 } elseif (isFileReadable($FQFN)) {
2446 // $FQFN is a filename and no directory
2447 $time = filemtime($FQFN);
2448 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2449 if ($last_changed['time'] < $time) {
2450 // This file is newer as the file before
2451 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2452 $last_changed['path_name'] = $FQFN;
2453 $last_changed['time'] = $time;
2459 // "Getter" for revision/version data
2460 function getActualVersion ($type = 'Revision') {
2461 // By default nothing is new... ;-)
2464 // Is the cache entry there?
2465 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2466 // Found so increase cache hit
2467 incrementStatsEntry('cache_hits');
2470 return $GLOBALS['cache_array']['revision'][$type][0];
2472 // FQFN of revision file
2473 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2475 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2476 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2477 // Forced rebuild of .revision file
2480 // Check for revision file
2481 if (!isFileReadable($FQFN)) {
2482 // Not found, so we need to create it
2485 // Revision file found
2486 $ins_vers = explode("\n", readFromFile($FQFN));
2488 // Get array for mapping information
2489 $mapper = array_flip(getSearchFor());
2490 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2492 // Is the content valid?
2493 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2494 // File needs update!
2497 // Generate fake cache entry
2498 foreach ($mapper as $map=>$idx) {
2499 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2502 // Return found value
2503 return trim($ins_vers[$mapper[$type]]);
2508 // Has it been updated?
2509 if ($new === true) {
2511 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2513 // ... and call recursive
2514 return getActualVersion($type);
2519 // Repares an array we are looking for
2520 // 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
2521 function getSearchFor () {
2522 // Add Revision, Date, Tag and Author
2523 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2525 // Return the created array
2529 // @TODO Please describe this function
2530 function getArrayFromActualVersion () {
2534 // Directory to start with search
2535 $last_changed = array(
2540 // Init return array
2541 $akt_vers = array();
2543 // Init value for counting the founded keywords
2546 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2547 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2550 $last_file = readFromFile($last_changed['path_name']);
2552 // Get all the keywords to search for
2553 $searchFor = getSearchFor();
2555 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2556 foreach ($searchFor as $search) {
2557 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2558 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2559 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2560 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2563 // Save the last-changed filename for debugging
2564 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2566 // at least 3 keyword-Tags are needed for propper values
2567 if ($res && $res >= 3
2568 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2569 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2570 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2571 // Prepare content witch need special treadment
2573 // Prepare timestamp for date
2574 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2575 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2577 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2578 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2579 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2583 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2584 $version = sendGetRequest('check-updates3.php');
2587 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2588 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2589 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2590 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2591 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2592 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2595 // Return prepared array
2596 return $GLOBALS['cache_array']['revision'];
2599 // Back-ported from the new ship-simu engine. :-)
2600 function debug_get_printable_backtrace () {
2602 $backtrace = "<ol>\n";
2604 // Get and prepare backtrace for output
2605 $backtraceArray = debug_backtrace();
2606 foreach ($backtraceArray as $key => $trace) {
2607 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2608 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2609 if (!isset($trace['args'])) $trace['args'] = array();
2610 $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";
2614 $backtrace .= "</ol>\n";
2616 // Return the backtrace
2620 // Output a debug backtrace to the user
2621 function debug_report_bug ($message = '') {
2625 // Is the optional message set?
2626 if (!empty($message)) {
2628 $debug = sprintf("Note: %s<br />\n",
2632 // @TODO Add a little more infos here
2633 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2637 $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>";
2638 $debug .= debug_get_printable_backtrace();
2639 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2640 $debug .= "Thank you for finding bugs.";
2643 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2647 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2648 function generateSeed () {
2649 list($usec, $sec) = explode(' ', microtime());
2650 $microTime = (((float)$sec + (float)$usec)) * 100000;
2654 // Converts a message code to a human-readable message
2655 function getMessageFromErrorCode ($code) {
2659 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2660 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2661 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2662 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2663 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2664 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2665 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2666 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2667 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2668 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2669 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2670 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2671 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2672 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2673 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2674 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2675 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2676 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2677 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2678 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2679 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2680 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2681 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2682 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2683 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2684 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2685 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2686 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2688 case getCode('ERROR_MAILID'):
2689 if (isExtensionActive('mailid', true)) {
2690 $message = getMessage('ERROR_CONFIRMING_MAIL');
2692 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2696 case getCode('EXTENSION_PROBLEM'):
2697 if (isGetRequestElementSet('ext')) {
2698 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2700 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2704 case getCode('URL_TLOCK'):
2705 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2706 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2708 // Load timestamp from last order
2709 list($timestamp) = SQL_FETCHROW($result);
2710 $timestamp = generateDateTime($timestamp, 1);
2713 SQL_FREERESULT($result);
2715 // Calculate hours...
2716 $STD = round(getConfig('url_tlock') / 60 / 60);
2719 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2722 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2724 // Finally contruct the message
2725 // @TODO Rewrite this old lost code to a template
2726 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2727 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2728 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2732 // Missing/invalid code
2733 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2736 logDebugMessage(__FUNCTION__, __LINE__, $message);
2740 // Return the message
2744 // Generate a "link" for the given admin id (admin_id)
2745 function generateAdminLink ($adminId) {
2746 // No assigned admin is default
2747 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2749 // Zero? = Not assigned
2750 if (bigintval($adminId) > 0) {
2751 // Load admin's login
2752 $login = getAdminLogin($adminId);
2754 // Is the login valid?
2755 if ($login != '***') {
2756 // Is the extension there?
2757 if (isExtensionActive('admins')) {
2759 $admin = "<a href=\"".generateEmailLink(getAdminEmail($adminId), 'admins')."\">" . $login."</a>";
2761 // Extension not found
2762 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2766 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $adminId)."</div>";
2774 // Compile characters which are allowed in URLs
2775 function compileUriCode ($code, $simple = true) {
2776 // Compile constants
2777 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2779 // Compile QUOT and other non-HTML codes
2780 $code = str_replace('{DOT}', '.',
2781 str_replace('{SLASH}', '/',
2782 str_replace('{QUOT}', "'",
2783 str_replace('{DOLLAR}', '$',
2784 str_replace('{OPEN_ANCHOR}', '(',
2785 str_replace('{CLOSE_ANCHOR}', ')',
2786 str_replace('{OPEN_SQR}', '[',
2787 str_replace('{CLOSE_SQR}', ']',
2788 str_replace('{PER}', '%',
2792 // Return compiled code
2796 // Function taken from user comments on www.php.net / function eregi()
2797 function isUrlValidSimple ($url) {
2799 $url = secureString(str_replace("\\", '', compileCode(urldecode($url))));
2801 // Allows http and https
2802 $http = "(http|https)+(:\/\/)";
2804 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2805 // Test double-domains (e.g. .de.vu)
2806 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2808 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2810 $dir = "((/)+([-_\.[:alnum:]])+)*";
2812 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2813 // ... and the string after and including question character
2814 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2815 // Pattern for URLs like http://url/dir/doc.html?var=value
2816 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2817 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2818 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2819 // Pattern for URLs like http://url/dir/?var=value
2820 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2821 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2822 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2823 // Pattern for URLs like http://url/dir/page.ext
2824 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2825 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2826 $pattern['ipdp'] = $http . $ip . $dir . $page;
2827 // Pattern for URLs like http://url/dir
2828 $pattern['d1d'] = $http . $domain1 . $dir;
2829 $pattern['d2d'] = $http . $domain2 . $dir;
2830 $pattern['ipd'] = $http . $ip . $dir;
2831 // Pattern for URLs like http://url/?var=value
2832 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2833 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2834 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2835 // Pattern for URLs like http://url?var=value
2836 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2837 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2838 $pattern['ipg12'] = $http . $ip . $getstring1;
2839 // Test all patterns
2841 foreach ($pattern as $key => $pat) {
2843 if (isDebugRegExpressionEnabled()) {
2844 // @TODO Are these convertions still required?
2845 $pat = str_replace('.', "\.", $pat);
2846 $pat = str_replace('@', "\@", $pat);
2847 //* DEBUG: */ outputHtml($key."= " . $pat . "<br />");
2850 // Check if expression matches
2851 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2854 if ($reg === true) break;
2857 // Return true/false
2861 // Wtites data to a config.php-style file
2862 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2863 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2864 // Initialize some variables
2870 // Is the file there and read-/write-able?
2871 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2872 $search = 'CFG: ' . $comment;
2873 $tmp = $FQFN . '.tmp';
2875 // Open the source file
2876 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2878 // Is the resource valid?
2879 if (is_resource($fp)) {
2880 // Open temporary file
2881 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2883 // Is the resource again valid?
2884 if (is_resource($fp_tmp)) {
2885 // Mark temporary file as readable
2886 $GLOBALS['file_readable'][$tmp] = true;
2889 while (!feof($fp)) {
2890 // Read from source file
2891 $line = fgets ($fp, 1024);
2893 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2896 if ($next === $seek) {
2898 $line = $prefix . $DATA . $suffix . "\n";
2904 // Write to temp file
2905 fputs($fp_tmp, $line);
2911 // Finished writing tmp file
2915 // Close source file
2918 if (($done === true) && ($found === true)) {
2919 // Copy back tmp file and delete tmp :-)
2920 copyFileVerified($tmp, $FQFN, 0644);
2921 return removeFile($tmp);
2922 } elseif ($found === false) {
2923 outputHtml('<strong>CHANGE:</strong> 404!');
2925 outputHtml('<strong>TMP:</strong> UNDONE!');
2929 // File not found, not readable or writeable
2930 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2933 // An error was detected!
2936 // Send notification to admin
2937 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = 0) {
2938 if (getExtensionVersion('admins') >= '0.4.1') {
2940 sendAdminsEmails($subject, $templateName, $content, $userid);
2942 // Send out out-dated way
2943 $message = loadEmailTemplate($templateName, $content, $userid);
2944 sendAdminEmails($subject, $message);
2948 // Debug message logger
2949 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2950 // Is debug mode enabled?
2951 if ((isDebugModeEnabled()) || ($force === true)) {
2953 $message = str_replace("\r", '', str_replace("\n", '', $message));
2955 // Log this message away, we better don't call app_die() here to prevent an endless loop
2956 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2957 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2962 // Handle extra values
2963 function handleExtraValues ($filterFunction, $value, $extraValue) {
2964 // Default is the value itself
2967 // Do we have a special filter function?
2968 if (!empty($filterFunction)) {
2969 // Does the filter function exist?
2970 if (function_exists($filterFunction)) {
2971 // Do we have extra parameters here?
2972 if (!empty($extraValue)) {
2973 // Put both parameters in one new array by default
2974 $args = array($value, $extraValue);
2976 // If we have an array simply use it and pre-extend it with our value
2977 if (is_array($extraValue)) {
2978 // Make the new args array
2979 $args = merge_array(array($value), $extraValue);
2982 // Call the multi-parameter call-back
2983 $ret = call_user_func_array($filterFunction, $args);
2985 // One parameter call
2986 $ret = call_user_func($filterFunction, $value);
2995 // Converts timestamp selections into a timestamp
2996 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2997 // Init test variable
3000 // Get last three chars
3001 $test = substr($id, -3);
3003 // Improved way of checking! :-)
3004 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3005 // Found a multi-selection for timings?
3006 $test = substr($id, 0, -3);
3007 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)) {
3008 // Generate timestamp
3009 $postData[$test] = createTimestampFromSelections($test, $postData);
3010 $DATA[] = sprintf("%s='%s'", $test, $postData[$test]);
3012 // Remove data from array
3013 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3014 unset($postData[$test.'_' . $rem]);
3018 unset($id); $skip = true; $test2 = $test;
3021 // Process this entry
3027 // Reverts the german decimal comma into Computer decimal dot
3028 function convertCommaToDot ($str) {
3029 // Default float is not a float... ;-)
3032 // Which language is selected?
3033 switch (getLanguage()) {
3034 case 'de': // German language
3035 // Remove german thousand dots first
3036 $str = str_replace('.', '', $str);
3038 // Replace german commata with decimal dot and cast it
3039 $float = (float)str_replace(',', '.', $str);
3042 default: // US and so on
3043 // Remove thousand dots first and cast
3044 $float = (float)str_replace(',', '', $str);
3052 // Handle menu-depending failed logins and return the rendered content
3053 function handleLoginFailtures ($accessLevel) {
3054 // Default output is empty ;-)
3057 // Is the session data set?
3058 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3059 // Ignore zero values
3060 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3061 // Non-guest has login failures found, get both data and prepare it for template
3062 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3064 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3065 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3069 $OUT = loadTemplate('login_failures', true, $content);
3072 // Reset session data
3073 setSession('mxchange_' . $accessLevel.'_failures', '');
3074 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3077 // Return rendered content
3082 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3084 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3086 // Shall I remove the cache file?
3087 if (isCacheInstanceValid()) {
3089 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3091 $GLOBALS['cache_instance']->removeCacheFile($force);
3094 // Include file given?
3097 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3099 // Is the include there?
3100 if (isIncludeReadable($inc)) {
3101 // And rebuild it from scratch
3102 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3105 // Include not found!
3106 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3112 // Determines the real remote address
3113 function determineRealRemoteAddress () {
3114 // Is a proxy in use?
3115 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3117 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3118 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3119 // Yet, another proxy
3120 $address = $_SERVER['HTTP_CLIENT_IP'];
3122 // The regular address when no proxy was used
3123 $address = $_SERVER['REMOTE_ADDR'];
3126 // This strips out the real address from proxy output
3127 if (strstr($address, ',')) {
3128 $addressArray = explode(',', $address);
3129 $address = $addressArray[0];
3132 // Return the result
3136 // Adds a bonus mail to the queue
3137 // This is a high-level function!
3138 function addNewBonusMail ($data, $mode = '', $output=true) {
3139 // Use mode from data if not set and availble ;-)
3140 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3142 // Generate receiver list
3143 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3146 if (!empty($RECEIVER)) {
3147 // Add bonus mail to queue
3148 addBonusMailToQueue(
3160 // Mail inserted into bonus pool
3161 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3162 } elseif ($output) {
3163 // More entered than can be reached!
3164 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3167 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3171 // Determines referal id and sets it
3172 function determineReferalId () {
3173 // Skip this in non-html-mode
3174 if (getOutputMode() != 0) return false;
3176 // Check if refid is set
3177 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3179 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3180 // The variable user comes from the click-counter script click.php and we only accept this here
3181 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3182 } elseif (isPostRequestElementSet('refid')) {
3183 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3184 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3185 } elseif (isGetRequestElementSet('refid')) {
3186 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3187 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3188 } elseif (isGetRequestElementSet('ref')) {
3189 // Set refid=ref (the referal link uses such variable)
3190 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3191 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3192 // Set session refid als global
3193 $GLOBALS['refid'] = bigintval(getSession('refid'));
3194 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3195 // Select a random user which has confirmed enougth mails
3196 $GLOBALS['refid'] = determineRandomReferalId();
3197 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3198 // Set default refid as refid in URL
3199 $GLOBALS['refid'] = getConfig('def_refid');
3201 // No default ID when sql_patches is not installed or none set
3202 $GLOBALS['refid'] = 0;
3205 // Set cookie when default refid > 0
3206 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == 0) && (getConfig('def_refid') > 0))) {
3208 setSession('refid', $GLOBALS['refid']);
3211 // Return determined refid
3212 return $GLOBALS['refid'];
3215 // Enables the reset mode and runs it
3216 function doReset () {
3217 // Enable the reset mode
3218 $GLOBALS['reset_enabled'] = true;
3221 runFilterChain('reset');
3224 // Our shutdown-function
3225 function shutdown () {
3226 // Call the filter chain 'shutdown'
3227 runFilterChain('shutdown', null);
3229 if (SQL_IS_LINK_UP()) {
3231 SQL_CLOSE(__FILE__, __LINE__);
3232 } elseif (!isInstallationPhase()) {
3234 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3237 // Stop executing here
3241 // Setter for userid
3242 function setUserId ($userid) {
3243 $GLOBALS['userid'] = bigintval($userid);
3246 // Getter for userid or returns zero
3247 function getUserId () {
3251 // Is the userid set?
3252 if (isUserIdSet()) {
3254 $userid = $GLOBALS['userid'];
3261 // Checks ether the userid is set
3262 function isUserIdSet () {
3263 return (isset($GLOBALS['userid']));
3266 // Handle message codes from URL
3267 function handleCodeMessage () {
3268 if (isGetRequestElementSet('code')) {
3269 // Default extension is 'unknown'
3272 // Is extension given?
3273 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3275 // Convert the 'code' parameter from URL to a human-readable message
3276 $message = getMessageFromErrorCode(getRequestElement('code'));
3278 // Load message template
3279 loadTemplate('message', false, $message);
3283 // Setter for extra title
3284 function setExtraTitle ($extraTitle) {
3285 $GLOBALS['extra_title'] = $extraTitle;
3288 // Getter for extra title
3289 function getExtraTitle () {
3290 // Is the extra title set?
3291 if (!isExtraTitleSet()) {
3292 // No, then abort here
3293 debug_report_bug('extra_title is not set!');
3297 return $GLOBALS['extra_title'];
3300 // Checks if the extra title is set
3301 function isExtraTitleSet () {
3302 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3305 // Generates a 'extension foo inactive' message
3306 function generateExtensionInactiveMessage ($ext_name) {
3307 // Is the extension empty?
3308 if (empty($ext_name)) {
3309 // This should not happen
3310 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3314 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3316 // Is an admin logged in?
3318 // Then output admin message
3319 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3322 // Return prepared message
3326 // Generates a 'extension foo not installed' message
3327 function generateExtensionNotInstalledMessage ($ext_name) {
3328 // Is the extension empty?
3329 if (empty($ext_name)) {
3330 // This should not happen
3331 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3335 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3337 // Is an admin logged in?
3339 // Then output admin message
3340 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3343 // Return prepared message
3347 // Generates a message depending on if the extension is not installed or not
3349 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3353 // Is the extension not installed or just deactivated?
3354 switch (isExtensionInstalled($ext_name)) {
3355 case true; // Deactivated!
3356 $message = generateExtensionInactiveMessage($ext_name);
3359 case false; // Not installed!
3360 $message = generateExtensionNotInstalledMessage($ext_name);
3363 default: // Should not happen!
3364 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3365 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3369 // Return the message
3373 // Reads a directory recursively by default and searches for files not matching
3374 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3375 // a whole directory.
3376 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3377 // Add default entries we should exclude
3378 $excludeArray[] = '.';
3379 $excludeArray[] = '..';
3380 $excludeArray[] = '.svn';
3381 $excludeArray[] = '.htaccess';
3383 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3388 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3391 while ($baseFile = readdir($dirPointer)) {
3392 // Exclude '.', '..' and entries in $excludeArray automatically
3393 if (in_array($baseFile, $excludeArray, true)) {
3395 //* DEBUG: */ outputHtml('excluded=' . $baseFile . "<br />");
3399 // Construct include filename and FQFN
3400 $fileName = $baseDir . $baseFile;
3401 $FQFN = getConfig('PATH') . $fileName;
3403 // Remove double slashes
3404 $FQFN = str_replace('//', '/', $FQFN);
3406 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3407 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3408 // These Lines are only for debugging!!
3409 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . "<br />");
3410 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . "<br />");
3411 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . "<br />");
3417 // Skip also files with non-matching prefix genericly
3418 if (($recursive === true) && (isDirectory($FQFN))) {
3419 // Is a redirectory so read it as well
3420 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3422 // And skip further processing
3424 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3426 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3428 } elseif (!isFileReadable($FQFN)) {
3429 // Not readable so skip it
3430 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3434 // Is the file a PHP script or other?
3435 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3436 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3437 // Is this a valid include file?
3438 if ($extension == '.php') {
3439 // Remove both for extension name
3440 $extName = substr($baseFile, strlen($prefix), -4);
3442 // Is the extension valid and active?
3443 if (isExtensionNameValid($extName)) {
3444 // Then add this file
3445 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3446 $files[] = $fileName;
3448 // Add non-extension files as well
3449 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3450 if ($addBaseDir === true) {
3451 $files[] = $fileName;
3453 $files[] = $baseFile;
3457 // We found .php file but should not search for them, why?
3458 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3460 } elseif (substr($baseFile, -4, 4) == $extension) {
3461 // Other, generic file found
3462 $files[] = $fileName;
3467 closedir($dirPointer);
3472 // Return array with include files
3473 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3477 // Maps a module name into a database table name
3478 function mapModuleToTable ($moduleName) {
3479 // Map only these, still lame code...
3480 switch ($moduleName) {
3481 // 'index' is the guest's menu
3482 case 'index': $moduleName = 'guest'; break;
3483 // ... and 'login' the member's menu
3484 case 'login': $moduleName = 'member'; break;
3485 // Anything else will not be mapped, silently.
3492 // Add SQL debug data to array for later output
3493 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3494 // Don't execute anything here if we don't need
3495 if (getConfig('display_debug_sqls') != 'Y') return;
3499 'num_rows' => SQL_NUMROWS($result),
3500 'affected' => SQL_AFFECTEDROWS(),
3501 'sql_str' => $sqlString,
3502 'timing' => $timing,
3503 'file' => basename($F),
3508 $GLOBALS['debug_sqls'][] = $record;
3511 // Initializes the cache instance
3512 function initCacheInstance () {
3513 // Load include for CacheSystem class
3514 loadIncludeOnce('inc/classes/cachesystem.class.php');
3516 // Initialize cache system only when it's needed
3517 $GLOBALS['cache_instance'] = new CacheSystem();
3518 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3519 // Failed to initialize cache sustem
3520 addFatalMessage(__FILE__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_CANNOT_INITIALIZE'));
3524 // Getter for message from array or raw message
3525 function getMessageFromIndexedArray ($message, $pos, $array) {
3526 // Check if the requested message was found in array
3527 if (isset($array[$pos])) {
3528 // ... if yes then use it!
3529 $ret = $array[$pos];
3531 // ... else use default message
3539 // Print code with line numbers
3540 function linenumberCode ($code) {
3541 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3542 $count_lines = count($codeE);
3544 $r = 'Line | Code:<br />';
3545 foreach($codeE as $line => $c) {
3546 $r .= '<div class="line"><span class="linenum">';
3547 if ($count_lines == 1) {
3550 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3555 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3558 return '<div class="code">' . $r . '</div>';
3561 // Convert ';' to ', ' for e.g. receiver list
3562 function convertReceivers ($old) {
3563 return str_replace(';', ', ', $old);
3566 //////////////////////////////////////////////////
3567 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3568 //////////////////////////////////////////////////
3570 if (!function_exists('html_entity_decode')) {
3571 // Taken from documentation on www.php.net
3572 function html_entity_decode ($string) {
3573 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3574 $trans_tbl = array_flip($trans_tbl);
3575 return strtr($string, $trans_tbl);
3579 if (!function_exists('http_build_query')) {
3580 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3581 function http_build_query($data, $prefix='', $sep='', $key='') {
3583 foreach ((array)$data as $k => $v) {
3584 if (is_int($k) && $prefix != null) {
3585 $k = urlencode($prefix . $k);
3588 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3590 if (is_array($v) || is_object($v)) {
3591 array_push($ret, http_build_query($v, '', $sep, $k));
3593 array_push($ret, $k.'='.urlencode($v));
3597 if (empty($sep)) $sep = ini_get('arg_separator.output');
3599 return implode($sep, $ret);