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);
532 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode(smartAddSlashes($GLOBALS['tpl_content']))."\");";
533 eval($GLOBALS['tpl_content']);
534 } elseif (!empty($template)) {
535 // Template file not found!
536 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
537 {--TEMPLATE_CONTENT--}
538 <pre>".print_r($content, true)."</pre>
540 <pre>".print_r($DATA, true)."</pre>
543 // Debug mode not active? Then remove the HTML tags
544 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
546 // No template name supplied!
547 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
550 // Is there some content?
551 if (empty($newContent)) {
553 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
554 // Add last error if the required function exists
555 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
558 // Remove content and data
562 // Compile the code and eval it
563 $eval = '$newContent = "' . compileCode(smartAddSlashes($newContent)) . '";';
570 // Send mail out to an email address
571 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
572 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
574 // Compile subject line (for POINTS constant etc.)
575 eval("\$subject = decodeEntities(\"".compileCode(smartAddSlashes($subject))."\");");
578 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
579 // Value detected, is the message extension installed?
580 // @TODO Extension 'msg' does not exist
581 if (isExtensionActive('msg')) {
582 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
585 // Load email address
586 $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
587 array(bigintval($toEmail)), __FUNCTION__, __LINE__);
588 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email).'<br />');
590 // Does the user exist?
591 if (SQL_NUMROWS($result_email)) {
592 // Load email address
593 list($toEmail) = SQL_FETCHROW($result_email);
596 $toEmail = getConfig('WEBMASTER');
600 SQL_FREERESULT($result_email);
602 } elseif ($toEmail == '0') {
604 $toEmail = getConfig('WEBMASTER');
606 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
608 // Check for PHPMailer or debug-mode
609 if (!checkPhpMailerUsage()) {
610 // Not in PHPMailer-Mode
611 if (empty($mailHeader)) {
612 // Load email header template
613 $mailHeader = loadEmailTemplate('header');
616 $mailHeader .= loadEmailTemplate('header');
618 } elseif (isDebugModeEnabled()) {
619 if (empty($mailHeader)) {
620 // Load email header template
621 $mailHeader = loadEmailTemplate('header');
624 $mailHeader .= loadEmailTemplate('header');
629 eval("\$toEmail = \"".compileCode(smartAddSlashes($toEmail))."\";");
632 eval("\$message = \"".compileCode(smartAddSlashes($message))."\";");
634 // Fix HTML parameter (default is no!)
635 if (empty($isHtml)) $isHtml = 'N';
636 if (isDebugModeEnabled()) {
637 // In debug mode we want to display the mail instead of sending it away so we can debug this part
639 Headers : ' . str_replace('<', '<', str_replace('>', '>', htmlentities(trim($mailHeader)))) . '
640 To : ' . $toEmail . '
641 Subject : ' . $subject . '
642 Message : ' . $message . '
644 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
645 // Send mail as HTML away
646 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
647 } elseif (!empty($toEmail)) {
649 sendRawEmail($toEmail, $subject, $message, $mailHeader);
650 } elseif ($isHtml != 'Y') {
652 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
656 // Check if legacy or PHPMailer command
657 // @TODO Rewrite this to an extension 'smtp'
659 function checkPhpMailerUsage() {
660 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
663 // Send out a raw email with PHPMailer class or legacy mail() command
664 function sendRawEmail ($toEmail, $subject, $message, $from) {
665 // Shall we use PHPMailer class or legacy mode?
666 if (checkPhpMailerUsage()) {
667 // Use PHPMailer class with SMTP enabled
668 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
669 loadIncludeOnce('inc/phpmailer/class.smtp.php');
672 $mail = new PHPMailer();
673 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
676 $mail->SMTPAuth = true;
677 $mail->Host = getConfig('SMTP_HOSTNAME');
679 $mail->Username = getConfig('SMTP_USER');
680 $mail->Password = getConfig('SMTP_PASSWORD');
682 $mail->From = getConfig('WEBMASTER');
686 $mail->FromName = getConfig('MAIN_TITLE');
687 $mail->Subject = $subject;
688 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
689 $mail->Body = $message;
690 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
691 $mail->WordWrap = 70;
694 $mail->Body = decodeEntities($message);
696 $mail->AddAddress($toEmail, '');
697 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
698 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
699 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
702 // Use legacy mail() command
703 mail($toEmail, $subject, decodeEntities($message), $from);
707 // Generate a password in a specified length or use default password length
708 function generatePassword ($length = 0) {
709 // Auto-fix invalid length of zero
710 if ($length == 0) $length = getConfig('pass_len');
712 // Initialize array with all allowed chars
713 $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,-,+,_,/,.');
715 // Start creating password
717 for ($i = 0; $i < $length; $i++) {
718 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
721 // When the size is below 40 we can also add additional security by scrambling
722 // it. Otherwise we may corrupt hashes
723 if (strlen($PASS) <= 40) {
724 // Also scramble the password
725 $PASS = scrambleString($PASS);
728 // Return the password
732 // Generates a human-readable timestamp from the Uni* stamp
733 function generateDateTime ($time, $mode = 0) {
734 // Filter out numbers
735 $time = bigintval($time);
737 // If the stamp is zero it mostly didn't "happen"
740 return getMessage('NEVER_HAPPENED');
743 switch (getLanguage()) {
744 case 'de': // German date / time format
746 case 0: $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
747 case 1: $ret = strtolower(date('d.m.Y - H:i', $time)); break;
748 case 2: $ret = date('d.m.Y|H:i', $time); break;
749 case 3: $ret = date('d.m.Y', $time); break;
751 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
756 default: // Default is the US date / time format!
758 case 0: $ret = date('r', $time); break;
759 case 1: $ret = date('Y-m-d - g:i A', $time); break;
760 case 2: $ret = date('y-m-d|H:i', $time); break;
761 case 3: $ret = date('y-m-d', $time); break;
763 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
772 // Translates Y/N to yes/no
773 function translateYesNo ($yn) {
775 $translated = '??? (' . $yn . ')';
777 case 'Y': $translated = getMessage('YES'); break;
778 case 'N': $translated = getMessage('NO'); break;
781 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
789 // Translates the "pool type" into human-readable
790 function translatePoolType ($type) {
791 // Default?type is unknown
792 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
795 $constName = sprintf("POOL_TYPE_%s", $type);
798 if (isMessageIdValid($constName)) {
800 $translated = getMessage($constName);
803 // Return "translation"
807 // Translates the american decimal dot into a german comma
808 function translateComma ($dotted, $cut = true, $max = 0) {
809 // Default is 3 you can change this in admin area "Misc -> Misc Options"
810 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
812 // Use from config is default
813 $maxComma = getConfig('max_comma');
815 // Use from parameter?
816 if ($max > 0) $maxComma = $max;
819 if (($cut === true) && ($max == 0)) {
820 // Test for commata if in cut-mode
821 $com = explode('.', $dotted);
822 if (count($com) < 2) {
823 // Don't display commatas even if there are none... ;-)
829 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
832 switch (getLanguage()) {
833 case 'de': // German language
834 $dotted = number_format($dotted, $maxComma, ',', '.');
837 default: // All others
838 $dotted = number_format($dotted, $maxComma, '.', ',');
842 // Return translated value
846 // Translate Uni*-like gender to human-readable
847 function translateGender ($gender) {
849 $ret = '!' . $gender . '!';
851 // Male/female or company?
853 case 'M': $ret = getMessage('GENDER_M'); break;
854 case 'F': $ret = getMessage('GENDER_F'); break;
855 case 'C': $ret = getMessage('GENDER_C'); break;
857 // Log unknown gender
858 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
862 // Return translated gender
866 // "Translates" the user status
867 function translateUserStatus ($status) {
868 // Generate message depending on status
873 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
878 $ret = getMessage('ACCOUNT_DELETED');
882 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
883 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
891 // Generates an URL for the dereferer
892 function generateDerefererUrl ($URL) {
893 // Don't de-refer our own links!
894 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
895 // De-refer this link
896 $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
903 // Generates an URL for the frametester
904 function generateFrametesterUrl ($URL) {
905 // Prepare frametester URL
906 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
907 encodeString(compileUriCode($URL))
910 // Return the new URL
911 return $frametesterUrl;
914 // Count entries from e.g. a selection box
915 function countSelection ($array) {
917 if (!is_array($array)) {
919 debug_report_bug(__FUNCTION__.': No array provided.');
926 foreach ($array as $key => $selected) {
928 if (!empty($selected)) $ret++;
931 // Return counted selections
935 // Generate XHTML code for the CAPTCHA
936 function generateCaptchaCode ($code, $type, $DATA, $userid) {
937 return '<img border="0" alt="Code ' . $code . '" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
940 // Generates a timestamp (some wrapper for mktime())
941 function makeTime ($hours, $minutes, $seconds, $stamp) {
942 // Extract day, month and year from given timestamp
943 $days = date('d', $stamp);
944 $months = date('m', $stamp);
945 $years = date('Y', $stamp);
947 // Create timestamp for wished time which depends on extracted date
958 // Redirects to an URL and if neccessarry extends it with own base URL
959 function redirectToUrl ($URL) {
960 // Compile out URI codes
961 $URL = compileUriCode($URL);
963 // Check if http(s):// is there
964 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
965 // Make all URLs full-qualified
966 $URL = getConfig('URL') . '/' . $URL;
969 // Three different debug ways...
970 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
971 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $URL);
972 //* DEBUG: */ die($URL);
974 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
975 $rel = ' rel="external"';
977 // Do we have internal or external URL?
978 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
979 // Own (=internal) URL
984 $GLOBALS['output'] = ob_get_contents();
986 // Clear it only if there is content
987 if (!empty($GLOBALS['output'])) {
991 // Simple probe for bots/spiders from search engines
992 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
993 // Secure the URL against bad things such als HTML insertions and so on...
994 $URL = secureString($URL);
996 // Output new location link as anchor
997 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
998 } elseif (!headers_sent()) {
999 // Load URL when headers are not sent
1000 //* DEBUG: */ debug_report_bug("URL={$URL}");
1001 sendHeader('Location: '.str_replace('&', '&', $URL));
1003 // Output error message
1004 loadInclude('inc/header.php');
1005 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
1006 loadInclude('inc/footer.php');
1009 // Shut the mailer down here
1013 // Wrapper for redirectToUrl but URL comes from a configuration entry
1014 function redirectToConfiguredUrl ($configEntry) {
1016 $URL = getConfig($configEntry);
1019 if (is_null($URL)) {
1021 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1025 redirectToUrl($URL);
1028 // Compiles the given HTML/mail code
1029 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1030 // Is the code a string?
1031 if (!is_string($code)) {
1032 // Silently return it
1036 // Init replacement-array with full security characters
1037 $secChars = $GLOBALS['security_chars'];
1039 // Select smaller set of chars to replace when we e.g. want to compile URLs
1040 if ($full === false) $secChars = $GLOBALS['url_chars'];
1042 // Compile more through a filter
1043 $code = runFilterChain('compile_code', $code);
1045 // Compile constants
1046 if ($constants === true) {
1047 // BEFORE 0.2.1 : Language and data constants
1048 // WITH 0.2.1+ : Only language constants
1049 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1051 // BEFORE 0.2.1 : Not used
1052 // WITH 0.2.1+ : Data constants
1053 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1056 // Compile QUOT and other non-HTML codes
1057 foreach ($secChars['to'] as $k => $to) {
1058 // Do the reversed thing as in inc/libs/security_functions.php
1059 $code = str_replace($to, $secChars['from'][$k], $code);
1062 // But shall I keep simple quotes for later use?
1063 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1065 // Find $content[bla][blub] entries
1066 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1068 // Are some matches found?
1069 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1070 // Replace all matches
1071 $matchesFound = array();
1072 foreach ($matches[0] as $key => $match) {
1073 // Fuzzy look has failed by default
1074 $fuzzyFound = false;
1076 // Fuzzy look on match if already found
1077 foreach ($matchesFound as $found => $set) {
1079 $test = substr($found, 0, strlen($match));
1081 // Does this entry exist?
1082 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1083 if ($test == $match) {
1085 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1092 if ($fuzzyFound === true) continue;
1094 // Take all string elements
1095 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1096 // Replace it in the code
1097 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1098 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1099 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1100 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1101 $matchesFound[$match] = 1;
1102 } elseif (!isset($matchesFound[$match])) {
1103 // Not yet replaced!
1104 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1105 $code = str_replace($match, "\"." . $match.".\"", $code);
1106 $matchesFound[$match] = 1;
1111 // Return compiled code
1115 /************************************************************************
1117 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1118 * $a_sort sortiert: *
1120 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1121 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1122 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1123 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1124 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1126 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1127 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1128 * Sie, dass es doch nicht so schwer ist! :-) *
1130 ************************************************************************/
1131 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1133 while ($primary_key < count($a_sort)) {
1134 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1135 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1137 if ($nums === false) {
1138 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1139 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1140 } elseif ($key != $key2) {
1141 // Sort numbers (E.g.: 9 < 10)
1142 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1143 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1147 // We have found two different values, so let's sort whole array
1148 foreach ($dummy as $sort_key => $sort_val) {
1149 $t = $dummy[$sort_key][$key];
1150 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1151 $dummy[$sort_key][$key2] = $t;
1162 // Write back sorted array
1167 function addSelectionBox ($type, $default, $prefix = '', $id = 0) {
1170 if ($type == 'yn') {
1171 // This is a yes/no selection only!
1172 if ($id > 0) $prefix .= "[" . $id."]";
1173 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1175 // Begin with regular selection box here
1176 if (!empty($prefix)) $prefix .= "_";
1178 if ($id > 0) $type2 .= "[" . $id."]";
1179 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1184 for ($idx = 1; $idx < 32; $idx++) {
1185 $OUT .= "<option value=\"" . $idx."\"";
1186 if ($default == $idx) $OUT .= ' selected="selected"';
1187 $OUT .= ">" . $idx."</option>\n";
1191 case 'month': // Month
1192 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1193 $OUT .= "<option value=\"" . $month."\"";
1194 if ($default == $month) $OUT .= ' selected="selected"';
1195 $OUT .= ">" . $descr."</option>\n";
1199 case 'year': // Year
1201 $year = date('Y', time());
1203 // Use configured min age or fixed?
1204 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1206 $startYear = $year - getConfig('min_age');
1209 $startYear = $year - 16;
1212 // Calculate earliest year (100 years old people can still enter Internet???)
1213 $minYear = $year - 100;
1215 // Check if the default value is larger than minimum and bigger than actual year
1216 if (($default > $minYear) && ($default >= $year)) {
1217 for ($idx = $year; $idx < ($year + 11); $idx++) {
1218 $OUT .= "<option value=\"" . $idx."\"";
1219 if ($default == $idx) $OUT .= ' selected="selected"';
1220 $OUT .= ">" . $idx."</option>\n";
1222 } elseif ($default == -1) {
1223 // Current year minus 1
1224 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1226 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1229 // Get current year and subtract the configured minimum age
1230 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1231 // Calculate earliest year depending on extension version
1232 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1233 // Use configured minimum age
1234 $year = date('Y', time()) - getConfig('min_age');
1236 // Use fixed 16 years age
1237 $year = date('Y', time()) - 16;
1240 // Construct year selection list
1241 for ($idx = $minYear; $idx <= $year; $idx++) {
1242 $OUT .= "<option value=\"" . $idx."\"";
1243 if ($default == $idx) $OUT .= ' selected="selected"';
1244 $OUT .= ">" . $idx."</option>\n";
1251 for ($idx = 0; $idx < 60; $idx+=5) {
1252 if (strlen($idx) == 1) $idx = 0 . $idx;
1253 $OUT .= "<option value=\"" . $idx."\"";
1254 if ($default == $idx) $OUT .= ' selected="selected"';
1255 $OUT .= ">" . $idx."</option>\n";
1260 for ($idx = 0; $idx < 24; $idx++) {
1261 if (strlen($idx) == 1) $idx = 0 . $idx;
1262 $OUT .= "<option value=\"" . $idx."\"";
1263 if ($default == $idx) $OUT .= ' selected="selected"';
1264 $OUT .= ">" . $idx."</option>\n";
1269 $OUT .= "<option value=\"Y\"";
1270 if ($default == 'Y') $OUT .= ' selected="selected"';
1271 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1272 if ($default != 'Y') $OUT .= ' selected="selected"';
1273 $OUT .= ">{--NO--}</option>\n";
1276 $OUT .= " </select>\n";
1281 // Deprecated : $length
1284 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1285 // Build server string
1286 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1289 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1290 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1291 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1292 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1293 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1295 // Build string from misc data
1296 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1298 // Add more additional data
1299 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1301 // Add referal id, language, theme and userid
1302 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1303 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1304 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1305 $data .= getConfig('ENCRYPT_SEPERATOR') . getUserId();
1307 // Calculate number for generating the code
1308 $a = $code + getConfig('_ADD') - 1;
1310 if (isConfigEntrySet('master_salt')) {
1311 // Generate hash with master salt from modula of number with the prime number and other data
1312 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, getConfig('master_salt'));
1314 // Create number from hash
1315 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1317 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1318 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, getConfig('salt_length')));
1320 // Create number from hash
1321 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1324 // At least 10 numbers shall be secure enought!
1325 $len = getConfig('code_length');
1326 if ($len == 0) $len = $length;
1327 if ($len == 0) $len = 10;
1329 // Cut off requested counts of number
1330 $return = substr(str_replace('.', '', $rcode), 0, $len);
1332 // Done building code
1336 // Does only allow numbers
1337 function bigintval ($num, $castValue = true) {
1338 // Filter all numbers out
1339 $ret = preg_replace('/[^0123456789]/', '', $num);
1342 if ($castValue) $ret = (double)$ret;
1344 // Has the whole value changed?
1345 // @TODO Remove this if() block if all is working fine
1346 if ('' . $ret . '' != '' . $num . '') {
1348 //debug_report_bug("{$ret}<>{$num}");
1355 // Insert the code in $img_code into jpeg or PNG image
1356 function generateImageOrCode ($img_code, $headerSent=true) {
1357 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1358 // Stop execution of function here because of over-sized code length
1360 } elseif ($headerSent === false) {
1361 // Return in an HTML code code
1362 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1366 $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
1367 if (isFileReadable($img)) {
1368 // Switch image type
1369 switch (getConfig('img_type'))
1372 // Okay, load image and hide all errors
1373 $image = imagecreatefromjpeg($img);
1377 // Okay, load image and hide all errors
1378 $image = imagecreatefrompng($img);
1382 // Exit function here
1383 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1387 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1388 $text_color = imagecolorallocate($image, 0, 0, 0);
1390 // Insert code into image
1391 imagestring($image, 5, 14, 2, $img_code, $text_color);
1393 // Return to browser
1394 sendHeader('Content-Type: image/' . getConfig('img_type'));
1396 // Output image with matching image factory
1397 switch (getConfig('img_type')) {
1398 case 'jpg': imagejpeg($image); break;
1399 case 'png': imagepng($image); break;
1402 // Remove image from memory
1403 imagedestroy($image);
1405 // Create selection box or array of splitted timestamp
1406 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1407 // Calculate 2-seconds timestamp
1408 $stamp = round($timestamp);
1409 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1411 // Do we have a leap year?
1413 $TEST = date('Y', time()) / 4;
1414 $M1 = date('m', time());
1415 $M2 = date('m', (time() + $timestamp));
1417 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1418 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1420 // First of all years...
1421 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1422 //* DEBUG: */ print("Y={$Y}<br />");
1424 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1425 //* DEBUG: */ print("M={$M}<br />");
1427 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1428 //* DEBUG: */ print("W={$W}<br />");
1430 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1431 //* DEBUG: */ print("D={$D}<br />");
1433 $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));
1434 //* DEBUG: */ print("h={$h}<br />");
1436 $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));
1437 //* DEBUG: */ print("m={$m}<br />");
1438 // And at last seconds...
1439 $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));
1440 //* DEBUG: */ print("s={$s}<br />");
1442 // Is seconds zero and time is < 60 seconds?
1443 if (($s == 0) && ($timestamp < 60)) {
1445 $s = round($timestamp);
1449 // Now we convert them in seconds...
1451 if ($return_array) {
1452 // Just put all data in an array for later use
1464 $OUT = "<div align=\"" . $align."\">\n";
1465 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1468 if (ereg('Y', $display) || (empty($display))) {
1469 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1472 if (ereg('M', $display) || (empty($display))) {
1473 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1476 if (ereg("W", $display) || (empty($display))) {
1477 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1480 if (ereg("D", $display) || (empty($display))) {
1481 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1484 if (ereg("h", $display) || (empty($display))) {
1485 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1488 if (ereg('m', $display) || (empty($display))) {
1489 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1492 if (ereg("s", $display) || (empty($display))) {
1493 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1499 if (ereg('Y', $display) || (empty($display))) {
1500 // Generate year selection
1501 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1502 for ($idx = 0; $idx <= 10; $idx++) {
1503 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1504 if ($idx == $Y) $OUT .= ' selected="selected"';
1505 $OUT .= ">" . $idx."</option>\n";
1507 $OUT .= " </select></td>\n";
1509 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1512 if (ereg('M', $display) || (empty($display))) {
1513 // Generate month selection
1514 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1515 for ($idx = 0; $idx <= 11; $idx++)
1517 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1518 if ($idx == $M) $OUT .= ' selected="selected"';
1519 $OUT .= ">" . $idx."</option>\n";
1521 $OUT .= " </select></td>\n";
1523 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1526 if (ereg("W", $display) || (empty($display))) {
1527 // Generate week selection
1528 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1529 for ($idx = 0; $idx <= 4; $idx++) {
1530 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1531 if ($idx == $W) $OUT .= ' selected="selected"';
1532 $OUT .= ">" . $idx."</option>\n";
1534 $OUT .= " </select></td>\n";
1536 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1539 if (ereg("D", $display) || (empty($display))) {
1540 // Generate day selection
1541 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1542 for ($idx = 0; $idx <= 31; $idx++) {
1543 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1544 if ($idx == $D) $OUT .= ' selected="selected"';
1545 $OUT .= ">" . $idx."</option>\n";
1547 $OUT .= " </select></td>\n";
1549 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1552 if (ereg("h", $display) || (empty($display))) {
1553 // Generate hour selection
1554 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1555 for ($idx = 0; $idx <= 23; $idx++) {
1556 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1557 if ($idx == $h) $OUT .= ' selected="selected"';
1558 $OUT .= ">" . $idx."</option>\n";
1560 $OUT .= " </select></td>\n";
1562 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1565 if (ereg('m', $display) || (empty($display))) {
1566 // Generate minute selection
1567 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1568 for ($idx = 0; $idx <= 59; $idx++) {
1569 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1570 if ($idx == $m) $OUT .= ' selected="selected"';
1571 $OUT .= ">" . $idx."</option>\n";
1573 $OUT .= " </select></td>\n";
1575 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1578 if (ereg("s", $display) || (empty($display))) {
1579 // Generate second selection
1580 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1581 for ($idx = 0; $idx <= 59; $idx++) {
1582 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1583 if ($idx == $s) $OUT .= ' selected="selected"';
1584 $OUT .= ">" . $idx."</option>\n";
1586 $OUT .= " </select></td>\n";
1588 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1591 $OUT .= "</table>\n";
1593 // Return generated HTML code
1599 function createTimestampFromSelections ($prefix, $postData) {
1600 // Initial return value
1603 // Do we have a leap year?
1605 $TEST = date('Y', time()) / 4;
1606 $M1 = date('m', time());
1607 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1608 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1609 // First add years...
1610 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1612 $ret += $postData[$prefix."_mo"] * 2628000;
1614 $ret += $postData[$prefix."_we"] * 604800;
1616 $ret += $postData[$prefix."_da"] * 86400;
1618 $ret += $postData[$prefix."_ho"] * 3600;
1620 $ret += $postData[$prefix."_mi"] * 60;
1621 // And at last seconds...
1622 $ret += $postData[$prefix."_se"];
1623 // Return calculated value
1627 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1628 function createFancyTime ($stamp) {
1629 // Get data array with years/months/weeks/days/...
1630 $data = createTimeSelections($stamp, '', '', '', true);
1632 foreach($data as $k => $v) {
1634 // Value is greater than 0 "eval" data to return string
1635 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1640 // Do we have something there?
1641 if (strlen($ret) > 0) {
1642 // Remove leading commata and space
1643 $ret = substr($ret, 2);
1646 $ret = "0 {--_SECONDS--}";
1649 // Return fancy time string
1653 // Generates a navigation row for listing emails
1654 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1655 $SEP = ''; $TOP = '';
1656 if ($show_form === false) {
1658 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1662 for ($page = 1; $page <= $PAGES; $page++) {
1663 // Is the page currently selected or shall we generate a link to it?
1664 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1665 // Is currently selected, so only highlight it
1666 $NAV .= '<strong>-';
1668 // Open anchor tag and add base URL
1669 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1671 // Add userid when we shall show all mails from a single member
1672 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1674 // Close open anchor tag
1678 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1679 // Is currently selected, so only highlight it
1680 $NAV .= '-</strong>';
1686 // Add seperator if we have not yet reached total pages
1687 if ($page < $PAGES) $NAV .= ' | ';
1690 // Define constants only once
1691 $content['nav'] = $NAV;
1692 $content['span'] = $colspan;
1693 $content['top'] = $TOP;
1694 $content['sep'] = $SEP;
1696 // Load navigation template
1697 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1699 if ($return === true) {
1700 // Return generated HTML-Code
1708 // Extract host from script name
1709 function extractHostnameFromUrl (&$script) {
1710 // Use default SERVER_URL by default... ;) So?
1711 $url = getConfig('SERVER_URL');
1713 // Is this URL valid?
1714 if (substr($script, 0, 7) == 'http://') {
1715 // Use the hostname from script URL as new hostname
1716 $url = substr($script, 7);
1717 $extract = explode('/', $url);
1719 // Done extracting the URL :)
1722 // Extract host name
1723 $host = str_replace('http://', '', $url);
1724 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1726 // Generate relative URL
1727 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1728 if (substr(strtolower($script), 0, 7) == 'http://') {
1729 // But only if http:// is in front!
1730 $script = substr($script, (strlen($url) + 7));
1731 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1733 $script = substr($script, (strlen($url) + 8));
1736 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1737 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1743 // Send a GET request
1744 function sendGetRequest ($script, $data = array()) {
1745 // Extract host name from script
1746 $host = extractHostnameFromUrl($script);
1749 $scriptData = http_build_query($data, '', '&');
1751 // Do we have a question-mark in the script?
1752 if (strpos($script, '?') === false) {
1753 // No, so first char must be question mark
1754 $scriptData = '?' . $scriptData;
1757 $scriptData = '&' . $scriptData;
1761 $script .= $scriptData;
1763 // Generate GET request header
1764 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1765 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1766 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1767 if (isConfigEntrySet('FULL_VERSION')) {
1768 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1770 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1772 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1773 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1774 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1776 // Send the raw request
1777 $response = sendRawRequest($host, $request);
1779 // Return the result to the caller function
1783 // Send a POST request
1784 function sendPostRequest ($script, $postData) {
1785 // Is postData an array?
1786 if (!is_array($postData)) {
1788 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1789 return array('', '', '');
1792 // Compile the script name
1793 $script = compileCode($script);
1795 // Extract host name from script
1796 $host = extractHostnameFromUrl($script);
1798 // Construct request
1799 $data = http_build_query($postData, '', '&');
1801 // Generate POST request header
1802 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1803 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1804 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1805 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1806 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1807 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1808 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1809 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1812 // Send the raw request
1813 $response = sendRawRequest($host, $request);
1815 // Return the result to the caller function
1819 // Sends a raw request to another host
1820 function sendRawRequest ($host, $request) {
1821 // Init errno and errdesc with 'all fine' values
1822 $errno = 0; $errdesc = '';
1825 $response = array('', '', '');
1827 // Default is not to use proxy
1830 // Are proxy settins set?
1831 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1837 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1838 if ($useProxy === true) {
1839 // Connect to host through proxy connection
1840 $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1842 // Connect to host directly
1843 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1847 if (!is_resource($fp)) {
1853 if ($useProxy === true) {
1854 // Generate CONNECT request header
1855 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1856 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1858 // Use login data to proxy? (username at least!)
1859 if (getConfig('proxy_username') != '') {
1861 $encodedAuth = base64_encode(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
1862 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1865 // Add last new-line
1866 $proxyTunnel .= getConfig('HTTP_EOL');
1867 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1870 fputs($fp, $proxyTunnel);
1874 // No response received
1878 // Read the first line
1879 $resp = trim(fgets($fp, 10240));
1880 $respArray = explode(' ', $resp);
1881 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1882 // Invalid response!
1888 fputs($fp, $request);
1891 while (!feof($fp)) {
1892 $response[] = trim(fgets($fp, 1024));
1898 // Skip first empty lines
1900 foreach ($resp as $idx => $line) {
1902 $line = trim($line);
1904 // Is this line empty?
1907 array_shift($response);
1909 // Abort on first non-empty line
1914 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1916 // Proxy agent found?
1917 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1918 // Proxy header detected, so remove two lines
1919 array_shift($response);
1920 array_shift($response);
1923 // Was the request successfull?
1924 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1925 // Not found / access forbidden
1926 $response = array('', '', '');
1933 // Taken from www.php.net eregi() user comments
1934 function isEmailValid ($email) {
1936 $email = compileCode($email);
1938 // Check first part of email address
1939 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1942 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1945 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1947 // Return check result
1948 return preg_match($regex, $email);
1951 // Function taken from user comments on www.php.net / function eregi()
1952 function isUrlValid ($URL, $compile=true) {
1953 // Trim URL a little
1954 $URL = trim(urldecode($URL));
1955 //* DEBUG: */ outputHtml($URL.'<br />');
1957 // Compile some chars out...
1958 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1959 //* DEBUG: */ outputHtml($URL.'<br />');
1961 // Check for the extension filter
1962 if (isExtensionActive('filter')) {
1963 // Use the extension's filter set
1964 return FILTER_VALIDATE_URL($URL, false);
1967 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1968 // https:// in front of the URLs
1969 return isUrlValidSimple($URL);
1972 // Generate a list of administrative links to a given userid
1973 function generateMemberAdminActionLinks ($userid, $status = '') {
1974 // Make sure userid is a number
1975 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1977 // Define all main targets
1978 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1980 // Begin of navigation links
1983 foreach ($targetArray as $tar) {
1984 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1985 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1986 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1987 // Locked accounts shall be unlocked
1988 $OUT .= 'UNLOCK_USER';
1990 // All other status is fine
1991 $OUT .= strtoupper($tar);
1993 $OUT .= "_TITLE--}\">{--ADMIN_";
1994 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1995 // Locked accounts shall be unlocked
1996 $OUT .= 'UNLOCK_USER';
1998 // All other status is fine
1999 $OUT .= strtoupper($tar);
2001 $OUT .= "--}</a></span> | ";
2004 // Finish navigation link
2005 $OUT = substr($OUT, 0, -7) . ']';
2011 // Generate an email link
2012 function generateEmailLink ($email, $table = 'admins') {
2013 // Default email link (INSECURE! Spammer can read this by harvester programs)
2014 $EMAIL = 'mailto:' . $email;
2016 // Check for several extensions
2017 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2018 // Create email link for contacting admin in guest area
2019 $EMAIL = generateAdminEmailLink($email);
2020 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2021 // Create email link for contacting a member within admin area (or later in other areas, too?)
2022 $EMAIL = generateUserEmailLink($email, 'admin');
2023 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2024 // Create email link to contact sponsor within admin area (or like the link above?)
2025 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2028 // Shall I close the link when there is no admin?
2029 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2031 // Return email link
2035 // Generate a hash for extra-security for all passwords
2036 function generateHash ($plainText, $salt = '') {
2037 // Is the required extension 'sql_patches' there and a salt is not given?
2038 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2039 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2040 return md5($plainText);
2043 // Do we miss an arry element here?
2044 if (!isConfigEntrySet('file_hash')) {
2046 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2049 // When the salt is empty build a new one, else use the first x configured characters as the salt
2051 // Build server string (inc/databases.php is no longer updated with every commit)
2052 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2055 $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');
2058 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2060 // Calculate number for generating the code
2061 $a = time() + getConfig('_ADD') - 1;
2063 // Generate SHA1 sum from modula of number and the prime number
2064 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2065 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2066 $sha1 = scrambleString($sha1);
2067 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2068 //* DEBUG: */ $sha1b = descrambleString($sha1);
2069 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2071 // Generate the password salt string
2072 $salt = substr($sha1, 0, getConfig('salt_length'));
2073 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2076 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2077 $salt = substr($salt, 0, getConfig('salt_length'));
2078 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2080 // Sanity check on salt
2081 if (strlen($salt) != getConfig('salt_length')) {
2083 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2088 return $salt.sha1($salt . $plainText);
2091 // Scramble a string
2092 function scrambleString($str) {
2096 // Final check, in case of failture it will return unscrambled string
2097 if (strlen($str) > 40) {
2098 // The string is to long
2100 } elseif (strlen($str) == 40) {
2102 $scrambleNums = explode(':', getConfig('pass_scramble'));
2104 // Generate new numbers
2105 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2108 // Scramble string here
2109 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2110 for ($idx = 0; $idx < strlen($str); $idx++) {
2111 // Get char on scrambled position
2112 $char = substr($str, $scrambleNums[$idx], 1);
2114 // Add it to final output string
2115 $scrambled .= $char;
2118 // Return scrambled string
2119 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2123 // De-scramble a string scrambled by scrambleString()
2124 function descrambleString($str) {
2125 // Scramble only 40 chars long strings
2126 if (strlen($str) != 40) return $str;
2128 // Load numbers from config
2129 $scrambleNums = explode(':', getConfig('pass_scramble'));
2132 if (count($scrambleNums) != 40) return $str;
2134 // Begin descrambling
2135 $orig = str_repeat(' ', 40);
2136 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2137 for ($idx = 0; $idx < 40; $idx++) {
2138 $char = substr($str, $idx, 1);
2139 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2142 // Return scrambled string
2143 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2147 // Generated a "string" for scrambling
2148 function genScrambleString ($len) {
2149 // Prepare array for the numbers
2150 $scrambleNumbers = array();
2152 // First we need to setup randomized numbers from 0 to 31
2153 for ($idx = 0; $idx < $len; $idx++) {
2155 $rand = mt_rand(0, ($len -1));
2157 // Check for it by creating more numbers
2158 while (array_key_exists($rand, $scrambleNumbers)) {
2159 $rand = mt_rand(0, ($len -1));
2163 $scrambleNumbers[$rand] = $rand;
2166 // So let's create the string for storing it in database
2167 $scrambleString = implode(':', $scrambleNumbers);
2168 return $scrambleString;
2171 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2172 function generatePassString ($passHash) {
2173 // Return vanilla password hash
2176 // Is a secret key and master salt already initialized?
2177 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2178 // Only calculate when the secret key is generated
2179 $newHash = ''; $start = 9;
2180 for ($idx = 0; $idx < 10; $idx++) {
2181 $part1 = hexdec(substr($passHash, $start, 4));
2182 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2183 $mod = dechex($idx);
2184 if ($part1 > $part2) {
2185 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2186 } elseif ($part2 > $part1) {
2187 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2189 $mod = substr($mod, 0, 4);
2190 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2191 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2192 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2197 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2198 $ret = generateHash($newHash, getConfig('master_salt'));
2199 //* DEBUG: */ print('ret='.$ret.'<br />');
2202 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2203 $ret = md5($passHash);
2204 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2211 // Fix "deleted" cookies
2212 function fixDeletedCookies ($cookies) {
2213 // Is this an array with entries?
2214 if ((is_array($cookies)) && (count($cookies) > 0)) {
2215 // Then check all cookies if they are marked as deleted!
2216 foreach ($cookies as $cookieName) {
2217 // Is the cookie set to "deleted"?
2218 if (getSession($cookieName) == 'deleted') {
2219 setSession($cookieName, '');
2225 // Output error messages in a fasioned way and die...
2226 function app_die ($F, $L, $message) {
2227 // Check if Script is already dieing and not let it kill itself another 1000 times
2228 if (!isset($GLOBALS['app_died'])) {
2229 // Make sure, that the script realy realy diese here and now
2230 $GLOBALS['app_died'] = true;
2233 loadIncludeOnce('inc/header.php');
2235 // Rewrite message for output
2236 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2238 // Better log this message away
2239 logDebugMessage($F, $L, $message);
2241 // Load the message template
2242 loadTemplate('admin_settings_saved', false, $message);
2245 loadIncludeOnce('inc/footer.php');
2247 // Script tried to kill itself twice
2248 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2252 // Display parsing time and number of SQL queries in footer
2253 function displayParsingTime() {
2254 // Is the timer started?
2255 if (!isset($GLOBALS['startTime'])) {
2261 $endTime = microtime(true);
2263 // "Explode" both times
2264 $start = explode(' ', $GLOBALS['startTime']);
2265 $end = explode(' ', $endTime);
2266 $runTime = $end[0] - $start[0];
2267 if ($runTime < 0) $runTime = 0;
2271 'runtime' => translateComma($runTime),
2272 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2275 // Load the template
2276 loadTemplate('show_timings', false, $content);
2279 // Check wether a boolean constant is set
2280 // Taken from user comments in PHP documentation for function constant()
2281 function isBooleanConstantAndTrue ($constName) { // : Boolean
2282 // Failed by default
2286 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2288 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2289 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2292 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2293 if (defined($constName)) {
2295 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2296 $res = (constant($constName) === true);
2300 $GLOBALS['cache_array']['const'][$constName] = $res;
2302 //* DEBUG: */ var_dump($res);
2308 // Checks if a given apache module is loaded
2309 function isApacheModuleLoaded ($apacheModule) {
2310 // Check it and return result
2311 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2314 // Get current theme name
2315 function getCurrentTheme () {
2316 // The default theme is 'default'... ;-)
2319 // Load default theme if not empty from configuration
2320 if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
2322 if (!isSessionVariableSet('mxchange_theme')) {
2323 // Set default theme
2325 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2326 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2327 // Get theme from cookie
2328 $ret = getSession('mxchange_theme');
2331 if (getThemeId($ret) == 0) {
2332 // Fix it to default
2335 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2336 // Prepare FQFN for checking
2337 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2339 // Installation mode active
2340 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2341 // Set cookie from URL data
2342 setTheme(getRequestElement('theme'));
2343 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2344 // Set cookie from posted data
2345 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2349 $ret = getSession('mxchange_theme');
2351 // Invalid design, reset cookie
2355 // Return theme value
2359 // Setter for theme in session
2360 function setTheme ($newTheme) {
2361 setSession('mxchange_theme', $newTheme);
2364 // Get id from theme
2365 // @TODO Try to move this to inc/libs/theme_functions.php
2366 function getThemeId ($name) {
2367 // Is the extension 'theme' installed?
2368 if (!isExtensionActive('theme')) {
2376 // Is the cache entry there?
2377 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2378 // Get the version from cache
2379 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2382 incrementStatsEntry('cache_hits');
2383 } elseif (getExtensionVersion('cache') != '0.1.8') {
2384 // Check if current theme is already imported or not
2385 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2386 array($name), __FUNCTION__, __LINE__);
2389 if (SQL_NUMROWS($result) == 1) {
2391 list($id) = SQL_FETCHROW($result);
2395 SQL_FREERESULT($result);
2402 // Generates an error code from given account status
2403 function generateErrorCodeFromUserStatus ($status) {
2404 // @TODO The status should never be empty
2405 if (empty($status)) {
2406 // Something really bad happend here
2407 debug_report_bug(__FUNCTION__ . ': status is empty.');
2410 // Default error code if unknown account status
2411 $errorCode = getCode('UNKNOWN_STATUS');
2413 // Generate constant name
2414 $constantName = sprintf("ID_%s", $status);
2416 // Is the constant there?
2417 if (isCodeSet($constantName)) {
2419 $errorCode = getCode($constantName);
2422 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2425 // Return error code
2429 // Function to search for the last modifified file
2430 function searchDirsRecursive ($dir, &$last_changed) {
2432 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2433 // Does it match what we are looking for? (We skip a lot files already!)
2434 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2435 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2436 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2437 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2439 // Walk through all entries
2440 foreach ($ds as $d) {
2441 // Generate proper FQFN
2442 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2444 // Is it a file and readable?
2445 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2446 if (isDirectory($FQFN)) {
2447 // $FQFN is a directory so also crawl into this directory
2449 if (!empty($dir)) $newDir = $dir . '/'. $d;
2450 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2451 searchDirsRecursive($newDir, $last_changed);
2452 } elseif (isFileReadable($FQFN)) {
2453 // $FQFN is a filename and no directory
2454 $time = filemtime($FQFN);
2455 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2456 if ($last_changed['time'] < $time) {
2457 // This file is newer as the file before
2458 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2459 $last_changed['path_name'] = $FQFN;
2460 $last_changed['time'] = $time;
2466 // "Getter" for revision/version data
2467 function getActualVersion ($type = 'Revision') {
2468 // By default nothing is new... ;-)
2471 // Is the cache entry there?
2472 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2473 // Found so increase cache hit
2474 incrementStatsEntry('cache_hits');
2477 return $GLOBALS['cache_array']['revision'][$type][0];
2479 // FQFN of revision file
2480 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2482 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2483 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2484 // Forced rebuild of .revision file
2487 // Check for revision file
2488 if (!isFileReadable($FQFN)) {
2489 // Not found, so we need to create it
2492 // Revision file found
2493 $ins_vers = explode("\n", readFromFile($FQFN));
2495 // Get array for mapping information
2496 $mapper = array_flip(getSearchFor());
2497 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2499 // Is the content valid?
2500 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2501 // File needs update!
2504 // Generate fake cache entry
2505 foreach ($mapper as $map=>$idx) {
2506 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2509 // Return found value
2510 return trim($ins_vers[$mapper[$type]]);
2515 // Has it been updated?
2516 if ($new === true) {
2518 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2520 // ... and call recursive
2521 return getActualVersion($type);
2526 // Repares an array we are looking for
2527 // 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
2528 function getSearchFor () {
2529 // Add Revision, Date, Tag and Author
2530 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2532 // Return the created array
2536 // @TODO Please describe this function
2537 function getArrayFromActualVersion () {
2541 // Directory to start with search
2542 $last_changed = array(
2547 // Init return array
2548 $akt_vers = array();
2550 // Init value for counting the founded keywords
2553 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2554 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2557 $last_file = readFromFile($last_changed['path_name']);
2559 // Get all the keywords to search for
2560 $searchFor = getSearchFor();
2562 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2563 foreach ($searchFor as $search) {
2564 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2565 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2566 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2567 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2570 // Save the last-changed filename for debugging
2571 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2573 // at least 3 keyword-Tags are needed for propper values
2574 if ($res && $res >= 3
2575 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2576 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2577 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2578 // Prepare content witch need special treadment
2580 // Prepare timestamp for date
2581 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2582 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2584 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2585 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2586 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2590 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2591 $version = sendGetRequest('check-updates3.php');
2594 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2595 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2596 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2597 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2598 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2599 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2602 // Return prepared array
2603 return $GLOBALS['cache_array']['revision'];
2606 // Back-ported from the new ship-simu engine. :-)
2607 function debug_get_printable_backtrace () {
2609 $backtrace = "<ol>\n";
2611 // Get and prepare backtrace for output
2612 $backtraceArray = debug_backtrace();
2613 foreach ($backtraceArray as $key => $trace) {
2614 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2615 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2616 if (!isset($trace['args'])) $trace['args'] = array();
2617 $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";
2621 $backtrace .= "</ol>\n";
2623 // Return the backtrace
2627 // Output a debug backtrace to the user
2628 function debug_report_bug ($message = '') {
2629 // Is this already called?
2630 if (isset($GLOBALS[__FUNCTION__])) {
2632 print 'Message:'.$message.'<br />Backtrace:<pre>';
2633 debug_print_backtrace();
2637 // Set this function as called
2638 $GLOBALS[__FUNCTION__] = true;
2643 // Is the optional message set?
2644 if (!empty($message)) {
2646 $debug = sprintf("Note: %s<br />\n",
2650 // @TODO Add a little more infos here
2651 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2655 $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>";
2656 $debug .= debug_get_printable_backtrace();
2657 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2658 $debug .= "Thank you for finding bugs.";
2661 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2665 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2666 function generateSeed () {
2667 list($usec, $sec) = explode(' ', microtime());
2668 $microTime = (((float)$sec + (float)$usec)) * 100000;
2672 // Converts a message code to a human-readable message
2673 function getMessageFromErrorCode ($code) {
2677 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2678 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2679 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2680 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2681 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2682 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2683 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2684 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2685 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2686 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2687 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2688 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2689 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2690 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2691 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2692 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2693 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2694 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2695 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2696 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2697 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2698 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2699 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2700 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2701 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2702 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2703 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2704 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2706 case getCode('ERROR_MAILID'):
2707 if (isExtensionActive('mailid', true)) {
2708 $message = getMessage('ERROR_CONFIRMING_MAIL');
2710 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2714 case getCode('EXTENSION_PROBLEM'):
2715 if (isGetRequestElementSet('ext')) {
2716 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2718 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2722 case getCode('URL_TLOCK'):
2723 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2724 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2726 // Load timestamp from last order
2727 list($timestamp) = SQL_FETCHROW($result);
2728 $timestamp = generateDateTime($timestamp, 1);
2731 SQL_FREERESULT($result);
2733 // Calculate hours...
2734 $STD = round(getConfig('url_tlock') / 60 / 60);
2737 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2740 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2742 // Finally contruct the message
2743 // @TODO Rewrite this old lost code to a template
2744 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2745 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2746 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2750 // Missing/invalid code
2751 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2754 logDebugMessage(__FUNCTION__, __LINE__, $message);
2758 // Return the message
2762 // Generate a "link" for the given admin id (admin_id)
2763 function generateAdminLink ($adminId) {
2764 // No assigned admin is default
2765 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2767 // Zero? = Not assigned
2768 if (bigintval($adminId) > 0) {
2769 // Load admin's login
2770 $login = getAdminLogin($adminId);
2772 // Is the login valid?
2773 if ($login != '***') {
2774 // Is the extension there?
2775 if (isExtensionActive('admins')) {
2777 $admin = "<a href=\"".generateEmailLink(getAdminEmail($adminId), 'admins')."\">" . $login."</a>";
2779 // Extension not found
2780 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2784 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $adminId)."</div>";
2792 // Compile characters which are allowed in URLs
2793 function compileUriCode ($code, $simple = true) {
2794 // Compile constants
2795 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2797 // Compile QUOT and other non-HTML codes
2798 $code = str_replace('{DOT}', '.',
2799 str_replace('{SLASH}', '/',
2800 str_replace('{QUOT}', "'",
2801 str_replace('{DOLLAR}', '$',
2802 str_replace('{OPEN_ANCHOR}', '(',
2803 str_replace('{CLOSE_ANCHOR}', ')',
2804 str_replace('{OPEN_SQR}', '[',
2805 str_replace('{CLOSE_SQR}', ']',
2806 str_replace('{PER}', '%',
2810 // Return compiled code
2814 // Function taken from user comments on www.php.net / function eregi()
2815 function isUrlValidSimple ($url) {
2817 $url = secureString(str_replace("\\", '', compileCode(urldecode($url))));
2819 // Allows http and https
2820 $http = "(http|https)+(:\/\/)";
2822 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2823 // Test double-domains (e.g. .de.vu)
2824 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2826 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2828 $dir = "((/)+([-_\.[:alnum:]])+)*";
2830 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2831 // ... and the string after and including question character
2832 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2833 // Pattern for URLs like http://url/dir/doc.html?var=value
2834 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2835 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2836 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2837 // Pattern for URLs like http://url/dir/?var=value
2838 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2839 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2840 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2841 // Pattern for URLs like http://url/dir/page.ext
2842 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2843 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2844 $pattern['ipdp'] = $http . $ip . $dir . $page;
2845 // Pattern for URLs like http://url/dir
2846 $pattern['d1d'] = $http . $domain1 . $dir;
2847 $pattern['d2d'] = $http . $domain2 . $dir;
2848 $pattern['ipd'] = $http . $ip . $dir;
2849 // Pattern for URLs like http://url/?var=value
2850 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2851 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2852 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2853 // Pattern for URLs like http://url?var=value
2854 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2855 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2856 $pattern['ipg12'] = $http . $ip . $getstring1;
2857 // Test all patterns
2859 foreach ($pattern as $key => $pat) {
2861 if (isDebugRegExpressionEnabled()) {
2862 // @TODO Are these convertions still required?
2863 $pat = str_replace('.', "\.", $pat);
2864 $pat = str_replace('@', "\@", $pat);
2865 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2868 // Check if expression matches
2869 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2872 if ($reg === true) break;
2875 // Return true/false
2879 // Wtites data to a config.php-style file
2880 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2881 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2882 // Initialize some variables
2888 // Is the file there and read-/write-able?
2889 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2890 $search = 'CFG: ' . $comment;
2891 $tmp = $FQFN . '.tmp';
2893 // Open the source file
2894 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2896 // Is the resource valid?
2897 if (is_resource($fp)) {
2898 // Open temporary file
2899 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2901 // Is the resource again valid?
2902 if (is_resource($fp_tmp)) {
2903 // Mark temporary file as readable
2904 $GLOBALS['file_readable'][$tmp] = true;
2907 while (!feof($fp)) {
2908 // Read from source file
2909 $line = fgets ($fp, 1024);
2911 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2914 if ($next === $seek) {
2916 $line = $prefix . $DATA . $suffix . "\n";
2922 // Write to temp file
2923 fputs($fp_tmp, $line);
2929 // Finished writing tmp file
2933 // Close source file
2936 if (($done === true) && ($found === true)) {
2937 // Copy back tmp file and delete tmp :-)
2938 copyFileVerified($tmp, $FQFN, 0644);
2939 return removeFile($tmp);
2940 } elseif ($found === false) {
2941 outputHtml('<strong>CHANGE:</strong> 404!');
2943 outputHtml('<strong>TMP:</strong> UNDONE!');
2947 // File not found, not readable or writeable
2948 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2951 // An error was detected!
2954 // Send notification to admin
2955 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = 0) {
2956 if (getExtensionVersion('admins') >= '0.4.1') {
2958 sendAdminsEmails($subject, $templateName, $content, $userid);
2960 // Send out out-dated way
2961 $message = loadEmailTemplate($templateName, $content, $userid);
2962 sendAdminEmails($subject, $message);
2966 // Debug message logger
2967 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2968 // Is debug mode enabled?
2969 if ((isDebugModeEnabled()) || ($force === true)) {
2971 $message = str_replace("\r", '', str_replace("\n", '', $message));
2973 // Log this message away, we better don't call app_die() here to prevent an endless loop
2974 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2975 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2980 // Handle extra values
2981 function handleExtraValues ($filterFunction, $value, $extraValue) {
2982 // Default is the value itself
2985 // Do we have a special filter function?
2986 if (!empty($filterFunction)) {
2987 // Does the filter function exist?
2988 if (function_exists($filterFunction)) {
2989 // Do we have extra parameters here?
2990 if (!empty($extraValue)) {
2991 // Put both parameters in one new array by default
2992 $args = array($value, $extraValue);
2994 // If we have an array simply use it and pre-extend it with our value
2995 if (is_array($extraValue)) {
2996 // Make the new args array
2997 $args = merge_array(array($value), $extraValue);
3000 // Call the multi-parameter call-back
3001 $ret = call_user_func_array($filterFunction, $args);
3003 // One parameter call
3004 $ret = call_user_func($filterFunction, $value);
3013 // Converts timestamp selections into a timestamp
3014 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
3015 // Init test variable
3019 // Get last three chars
3020 $test = substr($id, -3);
3022 // Improved way of checking! :-)
3023 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3024 // Found a multi-selection for timings?
3025 $test = substr($id, 0, -3);
3026 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)) {
3027 // Generate timestamp
3028 $postData[$test] = createTimestampFromSelections($test, $postData);
3029 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
3030 $GLOBALS['skip_config'][$test] = true;
3032 // Remove data from array
3033 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3034 unset($postData[$test . '_' . $rem]);
3045 // Reverts the german decimal comma into Computer decimal dot
3046 function convertCommaToDot ($str) {
3047 // Default float is not a float... ;-)
3050 // Which language is selected?
3051 switch (getLanguage()) {
3052 case 'de': // German language
3053 // Remove german thousand dots first
3054 $str = str_replace('.', '', $str);
3056 // Replace german commata with decimal dot and cast it
3057 $float = (float)str_replace(',', '.', $str);
3060 default: // US and so on
3061 // Remove thousand dots first and cast
3062 $float = (float)str_replace(',', '', $str);
3070 // Handle menu-depending failed logins and return the rendered content
3071 function handleLoginFailtures ($accessLevel) {
3072 // Default output is empty ;-)
3075 // Is the session data set?
3076 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3077 // Ignore zero values
3078 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3079 // Non-guest has login failures found, get both data and prepare it for template
3080 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3082 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3083 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3087 $OUT = loadTemplate('login_failures', true, $content);
3090 // Reset session data
3091 setSession('mxchange_' . $accessLevel.'_failures', '');
3092 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3095 // Return rendered content
3100 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3102 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3104 // Shall I remove the cache file?
3105 if (isCacheInstanceValid()) {
3107 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3109 $GLOBALS['cache_instance']->removeCacheFile($force);
3112 // Include file given?
3115 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3117 // Is the include there?
3118 if (isIncludeReadable($inc)) {
3119 // And rebuild it from scratch
3120 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3123 // Include not found!
3124 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3130 // Determines the real remote address
3131 function determineRealRemoteAddress () {
3132 // Is a proxy in use?
3133 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3135 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3136 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3137 // Yet, another proxy
3138 $address = $_SERVER['HTTP_CLIENT_IP'];
3140 // The regular address when no proxy was used
3141 $address = $_SERVER['REMOTE_ADDR'];
3144 // This strips out the real address from proxy output
3145 if (strstr($address, ',')) {
3146 $addressArray = explode(',', $address);
3147 $address = $addressArray[0];
3150 // Return the result
3154 // Adds a bonus mail to the queue
3155 // This is a high-level function!
3156 function addNewBonusMail ($data, $mode = '', $output=true) {
3157 // Use mode from data if not set and availble ;-)
3158 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3160 // Generate receiver list
3161 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3164 if (!empty($RECEIVER)) {
3165 // Add bonus mail to queue
3166 addBonusMailToQueue(
3178 // Mail inserted into bonus pool
3179 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3180 } elseif ($output) {
3181 // More entered than can be reached!
3182 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3185 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3189 // Determines referal id and sets it
3190 function determineReferalId () {
3191 // Skip this in non-html-mode
3192 if (getOutputMode() != 0) return false;
3194 // Check if refid is set
3195 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3197 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3198 // The variable user comes from the click-counter script click.php and we only accept this here
3199 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3200 } elseif (isPostRequestElementSet('refid')) {
3201 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3202 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3203 } elseif (isGetRequestElementSet('refid')) {
3204 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3205 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3206 } elseif (isGetRequestElementSet('ref')) {
3207 // Set refid=ref (the referal link uses such variable)
3208 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3209 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3210 // Set session refid als global
3211 $GLOBALS['refid'] = bigintval(getSession('refid'));
3212 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3213 // Select a random user which has confirmed enougth mails
3214 $GLOBALS['refid'] = determineRandomReferalId();
3215 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3216 // Set default refid as refid in URL
3217 $GLOBALS['refid'] = getConfig('def_refid');
3219 // No default ID when sql_patches is not installed or none set
3220 $GLOBALS['refid'] = 0;
3223 // Set cookie when default refid > 0
3224 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == 0) && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3226 setSession('refid', $GLOBALS['refid']);
3229 // Return determined refid
3230 return $GLOBALS['refid'];
3233 // Enables the reset mode and runs it
3234 function doReset () {
3235 // Enable the reset mode
3236 $GLOBALS['reset_enabled'] = true;
3239 runFilterChain('reset');
3242 // Our shutdown-function
3243 function shutdown () {
3244 // Call the filter chain 'shutdown'
3245 runFilterChain('shutdown', null);
3247 if (SQL_IS_LINK_UP()) {
3249 SQL_CLOSE(__FILE__, __LINE__);
3250 } elseif (!isInstallationPhase()) {
3252 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3255 // Stop executing here
3259 // Setter for userid
3260 function setUserId ($userid) {
3261 $GLOBALS['userid'] = bigintval($userid);
3264 // Getter for userid or returns zero
3265 function getUserId () {
3269 // Is the userid set?
3270 if (isUserIdSet()) {
3272 $userid = $GLOBALS['userid'];
3279 // Checks ether the userid is set
3280 function isUserIdSet () {
3281 return (isset($GLOBALS['userid']));
3284 // Handle message codes from URL
3285 function handleCodeMessage () {
3286 if (isGetRequestElementSet('code')) {
3287 // Default extension is 'unknown'
3290 // Is extension given?
3291 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3293 // Convert the 'code' parameter from URL to a human-readable message
3294 $message = getMessageFromErrorCode(getRequestElement('code'));
3296 // Load message template
3297 loadTemplate('message', false, $message);
3301 // Setter for extra title
3302 function setExtraTitle ($extraTitle) {
3303 $GLOBALS['extra_title'] = $extraTitle;
3306 // Getter for extra title
3307 function getExtraTitle () {
3308 // Is the extra title set?
3309 if (!isExtraTitleSet()) {
3310 // No, then abort here
3311 debug_report_bug('extra_title is not set!');
3315 return $GLOBALS['extra_title'];
3318 // Checks if the extra title is set
3319 function isExtraTitleSet () {
3320 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3323 // Generates a 'extension foo inactive' message
3324 function generateExtensionInactiveMessage ($ext_name) {
3325 // Is the extension empty?
3326 if (empty($ext_name)) {
3327 // This should not happen
3328 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3332 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3334 // Is an admin logged in?
3336 // Then output admin message
3337 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3340 // Return prepared message
3344 // Generates a 'extension foo not installed' message
3345 function generateExtensionNotInstalledMessage ($ext_name) {
3346 // Is the extension empty?
3347 if (empty($ext_name)) {
3348 // This should not happen
3349 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3353 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3355 // Is an admin logged in?
3357 // Then output admin message
3358 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3361 // Return prepared message
3365 // Generates a message depending on if the extension is not installed or not
3367 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3371 // Is the extension not installed or just deactivated?
3372 switch (isExtensionInstalled($ext_name)) {
3373 case true; // Deactivated!
3374 $message = generateExtensionInactiveMessage($ext_name);
3377 case false; // Not installed!
3378 $message = generateExtensionNotInstalledMessage($ext_name);
3381 default: // Should not happen!
3382 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3383 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3387 // Return the message
3391 // Reads a directory recursively by default and searches for files not matching
3392 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3393 // a whole directory.
3394 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3395 // Add default entries we should exclude
3396 $excludeArray[] = '.';
3397 $excludeArray[] = '..';
3398 $excludeArray[] = '.svn';
3399 $excludeArray[] = '.htaccess';
3401 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3406 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3409 while ($baseFile = readdir($dirPointer)) {
3410 // Exclude '.', '..' and entries in $excludeArray automatically
3411 if (in_array($baseFile, $excludeArray, true)) {
3413 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3417 // Construct include filename and FQFN
3418 $fileName = $baseDir . $baseFile;
3419 $FQFN = getConfig('PATH') . $fileName;
3421 // Remove double slashes
3422 $FQFN = str_replace('//', '/', $FQFN);
3424 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3425 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3426 // These Lines are only for debugging!!
3427 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3428 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3429 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3435 // Skip also files with non-matching prefix genericly
3436 if (($recursive === true) && (isDirectory($FQFN))) {
3437 // Is a redirectory so read it as well
3438 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3440 // And skip further processing
3442 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3444 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3446 } elseif (!isFileReadable($FQFN)) {
3447 // Not readable so skip it
3448 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3452 // Is the file a PHP script or other?
3453 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3454 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3455 // Is this a valid include file?
3456 if ($extension == '.php') {
3457 // Remove both for extension name
3458 $extName = substr($baseFile, strlen($prefix), -4);
3460 // Is the extension valid and active?
3461 if (isExtensionNameValid($extName)) {
3462 // Then add this file
3463 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3464 $files[] = $fileName;
3466 // Add non-extension files as well
3467 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3468 if ($addBaseDir === true) {
3469 $files[] = $fileName;
3471 $files[] = $baseFile;
3475 // We found .php file but should not search for them, why?
3476 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3478 } elseif (substr($baseFile, -4, 4) == $extension) {
3479 // Other, generic file found
3480 $files[] = $fileName;
3485 closedir($dirPointer);
3490 // Return array with include files
3491 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3495 // Maps a module name into a database table name
3496 function mapModuleToTable ($moduleName) {
3497 // Map only these, still lame code...
3498 switch ($moduleName) {
3499 // 'index' is the guest's menu
3500 case 'index': $moduleName = 'guest'; break;
3501 // ... and 'login' the member's menu
3502 case 'login': $moduleName = 'member'; break;
3503 // Anything else will not be mapped, silently.
3510 // Add SQL debug data to array for later output
3511 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3512 // Already executed?
3513 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3514 // Then abort here, we don't need to profile a query twice
3518 // Remeber this as profiled (or not, but we don't care here)
3519 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3521 // Do we have cache?
3522 if (!isset($GLOBALS['debug_sql_available'])) {
3523 // Check it and cache it in $GLOBALS
3524 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3527 // Don't execute anything here if we don't need or ext-other is missing
3528 if ($GLOBALS['debug_sql_available'] === false) {
3534 'num_rows' => SQL_NUMROWS($result),
3535 'affected' => SQL_AFFECTEDROWS(),
3536 'sql_str' => $sqlString,
3537 'timing' => $timing,
3538 'file' => basename($F),
3543 $GLOBALS['debug_sqls'][] = $record;
3546 // Initializes the cache instance
3547 function initCacheInstance () {
3548 // Load include for CacheSystem class
3549 loadIncludeOnce('inc/classes/cachesystem.class.php');
3551 // Initialize cache system only when it's needed
3552 $GLOBALS['cache_instance'] = new CacheSystem();
3553 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3554 // Failed to initialize cache sustem
3555 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3559 // Getter for message from array or raw message
3560 function getMessageFromIndexedArray ($message, $pos, $array) {
3561 // Check if the requested message was found in array
3562 if (isset($array[$pos])) {
3563 // ... if yes then use it!
3564 $ret = $array[$pos];
3566 // ... else use default message
3574 // Print code with line numbers
3575 function linenumberCode ($code) {
3576 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3577 $count_lines = count($codeE);
3579 $r = 'Line | Code:<br />';
3580 foreach($codeE as $line => $c) {
3581 $r .= '<div class="line"><span class="linenum">';
3582 if ($count_lines == 1) {
3585 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3590 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3593 return '<div class="code">' . $r . '</div>';
3596 // Convert ';' to ', ' for e.g. receiver list
3597 function convertReceivers ($old) {
3598 return str_replace(';', ', ', $old);
3601 //////////////////////////////////////////////////
3602 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3603 //////////////////////////////////////////////////
3605 if (!function_exists('html_entity_decode')) {
3606 // Taken from documentation on www.php.net
3607 function html_entity_decode ($string) {
3608 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3609 $trans_tbl = array_flip($trans_tbl);
3610 return strtr($string, $trans_tbl);
3614 if (!function_exists('http_build_query')) {
3615 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3616 function http_build_query($data, $prefix='', $sep='', $key='') {
3618 foreach ((array)$data as $k => $v) {
3619 if (is_int($k) && $prefix != null) {
3620 $k = urlencode($prefix . $k);
3623 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3625 if (is_array($v) || is_object($v)) {
3626 array_push($ret, http_build_query($v, '', $sep, $k));
3628 array_push($ret, $k.'='.urlencode($v));
3632 if (empty($sep)) $sep = ini_get('arg_separator.output');
3634 return implode($sep, $ret);