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;
250 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
253 // Check for admin/guest/member templates
254 if (substr($template, 0, 6) == 'admin_') {
255 // Admin template found
257 } elseif (substr($template, 0, 6) == 'guest_') {
258 // Guest template found
260 } elseif (substr($template, 0, 7) == 'member_') {
261 // Member template found
263 } elseif (substr($template, 0, 8) == 'install_') {
264 // Installation template found
266 } elseif (substr($template, 0, 4) == 'ext_') {
267 // Extension template found
269 } elseif (substr($template, 0, 3) == 'la_') {
270 // 'Logical-area' template found
272 } elseif (substr($template, 0, 3) == 'js_') {
273 // JavaScript template found
275 } elseif (substr($template, 0, 5) == 'menu_') {
276 // Menu template found
279 // Test for extension
280 $test = substr($template, 0, strpos($template, '_'));
282 // Probe for valid extension name
283 if (isExtensionNameValid($test)) {
284 // Set extra path to extension's name
289 ////////////////////////
290 // Generate file name //
291 ////////////////////////
292 $FQFN = $basePath . $mode . $template . '.tpl';
294 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
295 // Select what depended header/footer template file for admin/guest/member area
296 $file2 = sprintf("%s%s%s_%s.tpl",
304 if (isFileReadable($file2)) $FQFN = $file2;
306 // Remove variable from memory
310 // Does the special template exists?
311 if (!isFileReadable($FQFN)) {
312 // Reset to default template
313 $FQFN = $basePath . $template . '.tpl';
316 // Now does the final template exists?
317 if (isFileReadable($FQFN)) {
318 // The local file does exists so we load it. :)
319 $GLOBALS['tpl_content'] = readFromFile($FQFN);
321 // Replace ' to our own chars to preventing them being quoted
322 while (strpos($GLOBALS['tpl_content'], "'") !== false) { $GLOBALS['tpl_content'] = str_replace("'", '{QUOT}', $GLOBALS['tpl_content']); }
324 // Do we have to compile the code?
326 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
327 // Normal HTML output?
328 if (getOutputMode() == 0) {
329 // Add surrounding HTML comments to help finding bugs faster
330 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
332 // Prepare eval() command
333 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
335 // Prepare eval() command
336 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
339 // Add surrounding HTML comments to help finding bugs faster
340 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
341 $eval = '$ret = "' . smartAddSlashes($ret) . '";';
344 // Cache the eval() command here
345 $GLOBALS['template_eval'][$template] = $eval;
348 eval($GLOBALS['template_eval'][$template]);
351 $GLOBALS['template_eval'][$template] = '404';
353 } elseif (((isAdmin()) || ((isInstalling()) && (!isInstalled()))) && ($GLOBALS['template_eval'][$template] == '404')) {
354 // Only admins shall see this warning or when installation mode is active
355 $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
356 (' . $template . ')<br />
358 {--TEMPLATE_CONTENT--}
359 <pre>' . print_r($content, true) . '</pre>
361 <pre>' . print_r($DATA, true) . '</pre>
365 eval($GLOBALS['template_eval'][$template]);
368 // Do we have some content to output or return?
370 // Not empty so let's put it out! ;)
371 if ($return === true) {
372 // Return the HTML code
378 } elseif (isDebugModeEnabled()) {
379 // Warning, empty output!
380 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
384 // Loads an email template and compiles it
385 function loadEmailTemplate ($template, $content = array(), $UID = 0) {
388 // Our configuration is kept non-global here
389 $_CONFIG = getConfigArray();
391 // Make sure all template names are lowercase!
392 $template = strtolower($template);
394 // Default 'nickname' if extension is not installed
397 // Prepare IP number and User Agent
398 $REMOTE_ADDR = detectRemoteAddr();
399 $HTTP_USER_AGENT = detectUserAgent();
402 $ADMIN = getConfig('MAIN_TITLE');
404 // Is the admin logged in?
407 $adminId = getCurrentAdminId();
410 $ADMIN = getAdminEmail($adminId);
413 // Neutral email address is default
414 $email = getConfig('WEBMASTER');
416 // Expiration in a nice output format
417 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
418 if (getConfig('auto_purge') == 0) {
419 // Will never expire!
420 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
422 // Create nice date string
423 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
426 // Is content an array?
427 if (is_array($content)) {
428 // Add expiration to array, $EXPIRATION is now deprecated!
429 $content['expiration'] = $EXPIRATION;
433 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content).'<br />');
434 if (($UID > 0) && (is_array($content))) {
435 // If nickname extension is installed, fetch nickname as well
436 if (isNicknameUsed($UID)) {
437 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
439 fetchUserData($UID, 'nickname');
441 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
446 // Merge data if valid
447 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
448 if (isUserDataValid()) {
449 $content = merge_array($content, getUserDataArray());
451 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
454 // Translate M to male or F to female if present
455 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
457 // Overwrite email from data if present
458 if (isset($content['email'])) $email = $content['email'];
460 // Store email for some functions in global data array
461 $DATA['email'] = $email;
464 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
466 // Check for admin/guest/member templates
467 if (substr($template, 0, 6) == 'admin_') {
468 // Admin template found
469 $FQFN = $basePath.'admin/' . $template.'.tpl';
470 } elseif (substr($template, 0, 6) == 'guest_') {
471 // Guest template found
472 $FQFN = $basePath.'guest/' . $template.'.tpl';
473 } elseif (substr($template, 0, 7) == 'member_') {
474 // Member template found
475 $FQFN = $basePath.'member/' . $template.'.tpl';
477 // Test for extension
478 $test = substr($template, 0, strpos($template, '_'));
479 if (isExtensionNameValid($test)) {
480 // Set extra path to extension's name
481 $FQFN = $basePath . $test.'/' . $template.'.tpl';
483 // No special filename
484 $FQFN = $basePath . $template.'.tpl';
488 // Does the special template exists?
489 if (!isFileReadable($FQFN)) {
490 // Reset to default template
491 $FQFN = $basePath . $template.'.tpl';
494 // Now does the final template exists?
496 if (isFileReadable($FQFN)) {
497 // The local file does exists so we load it. :)
498 $GLOBALS['tpl_content'] = readFromFile($FQFN);
501 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode(smartAddSlashes($GLOBALS['tpl_content']))."\");";
502 eval($GLOBALS['tpl_content']);
503 } elseif (!empty($template)) {
504 // Template file not found!
505 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
506 {--TEMPLATE_CONTENT--}
507 <pre>".print_r($content, true)."</pre>
509 <pre>".print_r($DATA, true)."</pre>
512 // Debug mode not active? Then remove the HTML tags
513 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
515 // No template name supplied!
516 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
519 // Is there some content?
520 if (empty($newContent)) {
522 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
523 // Add last error if the required function exists
524 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
527 // Remove content and data
531 // Compile the code and eval it
532 $eval = '$newContent = "' . compileCode(smartAddSlashes($newContent)) . '";';
539 // Send mail out to an email address
540 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
541 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
543 // Compile subject line (for POINTS constant etc.)
544 eval("\$subject = decodeEntities(\"".compileCode(smartAddSlashes($subject))."\");");
547 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
548 // Value detected, is the message extension installed?
549 // @TODO Extension 'msg' does not exist
550 if (isExtensionActive('msg')) {
551 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
554 // Does the user exist?
555 if (fetchUserData($toEmail)) {
557 $toEmail = getUserData('email');
560 $toEmail = getConfig('WEBMASTER');
563 } elseif ($toEmail == '0') {
565 $toEmail = getConfig('WEBMASTER');
567 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
569 // Check for PHPMailer or debug-mode
570 if (!checkPhpMailerUsage()) {
571 // Not in PHPMailer-Mode
572 if (empty($mailHeader)) {
573 // Load email header template
574 $mailHeader = loadEmailTemplate('header');
577 $mailHeader .= loadEmailTemplate('header');
579 } elseif (isDebugModeEnabled()) {
580 if (empty($mailHeader)) {
581 // Load email header template
582 $mailHeader = loadEmailTemplate('header');
585 $mailHeader .= loadEmailTemplate('header');
590 eval("\$toEmail = \"".compileCode(smartAddSlashes($toEmail))."\";");
593 eval("\$message = \"".compileCode(smartAddSlashes($message))."\";");
595 // Fix HTML parameter (default is no!)
596 if (empty($isHtml)) $isHtml = 'N';
597 if (isDebugModeEnabled()) {
598 // In debug mode we want to display the mail instead of sending it away so we can debug this part
600 Headers : ' . str_replace('<', '<', str_replace('>', '>', htmlentities(trim($mailHeader)))) . '
601 To : ' . $toEmail . '
602 Subject : ' . $subject . '
603 Message : ' . $message . '
605 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
606 // Send mail as HTML away
607 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
608 } elseif (!empty($toEmail)) {
610 sendRawEmail($toEmail, $subject, $message, $mailHeader);
611 } elseif ($isHtml != 'Y') {
613 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
617 // Check if legacy or PHPMailer command
618 // @TODO Rewrite this to an extension 'smtp'
620 function checkPhpMailerUsage() {
621 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
624 // Send out a raw email with PHPMailer class or legacy mail() command
625 function sendRawEmail ($toEmail, $subject, $message, $from) {
626 // Shall we use PHPMailer class or legacy mode?
627 if (checkPhpMailerUsage()) {
628 // Use PHPMailer class with SMTP enabled
629 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
630 loadIncludeOnce('inc/phpmailer/class.smtp.php');
633 $mail = new PHPMailer();
635 // Set charset to UTF-8
636 $mail->CharSet('UTF-8');
638 // Path for PHPMailer
639 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
642 $mail->SMTPAuth = true;
643 $mail->Host = getConfig('SMTP_HOSTNAME');
645 $mail->Username = getConfig('SMTP_USER');
646 $mail->Password = getConfig('SMTP_PASSWORD');
648 $mail->From = getConfig('WEBMASTER');
652 $mail->FromName = getConfig('MAIN_TITLE');
653 $mail->Subject = $subject;
654 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
655 $mail->Body = $message;
656 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
657 $mail->WordWrap = 70;
660 $mail->Body = decodeEntities($message);
662 $mail->AddAddress($toEmail, '');
663 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
664 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
665 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
668 // Use legacy mail() command
669 mail($toEmail, $subject, decodeEntities($message), $from);
673 // Generate a password in a specified length or use default password length
674 function generatePassword ($length = 0) {
675 // Auto-fix invalid length of zero
676 if ($length == 0) $length = getConfig('pass_len');
678 // Initialize array with all allowed chars
679 $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,-,+,_,/,.');
681 // Start creating password
683 for ($i = 0; $i < $length; $i++) {
684 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
687 // When the size is below 40 we can also add additional security by scrambling
688 // it. Otherwise we may corrupt hashes
689 if (strlen($PASS) <= 40) {
690 // Also scramble the password
691 $PASS = scrambleString($PASS);
694 // Return the password
698 // Generates a human-readable timestamp from the Uni* stamp
699 function generateDateTime ($time, $mode = 0) {
700 // Filter out numbers
701 $time = bigintval($time);
703 // If the stamp is zero it mostly didn't "happen"
706 return getMessage('NEVER_HAPPENED');
709 switch (getLanguage()) {
710 case 'de': // German date / time format
712 case 0: $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
713 case 1: $ret = strtolower(date('d.m.Y - H:i', $time)); break;
714 case 2: $ret = date('d.m.Y|H:i', $time); break;
715 case 3: $ret = date('d.m.Y', $time); break;
717 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
722 default: // Default is the US date / time format!
724 case 0: $ret = date('r', $time); break;
725 case 1: $ret = date('Y-m-d - g:i A', $time); break;
726 case 2: $ret = date('y-m-d|H:i', $time); break;
727 case 3: $ret = date('y-m-d', $time); break;
729 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
738 // Translates Y/N to yes/no
739 function translateYesNo ($yn) {
741 $translated = '??? (' . $yn . ')';
743 case 'Y': $translated = getMessage('YES'); break;
744 case 'N': $translated = getMessage('NO'); break;
747 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
755 // Translates the "pool type" into human-readable
756 function translatePoolType ($type) {
757 // Default?type is unknown
758 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
761 $constName = sprintf("POOL_TYPE_%s", $type);
764 if (isMessageIdValid($constName)) {
766 $translated = getMessage($constName);
769 // Return "translation"
773 // Translates the american decimal dot into a german comma
774 function translateComma ($dotted, $cut = true, $max = 0) {
775 // Default is 3 you can change this in admin area "Misc -> Misc Options"
776 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
778 // Use from config is default
779 $maxComma = getConfig('max_comma');
781 // Use from parameter?
782 if ($max > 0) $maxComma = $max;
785 if (($cut === true) && ($max == 0)) {
786 // Test for commata if in cut-mode
787 $com = explode('.', $dotted);
788 if (count($com) < 2) {
789 // Don't display commatas even if there are none... ;-)
795 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
798 switch (getLanguage()) {
799 case 'de': // German language
800 $dotted = number_format($dotted, $maxComma, ',', '.');
803 default: // All others
804 $dotted = number_format($dotted, $maxComma, '.', ',');
808 // Return translated value
812 // Translate Uni*-like gender to human-readable
813 function translateGender ($gender) {
815 $ret = '!' . $gender . '!';
817 // Male/female or company?
819 case 'M': $ret = getMessage('GENDER_M'); break;
820 case 'F': $ret = getMessage('GENDER_F'); break;
821 case 'C': $ret = getMessage('GENDER_C'); break;
823 // Log unknown gender
824 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
828 // Return translated gender
832 // "Translates" the user status
833 function translateUserStatus ($status) {
834 // Generate message depending on status
839 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
844 $ret = getMessage('ACCOUNT_DELETED');
848 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
849 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
857 // Generates an URL for the dereferer
858 function generateDerefererUrl ($URL) {
859 // Don't de-refer our own links!
860 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
861 // De-refer this link
862 $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
869 // Generates an URL for the frametester
870 function generateFrametesterUrl ($URL) {
871 // Prepare frametester URL
872 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
873 encodeString(compileUriCode($URL))
876 // Return the new URL
877 return $frametesterUrl;
880 // Count entries from e.g. a selection box
881 function countSelection ($array) {
883 if (!is_array($array)) {
885 debug_report_bug(__FUNCTION__.': No array provided.');
892 foreach ($array as $key => $selected) {
894 if (!empty($selected)) $ret++;
897 // Return counted selections
901 // Generate XHTML code for the CAPTCHA
902 function generateCaptchaCode ($code, $type, $DATA, $userid) {
903 return '<img border="0" alt="Code ' . $code . '" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
906 // Generates a timestamp (some wrapper for mktime())
907 function makeTime ($hours, $minutes, $seconds, $stamp) {
908 // Extract day, month and year from given timestamp
909 $days = date('d', $stamp);
910 $months = date('m', $stamp);
911 $years = date('Y', $stamp);
913 // Create timestamp for wished time which depends on extracted date
924 // Redirects to an URL and if neccessarry extends it with own base URL
925 function redirectToUrl ($URL) {
927 eval('$URL = "' . compileCode($URL) . '";');
929 // Check if http(s):// is there
930 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
931 // Make all URLs full-qualified
932 $URL = getConfig('URL') . '/' . $URL;
935 // Three different debug ways...
936 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
937 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
938 //* DEBUG: */ die($URL);
940 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
941 $rel = ' rel="external"';
943 // Do we have internal or external URL?
944 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
945 // Own (=internal) URL
950 $GLOBALS['output'] = ob_get_contents();
952 // Clear it only if there is content
953 if (!empty($GLOBALS['output'])) {
957 // Simple probe for bots/spiders from search engines
958 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
959 // Secure the URL against bad things such als HTML insertions and so on...
960 $URL = secureString($URL);
962 // Output new location link as anchor
963 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
964 } elseif (!headers_sent()) {
965 // Load URL when headers are not sent
966 //* DEBUG: */ debug_report_bug("URL={$URL}");
967 sendHeader('Location: '.str_replace('&', '&', $URL));
969 // Output error message
970 loadInclude('inc/header.php');
971 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
972 loadInclude('inc/footer.php');
975 // Shut the mailer down here
979 // Wrapper for redirectToUrl but URL comes from a configuration entry
980 function redirectToConfiguredUrl ($configEntry) {
982 $URL = getConfig($configEntry);
987 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
994 // Compiles the given HTML/mail code
995 function compileCode ($code, $simple = false, $constants = true, $full = true) {
996 // Is the code a string?
997 if (!is_string($code)) {
998 // Silently return it
1002 // Init replacement-array with full security characters
1003 $secChars = $GLOBALS['security_chars'];
1005 // Select smaller set of chars to replace when we e.g. want to compile URLs
1006 if ($full === false) $secChars = $GLOBALS['url_chars'];
1008 // Compile more through a filter
1009 $code = runFilterChain('compile_code', $code);
1011 // Compile constants
1012 if ($constants === true) {
1013 // BEFORE 0.2.1 : Language and data constants
1014 // WITH 0.2.1+ : Only language constants
1015 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1017 // BEFORE 0.2.1 : Not used
1018 // WITH 0.2.1+ : Data constants
1019 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1022 // Compile QUOT and other non-HTML codes
1023 foreach ($secChars['to'] as $k => $to) {
1024 // Do the reversed thing as in inc/libs/security_functions.php
1025 $code = str_replace($to, $secChars['from'][$k], $code);
1028 // But shall I keep simple quotes for later use?
1029 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1031 // Find $content[bla][blub] entries
1032 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1034 // Are some matches found?
1035 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1036 // Replace all matches
1037 $matchesFound = array();
1038 foreach ($matches[0] as $key => $match) {
1039 // Fuzzy look has failed by default
1040 $fuzzyFound = false;
1042 // Fuzzy look on match if already found
1043 foreach ($matchesFound as $found => $set) {
1045 $test = substr($found, 0, strlen($match));
1047 // Does this entry exist?
1048 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1049 if ($test == $match) {
1051 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1058 if ($fuzzyFound === true) continue;
1060 // Take all string elements
1061 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1062 // Replace it in the code
1063 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1064 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1065 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1066 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1067 $matchesFound[$match] = 1;
1068 } elseif (!isset($matchesFound[$match])) {
1069 // Not yet replaced!
1070 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1071 $code = str_replace($match, "\"." . $match.".\"", $code);
1072 $matchesFound[$match] = 1;
1077 // Return compiled code
1081 /************************************************************************
1083 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1084 * $a_sort sortiert: *
1086 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1087 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1088 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1089 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1090 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1092 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1093 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1094 * Sie, dass es doch nicht so schwer ist! :-) *
1096 ************************************************************************/
1097 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1099 while ($primary_key < count($a_sort)) {
1100 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1101 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1103 if ($nums === false) {
1104 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1105 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1106 } elseif ($key != $key2) {
1107 // Sort numbers (E.g.: 9 < 10)
1108 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1109 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1113 // We have found two different values, so let's sort whole array
1114 foreach ($dummy as $sort_key => $sort_val) {
1115 $t = $dummy[$sort_key][$key];
1116 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1117 $dummy[$sort_key][$key2] = $t;
1128 // Write back sorted array
1133 function addSelectionBox ($type, $default, $prefix = '', $id = 0) {
1136 if ($type == 'yn') {
1137 // This is a yes/no selection only!
1138 if ($id > 0) $prefix .= "[" . $id."]";
1139 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1141 // Begin with regular selection box here
1142 if (!empty($prefix)) $prefix .= "_";
1144 if ($id > 0) $type2 .= "[" . $id."]";
1145 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1150 for ($idx = 1; $idx < 32; $idx++) {
1151 $OUT .= "<option value=\"" . $idx."\"";
1152 if ($default == $idx) $OUT .= ' selected="selected"';
1153 $OUT .= ">" . $idx."</option>\n";
1157 case 'month': // Month
1158 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1159 $OUT .= "<option value=\"" . $month."\"";
1160 if ($default == $month) $OUT .= ' selected="selected"';
1161 $OUT .= ">" . $descr."</option>\n";
1165 case 'year': // Year
1167 $year = date('Y', time());
1169 // Use configured min age or fixed?
1170 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1172 $startYear = $year - getConfig('min_age');
1175 $startYear = $year - 16;
1178 // Calculate earliest year (100 years old people can still enter Internet???)
1179 $minYear = $year - 100;
1181 // Check if the default value is larger than minimum and bigger than actual year
1182 if (($default > $minYear) && ($default >= $year)) {
1183 for ($idx = $year; $idx < ($year + 11); $idx++) {
1184 $OUT .= "<option value=\"" . $idx."\"";
1185 if ($default == $idx) $OUT .= ' selected="selected"';
1186 $OUT .= ">" . $idx."</option>\n";
1188 } elseif ($default == -1) {
1189 // Current year minus 1
1190 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1192 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1195 // Get current year and subtract the configured minimum age
1196 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1197 // Calculate earliest year depending on extension version
1198 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1199 // Use configured minimum age
1200 $year = date('Y', time()) - getConfig('min_age');
1202 // Use fixed 16 years age
1203 $year = date('Y', time()) - 16;
1206 // Construct year selection list
1207 for ($idx = $minYear; $idx <= $year; $idx++) {
1208 $OUT .= "<option value=\"" . $idx."\"";
1209 if ($default == $idx) $OUT .= ' selected="selected"';
1210 $OUT .= ">" . $idx."</option>\n";
1217 for ($idx = 0; $idx < 60; $idx+=5) {
1218 if (strlen($idx) == 1) $idx = 0 . $idx;
1219 $OUT .= "<option value=\"" . $idx."\"";
1220 if ($default == $idx) $OUT .= ' selected="selected"';
1221 $OUT .= ">" . $idx."</option>\n";
1226 for ($idx = 0; $idx < 24; $idx++) {
1227 if (strlen($idx) == 1) $idx = 0 . $idx;
1228 $OUT .= "<option value=\"" . $idx."\"";
1229 if ($default == $idx) $OUT .= ' selected="selected"';
1230 $OUT .= ">" . $idx."</option>\n";
1235 $OUT .= "<option value=\"Y\"";
1236 if ($default == 'Y') $OUT .= ' selected="selected"';
1237 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1238 if ($default != 'Y') $OUT .= ' selected="selected"';
1239 $OUT .= ">{--NO--}</option>\n";
1242 $OUT .= " </select>\n";
1247 // Deprecated : $length
1250 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1251 // Build server string
1252 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1255 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1256 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1257 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1258 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1259 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1261 // Build string from misc data
1262 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1264 // Add more additional data
1265 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1267 // Add referal id, language, theme and userid
1268 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1269 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1270 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1271 $data .= getConfig('ENCRYPT_SEPERATOR') . getUserId();
1273 // Calculate number for generating the code
1274 $a = $code + getConfig('_ADD') - 1;
1276 if (isConfigEntrySet('master_salt')) {
1277 // Generate hash with master salt from modula of number with the prime number and other data
1278 $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'));
1280 // Create number from hash
1281 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1283 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1284 $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')));
1286 // Create number from hash
1287 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1290 // At least 10 numbers shall be secure enought!
1291 $len = getConfig('code_length');
1292 if ($len == 0) $len = $length;
1293 if ($len == 0) $len = 10;
1295 // Cut off requested counts of number
1296 $return = substr(str_replace('.', '', $rcode), 0, $len);
1298 // Done building code
1302 // Does only allow numbers
1303 function bigintval ($num, $castValue = true) {
1304 // Filter all numbers out
1305 $ret = preg_replace('/[^0123456789]/', '', $num);
1308 if ($castValue) $ret = (double)$ret;
1310 // Has the whole value changed?
1311 // @TODO Remove this if() block if all is working fine
1312 if ('' . $ret . '' != '' . $num . '') {
1314 //debug_report_bug("{$ret}<>{$num}");
1321 // Insert the code in $img_code into jpeg or PNG image
1322 function generateImageOrCode ($img_code, $headerSent=true) {
1323 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1324 // Stop execution of function here because of over-sized code length
1326 } elseif ($headerSent === false) {
1327 // Return in an HTML code code
1328 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1332 $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
1333 if (isFileReadable($img)) {
1334 // Switch image type
1335 switch (getConfig('img_type'))
1338 // Okay, load image and hide all errors
1339 $image = imagecreatefromjpeg($img);
1343 // Okay, load image and hide all errors
1344 $image = imagecreatefrompng($img);
1348 // Exit function here
1349 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1353 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1354 $text_color = imagecolorallocate($image, 0, 0, 0);
1356 // Insert code into image
1357 imagestring($image, 5, 14, 2, $img_code, $text_color);
1359 // Return to browser
1360 sendHeader('Content-Type: image/' . getConfig('img_type'));
1362 // Output image with matching image factory
1363 switch (getConfig('img_type')) {
1364 case 'jpg': imagejpeg($image); break;
1365 case 'png': imagepng($image); break;
1368 // Remove image from memory
1369 imagedestroy($image);
1371 // Create selection box or array of splitted timestamp
1372 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1373 // Calculate 2-seconds timestamp
1374 $stamp = round($timestamp);
1375 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1377 // Do we have a leap year?
1379 $TEST = date('Y', time()) / 4;
1380 $M1 = date('m', time());
1381 $M2 = date('m', (time() + $timestamp));
1383 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1384 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1386 // First of all years...
1387 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1388 //* DEBUG: */ print("Y={$Y}<br />");
1390 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1391 //* DEBUG: */ print("M={$M}<br />");
1393 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1394 //* DEBUG: */ print("W={$W}<br />");
1396 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1397 //* DEBUG: */ print("D={$D}<br />");
1399 $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));
1400 //* DEBUG: */ print("h={$h}<br />");
1402 $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));
1403 //* DEBUG: */ print("m={$m}<br />");
1404 // And at last seconds...
1405 $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));
1406 //* DEBUG: */ print("s={$s}<br />");
1408 // Is seconds zero and time is < 60 seconds?
1409 if (($s == 0) && ($timestamp < 60)) {
1411 $s = round($timestamp);
1415 // Now we convert them in seconds...
1417 if ($return_array) {
1418 // Just put all data in an array for later use
1430 $OUT = "<div align=\"" . $align."\">\n";
1431 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1434 if (ereg('Y', $display) || (empty($display))) {
1435 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1438 if (ereg('M', $display) || (empty($display))) {
1439 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1442 if (ereg("W", $display) || (empty($display))) {
1443 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1446 if (ereg("D", $display) || (empty($display))) {
1447 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1450 if (ereg("h", $display) || (empty($display))) {
1451 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1454 if (ereg('m', $display) || (empty($display))) {
1455 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1458 if (ereg("s", $display) || (empty($display))) {
1459 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1465 if (ereg('Y', $display) || (empty($display))) {
1466 // Generate year selection
1467 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1468 for ($idx = 0; $idx <= 10; $idx++) {
1469 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1470 if ($idx == $Y) $OUT .= ' selected="selected"';
1471 $OUT .= ">" . $idx."</option>\n";
1473 $OUT .= " </select></td>\n";
1475 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1478 if (ereg('M', $display) || (empty($display))) {
1479 // Generate month selection
1480 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1481 for ($idx = 0; $idx <= 11; $idx++)
1483 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1484 if ($idx == $M) $OUT .= ' selected="selected"';
1485 $OUT .= ">" . $idx."</option>\n";
1487 $OUT .= " </select></td>\n";
1489 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1492 if (ereg("W", $display) || (empty($display))) {
1493 // Generate week selection
1494 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1495 for ($idx = 0; $idx <= 4; $idx++) {
1496 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1497 if ($idx == $W) $OUT .= ' selected="selected"';
1498 $OUT .= ">" . $idx."</option>\n";
1500 $OUT .= " </select></td>\n";
1502 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1505 if (ereg("D", $display) || (empty($display))) {
1506 // Generate day selection
1507 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1508 for ($idx = 0; $idx <= 31; $idx++) {
1509 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1510 if ($idx == $D) $OUT .= ' selected="selected"';
1511 $OUT .= ">" . $idx."</option>\n";
1513 $OUT .= " </select></td>\n";
1515 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1518 if (ereg("h", $display) || (empty($display))) {
1519 // Generate hour selection
1520 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1521 for ($idx = 0; $idx <= 23; $idx++) {
1522 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1523 if ($idx == $h) $OUT .= ' selected="selected"';
1524 $OUT .= ">" . $idx."</option>\n";
1526 $OUT .= " </select></td>\n";
1528 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1531 if (ereg('m', $display) || (empty($display))) {
1532 // Generate minute selection
1533 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1534 for ($idx = 0; $idx <= 59; $idx++) {
1535 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1536 if ($idx == $m) $OUT .= ' selected="selected"';
1537 $OUT .= ">" . $idx."</option>\n";
1539 $OUT .= " </select></td>\n";
1541 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1544 if (ereg("s", $display) || (empty($display))) {
1545 // Generate second selection
1546 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1547 for ($idx = 0; $idx <= 59; $idx++) {
1548 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1549 if ($idx == $s) $OUT .= ' selected="selected"';
1550 $OUT .= ">" . $idx."</option>\n";
1552 $OUT .= " </select></td>\n";
1554 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1557 $OUT .= "</table>\n";
1559 // Return generated HTML code
1565 function createTimestampFromSelections ($prefix, $postData) {
1566 // Initial return value
1569 // Do we have a leap year?
1571 $TEST = date('Y', time()) / 4;
1572 $M1 = date('m', time());
1573 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1574 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1575 // First add years...
1576 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1578 $ret += $postData[$prefix."_mo"] * 2628000;
1580 $ret += $postData[$prefix."_we"] * 604800;
1582 $ret += $postData[$prefix."_da"] * 86400;
1584 $ret += $postData[$prefix."_ho"] * 3600;
1586 $ret += $postData[$prefix."_mi"] * 60;
1587 // And at last seconds...
1588 $ret += $postData[$prefix."_se"];
1589 // Return calculated value
1593 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1594 function createFancyTime ($stamp) {
1595 // Get data array with years/months/weeks/days/...
1596 $data = createTimeSelections($stamp, '', '', '', true);
1598 foreach($data as $k => $v) {
1600 // Value is greater than 0 "eval" data to return string
1601 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1606 // Do we have something there?
1607 if (strlen($ret) > 0) {
1608 // Remove leading commata and space
1609 $ret = substr($ret, 2);
1612 $ret = "0 {--_SECONDS--}";
1615 // Return fancy time string
1619 // Generates a navigation row for listing emails
1620 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1621 $SEP = ''; $TOP = '';
1622 if ($show_form === false) {
1624 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1628 for ($page = 1; $page <= $PAGES; $page++) {
1629 // Is the page currently selected or shall we generate a link to it?
1630 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1631 // Is currently selected, so only highlight it
1632 $NAV .= '<strong>-';
1634 // Open anchor tag and add base URL
1635 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1637 // Add userid when we shall show all mails from a single member
1638 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1640 // Close open anchor tag
1644 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1645 // Is currently selected, so only highlight it
1646 $NAV .= '-</strong>';
1652 // Add seperator if we have not yet reached total pages
1653 if ($page < $PAGES) $NAV .= ' | ';
1656 // Define constants only once
1657 $content['nav'] = $NAV;
1658 $content['span'] = $colspan;
1659 $content['top'] = $TOP;
1660 $content['sep'] = $SEP;
1662 // Load navigation template
1663 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1665 if ($return === true) {
1666 // Return generated HTML-Code
1674 // Extract host from script name
1675 function extractHostnameFromUrl (&$script) {
1676 // Use default SERVER_URL by default... ;) So?
1677 $url = getConfig('SERVER_URL');
1679 // Is this URL valid?
1680 if (substr($script, 0, 7) == 'http://') {
1681 // Use the hostname from script URL as new hostname
1682 $url = substr($script, 7);
1683 $extract = explode('/', $url);
1685 // Done extracting the URL :)
1688 // Extract host name
1689 $host = str_replace('http://', '', $url);
1690 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1692 // Generate relative URL
1693 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1694 if (substr(strtolower($script), 0, 7) == 'http://') {
1695 // But only if http:// is in front!
1696 $script = substr($script, (strlen($url) + 7));
1697 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1699 $script = substr($script, (strlen($url) + 8));
1702 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1703 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1709 // Send a GET request
1710 function sendGetRequest ($script, $data = array()) {
1711 // Extract host name from script
1712 $host = extractHostnameFromUrl($script);
1715 $scriptData = http_build_query($data, '', '&');
1717 // Do we have a question-mark in the script?
1718 if (strpos($script, '?') === false) {
1719 // No, so first char must be question mark
1720 $scriptData = '?' . $scriptData;
1723 $scriptData = '&' . $scriptData;
1727 $script .= $scriptData;
1729 // Generate GET request header
1730 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1731 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1732 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1733 if (isConfigEntrySet('FULL_VERSION')) {
1734 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1736 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1738 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1739 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1740 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1742 // Send the raw request
1743 $response = sendRawRequest($host, $request);
1745 // Return the result to the caller function
1749 // Send a POST request
1750 function sendPostRequest ($script, $postData) {
1751 // Is postData an array?
1752 if (!is_array($postData)) {
1754 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1755 return array('', '', '');
1758 // Compile the script name
1759 $script = compileCode($script);
1761 // Extract host name from script
1762 $host = extractHostnameFromUrl($script);
1764 // Construct request
1765 $data = http_build_query($postData, '', '&');
1767 // Generate POST request header
1768 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1769 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1770 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1771 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1772 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1773 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1774 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1775 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1778 // Send the raw request
1779 $response = sendRawRequest($host, $request);
1781 // Return the result to the caller function
1785 // Sends a raw request to another host
1786 function sendRawRequest ($host, $request) {
1787 // Init errno and errdesc with 'all fine' values
1788 $errno = 0; $errdesc = '';
1791 $response = array('', '', '');
1793 // Default is not to use proxy
1796 // Are proxy settins set?
1797 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1803 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1804 if ($useProxy === true) {
1805 // Connect to host through proxy connection
1806 $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1808 // Connect to host directly
1809 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1813 if (!is_resource($fp)) {
1819 if ($useProxy === true) {
1820 // Generate CONNECT request header
1821 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1822 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1824 // Use login data to proxy? (username at least!)
1825 if (getConfig('proxy_username') != '') {
1827 $encodedAuth = base64_encode(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(getConfig('proxy_password')));
1828 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1831 // Add last new-line
1832 $proxyTunnel .= getConfig('HTTP_EOL');
1833 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1836 fputs($fp, $proxyTunnel);
1840 // No response received
1844 // Read the first line
1845 $resp = trim(fgets($fp, 10240));
1846 $respArray = explode(' ', $resp);
1847 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1848 // Invalid response!
1854 fputs($fp, $request);
1857 while (!feof($fp)) {
1858 $response[] = trim(fgets($fp, 1024));
1864 // Skip first empty lines
1866 foreach ($resp as $idx => $line) {
1868 $line = trim($line);
1870 // Is this line empty?
1873 array_shift($response);
1875 // Abort on first non-empty line
1880 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1882 // Proxy agent found?
1883 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1884 // Proxy header detected, so remove two lines
1885 array_shift($response);
1886 array_shift($response);
1889 // Was the request successfull?
1890 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1891 // Not found / access forbidden
1892 $response = array('', '', '');
1899 // Taken from www.php.net eregi() user comments
1900 function isEmailValid ($email) {
1902 $email = compileCode($email);
1904 // Check first part of email address
1905 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1908 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1911 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1913 // Return check result
1914 return preg_match($regex, $email);
1917 // Function taken from user comments on www.php.net / function eregi()
1918 function isUrlValid ($URL, $compile=true) {
1919 // Trim URL a little
1920 $URL = trim(urldecode($URL));
1921 //* DEBUG: */ outputHtml($URL.'<br />');
1923 // Compile some chars out...
1924 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1925 //* DEBUG: */ outputHtml($URL.'<br />');
1927 // Check for the extension filter
1928 if (isExtensionActive('filter')) {
1929 // Use the extension's filter set
1930 return FILTER_VALIDATE_URL($URL, false);
1933 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1934 // https:// in front of the URLs
1935 return isUrlValidSimple($URL);
1938 // Generate a list of administrative links to a given userid
1939 function generateMemberAdminActionLinks ($userid, $status = '') {
1940 // Make sure userid is a number
1941 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1943 // Define all main targets
1944 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1946 // Begin of navigation links
1949 foreach ($targetArray as $tar) {
1950 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1951 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1952 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1953 // Locked accounts shall be unlocked
1954 $OUT .= 'UNLOCK_USER';
1956 // All other status is fine
1957 $OUT .= strtoupper($tar);
1959 $OUT .= "_TITLE--}\">{--ADMIN_";
1960 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1961 // Locked accounts shall be unlocked
1962 $OUT .= 'UNLOCK_USER';
1964 // All other status is fine
1965 $OUT .= strtoupper($tar);
1967 $OUT .= "--}</a></span> | ";
1970 // Finish navigation link
1971 $OUT = substr($OUT, 0, -7) . ']';
1977 // Generate an email link
1978 function generateEmailLink ($email, $table = 'admins') {
1979 // Default email link (INSECURE! Spammer can read this by harvester programs)
1980 $EMAIL = 'mailto:' . $email;
1982 // Check for several extensions
1983 if ((isExtensionActive('admins')) && ($table == 'admins')) {
1984 // Create email link for contacting admin in guest area
1985 $EMAIL = generateAdminEmailLink($email);
1986 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
1987 // Create email link for contacting a member within admin area (or later in other areas, too?)
1988 $EMAIL = generateUserEmailLink($email, 'admin');
1989 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1990 // Create email link to contact sponsor within admin area (or like the link above?)
1991 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
1994 // Shall I close the link when there is no admin?
1995 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
1997 // Return email link
2001 // Generate a hash for extra-security for all passwords
2002 function generateHash ($plainText, $salt = '') {
2003 // Is the required extension 'sql_patches' there and a salt is not given?
2004 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2005 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2006 return md5($plainText);
2009 // Do we miss an arry element here?
2010 if (!isConfigEntrySet('file_hash')) {
2012 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2015 // When the salt is empty build a new one, else use the first x configured characters as the salt
2017 // Build server string (inc/databases.php is no longer updated with every commit)
2018 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2021 $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');
2024 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2026 // Calculate number for generating the code
2027 $a = time() + getConfig('_ADD') - 1;
2029 // Generate SHA1 sum from modula of number and the prime number
2030 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2031 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2032 $sha1 = scrambleString($sha1);
2033 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2034 //* DEBUG: */ $sha1b = descrambleString($sha1);
2035 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2037 // Generate the password salt string
2038 $salt = substr($sha1, 0, getConfig('salt_length'));
2039 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2042 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2043 $salt = substr($salt, 0, getConfig('salt_length'));
2044 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2046 // Sanity check on salt
2047 if (strlen($salt) != getConfig('salt_length')) {
2049 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2054 return $salt.sha1($salt . $plainText);
2057 // Scramble a string
2058 function scrambleString($str) {
2062 // Final check, in case of failture it will return unscrambled string
2063 if (strlen($str) > 40) {
2064 // The string is to long
2066 } elseif (strlen($str) == 40) {
2068 $scrambleNums = explode(':', getConfig('pass_scramble'));
2070 // Generate new numbers
2071 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2074 // Scramble string here
2075 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2076 for ($idx = 0; $idx < strlen($str); $idx++) {
2077 // Get char on scrambled position
2078 $char = substr($str, $scrambleNums[$idx], 1);
2080 // Add it to final output string
2081 $scrambled .= $char;
2084 // Return scrambled string
2085 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2089 // De-scramble a string scrambled by scrambleString()
2090 function descrambleString($str) {
2091 // Scramble only 40 chars long strings
2092 if (strlen($str) != 40) return $str;
2094 // Load numbers from config
2095 $scrambleNums = explode(':', getConfig('pass_scramble'));
2098 if (count($scrambleNums) != 40) return $str;
2100 // Begin descrambling
2101 $orig = str_repeat(' ', 40);
2102 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2103 for ($idx = 0; $idx < 40; $idx++) {
2104 $char = substr($str, $idx, 1);
2105 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2108 // Return scrambled string
2109 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2113 // Generated a "string" for scrambling
2114 function genScrambleString ($len) {
2115 // Prepare array for the numbers
2116 $scrambleNumbers = array();
2118 // First we need to setup randomized numbers from 0 to 31
2119 for ($idx = 0; $idx < $len; $idx++) {
2121 $rand = mt_rand(0, ($len -1));
2123 // Check for it by creating more numbers
2124 while (array_key_exists($rand, $scrambleNumbers)) {
2125 $rand = mt_rand(0, ($len -1));
2129 $scrambleNumbers[$rand] = $rand;
2132 // So let's create the string for storing it in database
2133 $scrambleString = implode(':', $scrambleNumbers);
2134 return $scrambleString;
2137 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2138 function generatePassString ($passHash) {
2139 // Return vanilla password hash
2142 // Is a secret key and master salt already initialized?
2143 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2144 // Only calculate when the secret key is generated
2145 $newHash = ''; $start = 9;
2146 for ($idx = 0; $idx < 10; $idx++) {
2147 $part1 = hexdec(substr($passHash, $start, 4));
2148 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2149 $mod = dechex($idx);
2150 if ($part1 > $part2) {
2151 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2152 } elseif ($part2 > $part1) {
2153 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2155 $mod = substr($mod, 0, 4);
2156 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2157 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2158 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2163 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2164 $ret = generateHash($newHash, getConfig('master_salt'));
2165 //* DEBUG: */ print('ret='.$ret.'<br />');
2168 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2169 $ret = md5($passHash);
2170 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2177 // Fix "deleted" cookies
2178 function fixDeletedCookies ($cookies) {
2179 // Is this an array with entries?
2180 if ((is_array($cookies)) && (count($cookies) > 0)) {
2181 // Then check all cookies if they are marked as deleted!
2182 foreach ($cookies as $cookieName) {
2183 // Is the cookie set to "deleted"?
2184 if (getSession($cookieName) == 'deleted') {
2185 setSession($cookieName, '');
2191 // Output error messages in a fasioned way and die...
2192 function app_die ($F, $L, $message) {
2193 // Check if Script is already dieing and not let it kill itself another 1000 times
2194 if (!isset($GLOBALS['app_died'])) {
2195 // Make sure, that the script realy realy diese here and now
2196 $GLOBALS['app_died'] = true;
2199 loadIncludeOnce('inc/header.php');
2201 // Rewrite message for output
2202 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2204 // Better log this message away
2205 logDebugMessage($F, $L, $message);
2207 // Load the message template
2208 loadTemplate('admin_settings_saved', false, $message);
2211 loadIncludeOnce('inc/footer.php');
2213 // Script tried to kill itself twice
2214 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2218 // Display parsing time and number of SQL queries in footer
2219 function displayParsingTime() {
2220 // Is the timer started?
2221 if (!isset($GLOBALS['startTime'])) {
2227 $endTime = microtime(true);
2229 // "Explode" both times
2230 $start = explode(' ', $GLOBALS['startTime']);
2231 $end = explode(' ', $endTime);
2232 $runTime = $end[0] - $start[0];
2233 if ($runTime < 0) $runTime = 0;
2237 'runtime' => translateComma($runTime),
2238 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2241 // Load the template
2242 loadTemplate('show_timings', false, $content);
2245 // Check wether a boolean constant is set
2246 // Taken from user comments in PHP documentation for function constant()
2247 function isBooleanConstantAndTrue ($constName) { // : Boolean
2248 // Failed by default
2252 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2254 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2255 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2258 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2259 if (defined($constName)) {
2261 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2262 $res = (constant($constName) === true);
2266 $GLOBALS['cache_array']['const'][$constName] = $res;
2268 //* DEBUG: */ var_dump($res);
2274 // Checks if a given apache module is loaded
2275 function isApacheModuleLoaded ($apacheModule) {
2276 // Check it and return result
2277 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2280 // Get current theme name
2281 function getCurrentTheme () {
2282 // The default theme is 'default'... ;-)
2285 // Load default theme if not empty from configuration
2286 if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
2288 if (!isSessionVariableSet('mxchange_theme')) {
2289 // Set default theme
2291 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2292 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2293 // Get theme from cookie
2294 $ret = getSession('mxchange_theme');
2297 if (getThemeId($ret) == 0) {
2298 // Fix it to default
2301 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2302 // Prepare FQFN for checking
2303 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2305 // Installation mode active
2306 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2307 // Set cookie from URL data
2308 setTheme(getRequestElement('theme'));
2309 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2310 // Set cookie from posted data
2311 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2315 $ret = getSession('mxchange_theme');
2317 // Invalid design, reset cookie
2321 // Return theme value
2325 // Setter for theme in session
2326 function setTheme ($newTheme) {
2327 setSession('mxchange_theme', $newTheme);
2330 // Get id from theme
2331 // @TODO Try to move this to inc/libs/theme_functions.php
2332 function getThemeId ($name) {
2333 // Is the extension 'theme' installed?
2334 if (!isExtensionActive('theme')) {
2342 // Is the cache entry there?
2343 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2344 // Get the version from cache
2345 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2348 incrementStatsEntry('cache_hits');
2349 } elseif (getExtensionVersion('cache') != '0.1.8') {
2350 // Check if current theme is already imported or not
2351 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2352 array($name), __FUNCTION__, __LINE__);
2355 if (SQL_NUMROWS($result) == 1) {
2357 list($id) = SQL_FETCHROW($result);
2361 SQL_FREERESULT($result);
2368 // Generates an error code from given account status
2369 function generateErrorCodeFromUserStatus ($status='') {
2370 // If no status is provided, use the default, cached
2371 if ((empty($status)) && (isMember())) {
2373 $status = getUserData('status');
2376 // Default error code if unknown account status
2377 $errorCode = getCode('UNKNOWN_STATUS');
2379 // Generate constant name
2380 $constantName = sprintf("ID_%s", $status);
2382 // Is the constant there?
2383 if (isCodeSet($constantName)) {
2385 $errorCode = getCode($constantName);
2388 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2391 // Return error code
2395 // Function to search for the last modifified file
2396 function searchDirsRecursive ($dir, &$last_changed) {
2398 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2399 // Does it match what we are looking for? (We skip a lot files already!)
2400 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2401 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2402 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2403 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2405 // Walk through all entries
2406 foreach ($ds as $d) {
2407 // Generate proper FQFN
2408 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2410 // Is it a file and readable?
2411 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2412 if (isDirectory($FQFN)) {
2413 // $FQFN is a directory so also crawl into this directory
2415 if (!empty($dir)) $newDir = $dir . '/'. $d;
2416 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2417 searchDirsRecursive($newDir, $last_changed);
2418 } elseif (isFileReadable($FQFN)) {
2419 // $FQFN is a filename and no directory
2420 $time = filemtime($FQFN);
2421 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2422 if ($last_changed['time'] < $time) {
2423 // This file is newer as the file before
2424 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2425 $last_changed['path_name'] = $FQFN;
2426 $last_changed['time'] = $time;
2432 // "Getter" for revision/version data
2433 function getActualVersion ($type = 'Revision') {
2434 // By default nothing is new... ;-)
2437 // Is the cache entry there?
2438 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2439 // Found so increase cache hit
2440 incrementStatsEntry('cache_hits');
2443 return $GLOBALS['cache_array']['revision'][$type][0];
2445 // FQFN of revision file
2446 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2448 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2449 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2450 // Forced rebuild of .revision file
2453 // Check for revision file
2454 if (!isFileReadable($FQFN)) {
2455 // Not found, so we need to create it
2458 // Revision file found
2459 $ins_vers = explode("\n", readFromFile($FQFN));
2461 // Get array for mapping information
2462 $mapper = array_flip(getSearchFor());
2463 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2465 // Is the content valid?
2466 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2467 // File needs update!
2470 // Generate fake cache entry
2471 foreach ($mapper as $map=>$idx) {
2472 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2475 // Return found value
2476 return trim($ins_vers[$mapper[$type]]);
2481 // Has it been updated?
2482 if ($new === true) {
2484 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2486 // ... and call recursive
2487 return getActualVersion($type);
2492 // Repares an array we are looking for
2493 // The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
2494 function getSearchFor () {
2495 // Add Revision, Date, Tag and Author
2496 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2498 // Return the created array
2502 // @TODO Please describe this function
2503 function getArrayFromActualVersion () {
2507 // Directory to start with search
2508 $last_changed = array(
2513 // Init return array
2514 $akt_vers = array();
2516 // Init value for counting the founded keywords
2519 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2520 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2523 $last_file = readFromFile($last_changed['path_name']);
2525 // Get all the keywords to search for
2526 $searchFor = getSearchFor();
2528 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2529 foreach ($searchFor as $search) {
2530 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2531 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2532 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2533 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2536 // Save the last-changed filename for debugging
2537 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2539 // at least 3 keyword-Tags are needed for propper values
2540 if ($res && $res >= 3
2541 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2542 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2543 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2544 // Prepare content witch need special treadment
2546 // Prepare timestamp for date
2547 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2548 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2550 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2551 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2552 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2556 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2557 $version = sendGetRequest('check-updates3.php');
2560 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2561 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2562 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2563 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2564 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2565 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2568 // Return prepared array
2569 return $GLOBALS['cache_array']['revision'];
2572 // Back-ported from the new ship-simu engine. :-)
2573 function debug_get_printable_backtrace () {
2575 $backtrace = "<ol>\n";
2577 // Get and prepare backtrace for output
2578 $backtraceArray = debug_backtrace();
2579 foreach ($backtraceArray as $key => $trace) {
2580 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2581 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2582 if (!isset($trace['args'])) $trace['args'] = array();
2583 $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:" . $trace['line'].", <span class=\"backtrace_function\">" . $trace['function'].'('.count($trace['args']).")</span></li>\n";
2587 $backtrace .= "</ol>\n";
2589 // Return the backtrace
2593 // Output a debug backtrace to the user
2594 function debug_report_bug ($message = '') {
2595 // Is this already called?
2596 if (isset($GLOBALS[__FUNCTION__])) {
2598 print 'Message:'.$message.'<br />Backtrace:<pre>';
2599 debug_print_backtrace();
2603 // Set this function as called
2604 $GLOBALS[__FUNCTION__] = true;
2609 // Is the optional message set?
2610 if (!empty($message)) {
2612 $debug = sprintf("Note: %s<br />\n",
2616 // @TODO Add a little more infos here
2617 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2621 $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>";
2622 $debug .= debug_get_printable_backtrace();
2623 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2624 $debug .= "Thank you for finding bugs.";
2627 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2631 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2632 function generateSeed () {
2633 list($usec, $sec) = explode(' ', microtime());
2634 $microTime = (((float)$sec + (float)$usec)) * 100000;
2638 // Converts a message code to a human-readable message
2639 function getMessageFromErrorCode ($code) {
2643 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2644 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2645 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2646 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2647 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2648 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2649 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2650 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2651 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2652 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2653 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2654 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2655 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2656 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2657 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2658 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2659 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2660 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2661 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2662 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2663 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2664 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2665 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2666 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2667 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2668 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2669 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2670 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2672 case getCode('ERROR_MAILID'):
2673 if (isExtensionActive('mailid', true)) {
2674 $message = getMessage('ERROR_CONFIRMING_MAIL');
2676 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2680 case getCode('EXTENSION_PROBLEM'):
2681 if (isGetRequestElementSet('ext')) {
2682 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2684 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2688 case getCode('URL_TLOCK'):
2689 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2690 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2692 // Load timestamp from last order
2693 list($timestamp) = SQL_FETCHROW($result);
2694 $timestamp = generateDateTime($timestamp, 1);
2697 SQL_FREERESULT($result);
2699 // Calculate hours...
2700 $STD = round(getConfig('url_tlock') / 60 / 60);
2703 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2706 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2708 // Finally contruct the message
2709 // @TODO Rewrite this old lost code to a template
2710 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2711 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2712 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2716 // Missing/invalid code
2717 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2720 logDebugMessage(__FUNCTION__, __LINE__, $message);
2724 // Return the message
2728 // Generate a "link" for the given admin id (admin_id)
2729 function generateAdminLink ($adminId) {
2730 // No assigned admin is default
2731 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2733 // Zero? = Not assigned
2734 if (bigintval($adminId) > 0) {
2735 // Load admin's login
2736 $login = getAdminLogin($adminId);
2738 // Is the login valid?
2739 if ($login != '***') {
2740 // Is the extension there?
2741 if (isExtensionActive('admins')) {
2743 $admin = "<a href=\"".generateEmailLink(getAdminEmail($adminId), 'admins')."\">" . $login."</a>";
2745 // Extension not found
2746 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2750 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $adminId)."</div>";
2758 // Compile characters which are allowed in URLs
2759 function compileUriCode ($code, $simple = true) {
2760 // Compile constants
2761 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2763 // Compile QUOT and other non-HTML codes
2764 $code = str_replace('{DOT}', '.',
2765 str_replace('{SLASH}', '/',
2766 str_replace('{QUOT}', "'",
2767 str_replace('{DOLLAR}', '$',
2768 str_replace('{OPEN_ANCHOR}', '(',
2769 str_replace('{CLOSE_ANCHOR}', ')',
2770 str_replace('{OPEN_SQR}', '[',
2771 str_replace('{CLOSE_SQR}', ']',
2772 str_replace('{PER}', '%',
2776 // Return compiled code
2780 // Function taken from user comments on www.php.net / function eregi()
2781 function isUrlValidSimple ($url) {
2783 $url = secureString(str_replace("\\", '', compileCode(urldecode($url))));
2785 // Allows http and https
2786 $http = "(http|https)+(:\/\/)";
2788 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2789 // Test double-domains (e.g. .de.vu)
2790 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2792 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2794 $dir = "((/)+([-_\.[:alnum:]])+)*";
2796 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2797 // ... and the string after and including question character
2798 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2799 // Pattern for URLs like http://url/dir/doc.html?var=value
2800 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2801 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2802 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2803 // Pattern for URLs like http://url/dir/?var=value
2804 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2805 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2806 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2807 // Pattern for URLs like http://url/dir/page.ext
2808 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2809 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2810 $pattern['ipdp'] = $http . $ip . $dir . $page;
2811 // Pattern for URLs like http://url/dir
2812 $pattern['d1d'] = $http . $domain1 . $dir;
2813 $pattern['d2d'] = $http . $domain2 . $dir;
2814 $pattern['ipd'] = $http . $ip . $dir;
2815 // Pattern for URLs like http://url/?var=value
2816 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2817 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2818 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2819 // Pattern for URLs like http://url?var=value
2820 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2821 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2822 $pattern['ipg12'] = $http . $ip . $getstring1;
2823 // Test all patterns
2825 foreach ($pattern as $key => $pat) {
2827 if (isDebugRegExpressionEnabled()) {
2828 // @TODO Are these convertions still required?
2829 $pat = str_replace('.', "\.", $pat);
2830 $pat = str_replace('@', "\@", $pat);
2831 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2834 // Check if expression matches
2835 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2838 if ($reg === true) break;
2841 // Return true/false
2845 // Wtites data to a config.php-style file
2846 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2847 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2848 // Initialize some variables
2854 // Is the file there and read-/write-able?
2855 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2856 $search = 'CFG: ' . $comment;
2857 $tmp = $FQFN . '.tmp';
2859 // Open the source file
2860 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2862 // Is the resource valid?
2863 if (is_resource($fp)) {
2864 // Open temporary file
2865 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2867 // Is the resource again valid?
2868 if (is_resource($fp_tmp)) {
2869 // Mark temporary file as readable
2870 $GLOBALS['file_readable'][$tmp] = true;
2873 while (!feof($fp)) {
2874 // Read from source file
2875 $line = fgets ($fp, 1024);
2877 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2880 if ($next === $seek) {
2882 $line = $prefix . $DATA . $suffix . "\n";
2888 // Write to temp file
2889 fputs($fp_tmp, $line);
2895 // Finished writing tmp file
2899 // Close source file
2902 if (($done === true) && ($found === true)) {
2903 // Copy back tmp file and delete tmp :-)
2904 copyFileVerified($tmp, $FQFN, 0644);
2905 return removeFile($tmp);
2906 } elseif ($found === false) {
2907 outputHtml('<strong>CHANGE:</strong> 404!');
2909 outputHtml('<strong>TMP:</strong> UNDONE!');
2913 // File not found, not readable or writeable
2914 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2917 // An error was detected!
2920 // Send notification to admin
2921 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = 0) {
2922 if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
2924 sendAdminsEmails($subject, $templateName, $content, $userid);
2926 // Send out out-dated way
2927 $message = loadEmailTemplate($templateName, $content, $userid);
2928 sendAdminEmails($subject, $message);
2932 // Debug message logger
2933 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2934 // Is debug mode enabled?
2935 if ((isDebugModeEnabled()) || ($force === true)) {
2937 $message = str_replace("\r", '', str_replace("\n", '', $message));
2939 // Log this message away, we better don't call app_die() here to prevent an endless loop
2940 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2941 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2946 // Handle extra values
2947 function handleExtraValues ($filterFunction, $value, $extraValue) {
2948 // Default is the value itself
2951 // Do we have a special filter function?
2952 if (!empty($filterFunction)) {
2953 // Does the filter function exist?
2954 if (function_exists($filterFunction)) {
2955 // Do we have extra parameters here?
2956 if (!empty($extraValue)) {
2957 // Put both parameters in one new array by default
2958 $args = array($value, $extraValue);
2960 // If we have an array simply use it and pre-extend it with our value
2961 if (is_array($extraValue)) {
2962 // Make the new args array
2963 $args = merge_array(array($value), $extraValue);
2966 // Call the multi-parameter call-back
2967 $ret = call_user_func_array($filterFunction, $args);
2969 // One parameter call
2970 $ret = call_user_func($filterFunction, $value);
2979 // Converts timestamp selections into a timestamp
2980 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2981 // Init test variable
2985 // Get last three chars
2986 $test = substr($id, -3);
2988 // Improved way of checking! :-)
2989 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2990 // Found a multi-selection for timings?
2991 $test = substr($id, 0, -3);
2992 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)) {
2993 // Generate timestamp
2994 $postData[$test] = createTimestampFromSelections($test, $postData);
2995 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2996 $GLOBALS['skip_config'][$test] = true;
2998 // Remove data from array
2999 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3000 unset($postData[$test . '_' . $rem]);
3011 // Reverts the german decimal comma into Computer decimal dot
3012 function convertCommaToDot ($str) {
3013 // Default float is not a float... ;-)
3016 // Which language is selected?
3017 switch (getLanguage()) {
3018 case 'de': // German language
3019 // Remove german thousand dots first
3020 $str = str_replace('.', '', $str);
3022 // Replace german commata with decimal dot and cast it
3023 $float = (float)str_replace(',', '.', $str);
3026 default: // US and so on
3027 // Remove thousand dots first and cast
3028 $float = (float)str_replace(',', '', $str);
3036 // Handle menu-depending failed logins and return the rendered content
3037 function handleLoginFailtures ($accessLevel) {
3038 // Default output is empty ;-)
3041 // Is the session data set?
3042 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3043 // Ignore zero values
3044 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3045 // Non-guest has login failures found, get both data and prepare it for template
3046 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3048 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3049 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3053 $OUT = loadTemplate('login_failures', true, $content);
3056 // Reset session data
3057 setSession('mxchange_' . $accessLevel.'_failures', '');
3058 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3061 // Return rendered content
3066 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3068 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3070 // Shall I remove the cache file?
3071 if (isCacheInstanceValid()) {
3073 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3075 $GLOBALS['cache_instance']->removeCacheFile($force);
3078 // Include file given?
3081 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3083 // Is the include there?
3084 if (isIncludeReadable($inc)) {
3085 // And rebuild it from scratch
3086 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3089 // Include not found!
3090 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3096 // Determines the real remote address
3097 function determineRealRemoteAddress () {
3098 // Is a proxy in use?
3099 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3101 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3102 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3103 // Yet, another proxy
3104 $address = $_SERVER['HTTP_CLIENT_IP'];
3106 // The regular address when no proxy was used
3107 $address = $_SERVER['REMOTE_ADDR'];
3110 // This strips out the real address from proxy output
3111 if (strstr($address, ',')) {
3112 $addressArray = explode(',', $address);
3113 $address = $addressArray[0];
3116 // Return the result
3120 // Adds a bonus mail to the queue
3121 // This is a high-level function!
3122 function addNewBonusMail ($data, $mode = '', $output=true) {
3123 // Use mode from data if not set and availble ;-)
3124 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3126 // Generate receiver list
3127 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3130 if (!empty($RECEIVER)) {
3131 // Add bonus mail to queue
3132 addBonusMailToQueue(
3144 // Mail inserted into bonus pool
3145 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3146 } elseif ($output) {
3147 // More entered than can be reached!
3148 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3151 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3155 // Determines referal id and sets it
3156 function determineReferalId () {
3157 // Skip this in non-html-mode and outside ref.php
3158 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3160 // Check if refid is set
3161 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3163 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3164 // The variable user comes from the click-counter script click.php and we only accept this here
3165 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3166 } elseif (isPostRequestElementSet('refid')) {
3167 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3168 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3169 } elseif (isGetRequestElementSet('refid')) {
3170 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3171 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3172 } elseif (isGetRequestElementSet('ref')) {
3173 // Set refid=ref (the referal link uses such variable)
3174 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3175 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3176 // Set session refid als global
3177 $GLOBALS['refid'] = bigintval(getSession('refid'));
3178 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3179 // Select a random user which has confirmed enougth mails
3180 $GLOBALS['refid'] = determineRandomReferalId();
3181 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3182 // Set default refid as refid in URL
3183 $GLOBALS['refid'] = getConfig('def_refid');
3185 // No default id when sql_patches is not installed or none set
3186 $GLOBALS['refid'] = 0;
3189 // Set cookie when default refid > 0
3190 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == 0) && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3191 // Default is not found
3194 // Do we have nickname or userid set?
3195 if (isNicknameUsed($GLOBALS['refid'])) {
3196 // Nickname in URL, so load the id
3197 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3198 } elseif ($GLOBALS['refid'] > 0) {
3199 // Direct userid entered
3200 $found = fetchUserData($GLOBALS['refid']);
3203 // Is the record valid?
3204 if (($found === false) || (!isUserDataValid())) {
3205 // No, then reset referal id
3206 $GLOBALS['refid'] = getConfig('def_refid');
3210 setSession('refid', $GLOBALS['refid']);
3213 // Return determined refid
3214 return $GLOBALS['refid'];
3217 // Enables the reset mode and runs it
3218 function doReset () {
3219 // Enable the reset mode
3220 $GLOBALS['reset_enabled'] = true;
3223 runFilterChain('reset');
3226 // Our shutdown-function
3227 function shutdown () {
3228 // Call the filter chain 'shutdown'
3229 runFilterChain('shutdown', null);
3231 if (SQL_IS_LINK_UP()) {
3233 SQL_CLOSE(__FILE__, __LINE__);
3234 } elseif (!isInstallationPhase()) {
3236 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3239 // Stop executing here
3243 // Setter for userid
3244 function setUserId ($userid) {
3245 // We should not set userid to zero
3246 if ($userid == 0) debug_report_bug('Userid should not be set zero.');
3249 $GLOBALS['userid'] = bigintval($userid);
3252 // Getter for userid or returns zero
3253 function getUserId () {
3257 // Is the userid set?
3258 if (isUserIdSet()) {
3260 $userid = $GLOBALS['userid'];
3267 // Checks ether the userid is set
3268 function isUserIdSet () {
3269 return (isset($GLOBALS['userid']));
3272 // Handle message codes from URL
3273 function handleCodeMessage () {
3274 if (isGetRequestElementSet('code')) {
3275 // Default extension is 'unknown'
3278 // Is extension given?
3279 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3281 // Convert the 'code' parameter from URL to a human-readable message
3282 $message = getMessageFromErrorCode(getRequestElement('code'));
3284 // Load message template
3285 loadTemplate('message', false, $message);
3289 // Setter for extra title
3290 function setExtraTitle ($extraTitle) {
3291 $GLOBALS['extra_title'] = $extraTitle;
3294 // Getter for extra title
3295 function getExtraTitle () {
3296 // Is the extra title set?
3297 if (!isExtraTitleSet()) {
3298 // No, then abort here
3299 debug_report_bug('extra_title is not set!');
3303 return $GLOBALS['extra_title'];
3306 // Checks if the extra title is set
3307 function isExtraTitleSet () {
3308 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3311 // Generates a 'extension foo inactive' message
3312 function generateExtensionInactiveMessage ($ext_name) {
3313 // Is the extension empty?
3314 if (empty($ext_name)) {
3315 // This should not happen
3316 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3320 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3322 // Is an admin logged in?
3324 // Then output admin message
3325 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3328 // Return prepared message
3332 // Generates a 'extension foo not installed' message
3333 function generateExtensionNotInstalledMessage ($ext_name) {
3334 // Is the extension empty?
3335 if (empty($ext_name)) {
3336 // This should not happen
3337 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3341 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3343 // Is an admin logged in?
3345 // Then output admin message
3346 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3349 // Return prepared message
3353 // Generates a message depending on if the extension is not installed or not
3355 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3359 // Is the extension not installed or just deactivated?
3360 switch (isExtensionInstalled($ext_name)) {
3361 case true; // Deactivated!
3362 $message = generateExtensionInactiveMessage($ext_name);
3365 case false; // Not installed!
3366 $message = generateExtensionNotInstalledMessage($ext_name);
3369 default: // Should not happen!
3370 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3371 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3375 // Return the message
3379 // Reads a directory recursively by default and searches for files not matching
3380 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3381 // a whole directory.
3382 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3383 // Add default entries we should exclude
3384 $excludeArray[] = '.';
3385 $excludeArray[] = '..';
3386 $excludeArray[] = '.svn';
3387 $excludeArray[] = '.htaccess';
3389 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3394 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3397 while ($baseFile = readdir($dirPointer)) {
3398 // Exclude '.', '..' and entries in $excludeArray automatically
3399 if (in_array($baseFile, $excludeArray, true)) {
3401 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3405 // Construct include filename and FQFN
3406 $fileName = $baseDir . $baseFile;
3407 $FQFN = getConfig('PATH') . $fileName;
3409 // Remove double slashes
3410 $FQFN = str_replace('//', '/', $FQFN);
3412 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3413 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3414 // These Lines are only for debugging!!
3415 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3416 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3417 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3423 // Skip also files with non-matching prefix genericly
3424 if (($recursive === true) && (isDirectory($FQFN))) {
3425 // Is a redirectory so read it as well
3426 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3428 // And skip further processing
3430 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3432 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3434 } elseif (!isFileReadable($FQFN)) {
3435 // Not readable so skip it
3436 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3440 // Is the file a PHP script or other?
3441 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3442 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3443 // Is this a valid include file?
3444 if ($extension == '.php') {
3445 // Remove both for extension name
3446 $extName = substr($baseFile, strlen($prefix), -4);
3448 // Is the extension valid and active?
3449 if (isExtensionNameValid($extName)) {
3450 // Then add this file
3451 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3452 $files[] = $fileName;
3454 // Add non-extension files as well
3455 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3456 if ($addBaseDir === true) {
3457 $files[] = $fileName;
3459 $files[] = $baseFile;
3463 // We found .php file but should not search for them, why?
3464 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3466 } elseif (substr($baseFile, -4, 4) == $extension) {
3467 // Other, generic file found
3468 $files[] = $fileName;
3473 closedir($dirPointer);
3478 // Return array with include files
3479 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3483 // Maps a module name into a database table name
3484 function mapModuleToTable ($moduleName) {
3485 // Map only these, still lame code...
3486 switch ($moduleName) {
3487 // 'index' is the guest's menu
3488 case 'index': $moduleName = 'guest'; break;
3489 // ... and 'login' the member's menu
3490 case 'login': $moduleName = 'member'; break;
3491 // Anything else will not be mapped, silently.
3498 // Add SQL debug data to array for later output
3499 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3500 // Already executed?
3501 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3502 // Then abort here, we don't need to profile a query twice
3506 // Remeber this as profiled (or not, but we don't care here)
3507 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3509 // Do we have cache?
3510 if (!isset($GLOBALS['debug_sql_available'])) {
3511 // Check it and cache it in $GLOBALS
3512 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3515 // Don't execute anything here if we don't need or ext-other is missing
3516 if ($GLOBALS['debug_sql_available'] === false) {
3522 'num_rows' => SQL_NUMROWS($result),
3523 'affected' => SQL_AFFECTEDROWS(),
3524 'sql_str' => $sqlString,
3525 'timing' => $timing,
3526 'file' => basename($F),
3531 $GLOBALS['debug_sqls'][] = $record;
3534 // Initializes the cache instance
3535 function initCacheInstance () {
3536 // Load include for CacheSystem class
3537 loadIncludeOnce('inc/classes/cachesystem.class.php');
3539 // Initialize cache system only when it's needed
3540 $GLOBALS['cache_instance'] = new CacheSystem();
3541 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3542 // Failed to initialize cache sustem
3543 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3547 // Getter for message from array or raw message
3548 function getMessageFromIndexedArray ($message, $pos, $array) {
3549 // Check if the requested message was found in array
3550 if (isset($array[$pos])) {
3551 // ... if yes then use it!
3552 $ret = $array[$pos];
3554 // ... else use default message
3562 // Print code with line numbers
3563 function linenumberCode ($code) {
3564 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3565 $count_lines = count($codeE);
3567 $r = 'Line | Code:<br />';
3568 foreach($codeE as $line => $c) {
3569 $r .= '<div class="line"><span class="linenum">';
3570 if ($count_lines == 1) {
3573 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3578 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3581 return '<div class="code">' . $r . '</div>';
3584 // Convert ';' to ', ' for e.g. receiver list
3585 function convertReceivers ($old) {
3586 return str_replace(';', ', ', $old);
3589 // Determines the right page title
3590 function determinePageTitle () {
3591 // Config and database connection valid?
3592 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3596 // Title decoration enabled?
3597 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
3599 // Do we have some extra title?
3600 if (isExtraTitleSet()) {
3602 $TITLE .= getExtraTitle() . ' by ';
3606 $TITLE .= getConfig('MAIN_TITLE');
3608 // Add title of module? (middle decoration will also be added!)
3609 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3610 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3613 // Add title from what file
3615 if (getModule() == 'login') $mode = 'member';
3616 elseif (getModule() == 'index') $mode = 'guest';
3617 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= " ".trim(getConfig('title_middle'))." ".getModuleDescription($mode, getWhat());
3619 // Add title decorations? (right)
3620 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= " ".trim(getConfig('title_right'));
3622 // Remember title in constant for the template
3623 $pageTitle = $TITLE;
3624 } elseif ((isInstalled()) && (isAdminRegistered())) {
3625 // Installed, admin registered but no ext-sql_patches
3626 $pageTitle = '[-- ' . getConfig('MAIN_TITLE').' - '.getModuleTitle(getModule()) . ' --]';
3627 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3628 // Installed but no admin registered
3629 $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
3630 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3631 // Installation mode
3632 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3634 // Configuration not found!
3635 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3637 // Do not add the fatal message in installation mode
3638 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3645 //////////////////////////////////////////////////
3646 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3647 //////////////////////////////////////////////////
3649 if (!function_exists('html_entity_decode')) {
3650 // Taken from documentation on www.php.net
3651 function html_entity_decode ($string) {
3652 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3653 $trans_tbl = array_flip($trans_tbl);
3654 return strtr($string, $trans_tbl);
3658 if (!function_exists('http_build_query')) {
3659 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3660 function http_build_query($data, $prefix='', $sep='', $key='') {
3662 foreach ((array)$data as $k => $v) {
3663 if (is_int($k) && $prefix != null) {
3664 $k = urlencode($prefix . $k);
3667 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3669 if (is_array($v) || is_object($v)) {
3670 array_push($ret, http_build_query($v, '', $sep, $k));
3672 array_push($ret, $k.'='.urlencode($v));
3676 if (empty($sep)) $sep = ini_get('arg_separator.output');
3678 return implode($sep, $ret);