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 if (!isset($GLOBALS['output'])) $GLOBALS['output'] = '';
50 $username = getMessage('USERNAME_UNKNOWN');
51 if (isset($GLOBALS['username'])) $username = getUsername();
53 // Do we have HTML-Code here?
54 if (!empty($htmlCode)) {
55 // Yes, so we handle it as you have configured
56 switch (getConfig('OUTPUT_MODE')) {
58 // That's why you don't need any \n at the end of your HTML code... :-)
59 if (getPhpCaching() == 'on') {
60 // Output into PHP's internal buffer
61 outputRawCode($htmlCode);
63 // That's why you don't need any \n at the end of your HTML code... :-)
64 if ($newLine === true) print("\n");
66 // Render mode for old or lame servers...
67 $GLOBALS['output'] .= $htmlCode;
69 // That's why you don't need any \n at the end of your HTML code... :-)
70 if ($newLine === true) $GLOBALS['output'] .= "\n";
75 // If we are switching from render to direct output rendered code
76 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
78 // The same as above... ^
79 outputRawCode($htmlCode);
80 if ($newLine) print("\n");
84 // Huh, something goes wrong or maybe you have edited config.php ???
85 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
88 } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
89 // Headers already sent?
92 logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
94 // Trigger an user error
95 debug_report_bug('Headers are already sent!');
98 // Output cached HTML code
99 $GLOBALS['output'] = ob_get_contents();
101 // Clear output buffer for later output if output is found
102 if (!empty($GLOBALS['output'])) {
107 sendHeader('HTTP/1.1 200');
110 $now = gmdate('D, d M Y H:i:s') . ' GMT';
112 // General headers for no caching
113 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
114 sendHeader('Last-Modified: ' . $now);
115 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
116 sendHeader('Pragma: no-cache'); // HTTP/1.0
117 sendHeader('Connection: Close');
118 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
119 sendHeader('Content-language: ' . getLanguage());
121 // Extension 'rewrite' installed?
122 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
123 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
129 // Compile and run finished rendered HTML code
130 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
131 // Prepare the content and eval() it...
136 $eval = "\$newContent = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";";
139 // Was that eval okay?
140 if (empty($newContent)) {
141 // Something went wrong!
142 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>');
144 $GLOBALS['output'] = $newContent;
150 // Output code here, DO NOT REMOVE! ;-)
151 outputRawCode($GLOBALS['output']);
152 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
153 // Rewrite links when rewrite extension is active
154 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
155 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
158 // Compile and run finished rendered HTML code
159 while (strpos($GLOBALS['output'], '{!') > 0) {
160 eval("\$GLOBALS['output'] = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";");
163 // Output code here, DO NOT REMOVE! ;-)
164 outputRawCode($GLOBALS['output']);
168 // Output the raw HTML code
169 function outputRawCode ($htmlCode) {
170 // Output stripped HTML code to avoid broken JavaScript code, etc.
171 print(stripslashes(stripslashes($htmlCode)));
173 // Flush the output if only getPhpCaching() is not 'on'
174 if (getPhpCaching() != 'on') {
180 // Init fatal message array
181 function initFatalMessages () {
182 $GLOBALS['fatal_messages'] = array();
185 // Getter for whole fatal error messages
186 function getFatalArray () {
187 return $GLOBALS['fatal_messages'];
190 // Add a fatal error message to the queue array
191 function addFatalMessage ($F, $L, $message, $extra='') {
192 if (is_array($extra)) {
193 // Multiple extras for a message with masks
194 $message = call_user_func_array('sprintf', $extra);
195 } elseif (!empty($extra)) {
196 // $message is text with a mask plus extras to insert into the text
197 $message = sprintf($message, $extra);
200 // Add message to $GLOBALS['fatal_messages']
201 $GLOBALS['fatal_messages'][] = $message;
203 // Log fatal messages away
204 debug_report_bug($message);
205 logDebugMessage($F, $L, " message={$message}");
208 // Getter for total fatal message count
209 function getTotalFatalErrors () {
213 // Do we have at least the first entry?
214 if (!empty($GLOBALS['fatal_messages'][0])) {
216 $count = count($GLOBALS['fatal_messages']);
223 // Load a template file and return it's content (only it's name; do not use ' or ")
224 function loadTemplate ($template, $return=false, $content=array()) {
225 // @TODO Remove this sanity-check if all is fine
226 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
228 // @TODO Try to rewrite all $DATA to $content
232 if (isTemplateCached($template)) {
233 // Evaluate the cache
234 eval(readTemplateCache($template));
235 } elseif (!isset($GLOBALS['template_eval'][$template])) {
236 // Add more variables which you want to use in your template files
237 $username = getUsername();
239 // Make all template names lowercase
240 $template = strtolower($template);
242 // Count the template load
243 incrementConfigEntry('num_templates');
247 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
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($ret)) . '";';
334 } elseif (substr($template, 0, 3) == 'js_') {
335 // JavaScripts don't like entities
336 $eval = '$ret = decodeEntities("' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '");';
338 // Prepare eval() command
339 $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
342 // Add surrounding HTML comments to help finding bugs faster
343 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
344 $eval = '$ret = "' . smartAddSlashes($ret) . '";';
347 // Cache the eval() command here
348 $GLOBALS['template_eval'][$template] = $eval;
351 eval($GLOBALS['template_eval'][$template]);
352 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
353 // Only admins shall see this warning or when installation mode is active
354 $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
355 (' . $template . ')<br />
357 {--TEMPLATE_CONTENT--}
358 <pre>' . print_r($content, true) . '</pre>
360 <pre>' . print_r($DATA, true) . '</pre>
364 $GLOBALS['template_eval'][$template] = '404';
368 eval($GLOBALS['template_eval'][$template]);
371 // Do we have some content to output or return?
373 // Not empty so let's put it out! ;)
374 if ($return === true) {
375 // Return the HTML code
381 } elseif (isDebugModeEnabled()) {
382 // Warning, empty output!
383 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
387 // Loads an email template and compiles it
388 function loadEmailTemplate ($template, $content = array(), $UID = '0') {
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 = "' . compileRawCode(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(\"".compileRawCode(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 = \"".compileRawCode(smartAddSlashes($toEmail))."\";");
593 eval("\$message = \"".compileRawCode(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 = "' . compileRawCode($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
1003 $startCompile = explode(' ', microtime());
1006 $code = compileRawCode($code, $simple, $constants, $full);
1009 $compiled = explode(' ', microtime());
1012 $code .= '<!-- Compilation time: ' . ((($compiled[1] + $compiled[0]) - ($startCompile[1] + $startCompile[0])) * 1000). 'ms //-->';
1014 // Return compiled code
1018 // Compiles the code (use compileCode() only for HTML because of the comments)
1019 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1020 // Is the code a string?
1021 if (!is_string($code)) {
1022 // Silently return it
1026 // Init replacement-array with full security characters
1027 $secChars = $GLOBALS['security_chars'];
1029 // Select smaller set of chars to replace when we e.g. want to compile URLs
1030 if ($full === false) $secChars = $GLOBALS['url_chars'];
1032 // Compile more through a filter
1033 $code = runFilterChain('compile_code', $code);
1035 // Compile constants
1036 if ($constants === true) {
1037 // BEFORE 0.2.1 : Language and data constants
1038 // WITH 0.2.1+ : Only language constants
1039 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1041 // BEFORE 0.2.1 : Not used
1042 // WITH 0.2.1+ : Data constants
1043 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1046 // Compile QUOT and other non-HTML codes
1047 foreach ($secChars['to'] as $k => $to) {
1048 // Do the reversed thing as in inc/libs/security_functions.php
1049 $code = str_replace($to, $secChars['from'][$k], $code);
1052 // But shall I keep simple quotes for later use?
1053 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1055 // Find $content[bla][blub] entries
1056 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1058 // Are some matches found?
1059 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1060 // Replace all matches
1061 $matchesFound = array();
1062 foreach ($matches[0] as $key => $match) {
1063 // Fuzzy look has failed by default
1064 $fuzzyFound = false;
1066 // Fuzzy look on match if already found
1067 foreach ($matchesFound as $found => $set) {
1069 $test = substr($found, 0, strlen($match));
1071 // Does this entry exist?
1072 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1073 if ($test == $match) {
1075 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1082 if ($fuzzyFound === true) continue;
1084 // Take all string elements
1085 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1086 // Replace it in the code
1087 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1088 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1089 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1090 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1091 $matchesFound[$match] = 1;
1092 } elseif (!isset($matchesFound[$match])) {
1093 // Not yet replaced!
1094 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1095 $code = str_replace($match, "\"." . $match.".\"", $code);
1096 $matchesFound[$match] = 1;
1105 /************************************************************************
1107 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1108 * $a_sort sortiert: *
1110 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1111 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1112 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1113 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1114 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1116 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1117 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1118 * Sie, dass es doch nicht so schwer ist! :-) *
1120 ************************************************************************/
1121 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1123 while ($primary_key < count($a_sort)) {
1124 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1125 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1127 if ($nums === false) {
1128 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1129 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1130 } elseif ($key != $key2) {
1131 // Sort numbers (E.g.: 9 < 10)
1132 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1133 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1137 // We have found two different values, so let's sort whole array
1138 foreach ($dummy as $sort_key => $sort_val) {
1139 $t = $dummy[$sort_key][$key];
1140 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1141 $dummy[$sort_key][$key2] = $t;
1152 // Write back sorted array
1157 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1160 if ($type == 'yn') {
1161 // This is a yes/no selection only!
1162 if ($id > 0) $prefix .= "[" . $id."]";
1163 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1165 // Begin with regular selection box here
1166 if (!empty($prefix)) $prefix .= "_";
1168 if ($id > 0) $type2 .= "[" . $id."]";
1169 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1174 for ($idx = 1; $idx < 32; $idx++) {
1175 $OUT .= "<option value=\"" . $idx."\"";
1176 if ($default == $idx) $OUT .= ' selected="selected"';
1177 $OUT .= ">" . $idx."</option>\n";
1181 case 'month': // Month
1182 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1183 $OUT .= "<option value=\"" . $month."\"";
1184 if ($default == $month) $OUT .= ' selected="selected"';
1185 $OUT .= ">" . $descr."</option>\n";
1189 case 'year': // Year
1191 $year = date('Y', time());
1193 // Use configured min age or fixed?
1194 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1196 $startYear = $year - getConfig('min_age');
1199 $startYear = $year - 16;
1202 // Calculate earliest year (100 years old people can still enter Internet???)
1203 $minYear = $year - 100;
1205 // Check if the default value is larger than minimum and bigger than actual year
1206 if (($default > $minYear) && ($default >= $year)) {
1207 for ($idx = $year; $idx < ($year + 11); $idx++) {
1208 $OUT .= "<option value=\"" . $idx."\"";
1209 if ($default == $idx) $OUT .= ' selected="selected"';
1210 $OUT .= ">" . $idx."</option>\n";
1212 } elseif ($default == -1) {
1213 // Current year minus 1
1214 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1216 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1219 // Get current year and subtract the configured minimum age
1220 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1221 // Calculate earliest year depending on extension version
1222 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1223 // Use configured minimum age
1224 $year = date('Y', time()) - getConfig('min_age');
1226 // Use fixed 16 years age
1227 $year = date('Y', time()) - 16;
1230 // Construct year selection list
1231 for ($idx = $minYear; $idx <= $year; $idx++) {
1232 $OUT .= "<option value=\"" . $idx."\"";
1233 if ($default == $idx) $OUT .= ' selected="selected"';
1234 $OUT .= ">" . $idx."</option>\n";
1241 for ($idx = '0'; $idx < 60; $idx+=5) {
1242 if (strlen($idx) == 1) $idx = '0' . $idx;
1243 $OUT .= "<option value=\"" . $idx."\"";
1244 if ($default == $idx) $OUT .= ' selected="selected"';
1245 $OUT .= ">" . $idx."</option>\n";
1250 for ($idx = '0'; $idx < 24; $idx++) {
1251 if (strlen($idx) == 1) $idx = '0' . $idx;
1252 $OUT .= "<option value=\"" . $idx."\"";
1253 if ($default == $idx) $OUT .= ' selected="selected"';
1254 $OUT .= ">" . $idx."</option>\n";
1259 $OUT .= "<option value=\"Y\"";
1260 if ($default == 'Y') $OUT .= ' selected="selected"';
1261 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1262 if ($default != 'Y') $OUT .= ' selected="selected"';
1263 $OUT .= ">{--NO--}</option>\n";
1266 $OUT .= " </select>\n";
1271 // Deprecated : $length
1274 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1275 // Build server string
1276 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1279 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1280 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1281 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1282 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1283 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1285 // Build string from misc data
1286 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1288 // Add more additional data
1289 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1291 // Add referal id, language, theme and userid
1292 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1293 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1294 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1295 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1297 // Calculate number for generating the code
1298 $a = $code + getConfig('_ADD') - 1;
1300 if (isConfigEntrySet('master_salt')) {
1301 // Generate hash with master salt from modula of number with the prime number and other data
1302 $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'));
1304 // Create number from hash
1305 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1307 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1308 $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')));
1310 // Create number from hash
1311 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1314 // At least 10 numbers shall be secure enought!
1315 $len = getConfig('code_length');
1316 if ($len == '0') $len = $length;
1317 if ($len == '0') $len = 10;
1319 // Cut off requested counts of number
1320 $return = substr(str_replace('.', '', $rcode), 0, $len);
1322 // Done building code
1326 // Does only allow numbers
1327 function bigintval ($num, $castValue = true) {
1328 // Filter all numbers out
1329 $ret = preg_replace('/[^0123456789]/', '', $num);
1332 if ($castValue === true) $ret = (double)$ret;
1334 // Has the whole value changed?
1335 if ('' . $ret . '' != '' . $num . '') {
1337 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1344 // Insert the code in $img_code into jpeg or PNG image
1345 function generateImageOrCode ($img_code, $headerSent = true) {
1346 // Is the code size oversized or shouldn't we display it?
1347 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1348 // Stop execution of function here because of over-sized code length
1349 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1350 } elseif ($headerSent === false) {
1351 // Return an HTML code here
1352 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1356 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1359 getConfig('img_type')
1363 if (isFileReadable($img)) {
1364 // Switch image type
1365 switch (getConfig('img_type'))
1368 // Okay, load image and hide all errors
1369 $image = imagecreatefromjpeg($img);
1373 // Okay, load image and hide all errors
1374 $image = imagecreatefrompng($img);
1378 // Exit function here
1379 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1383 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1384 $text_color = imagecolorallocate($image, 0, 0, 0);
1386 // Insert code into image
1387 imagestring($image, 5, 14, 2, $img_code, $text_color);
1389 // Return to browser
1390 sendHeader('Content-Type: image/' . getConfig('img_type'));
1392 // Output image with matching image factory
1393 switch (getConfig('img_type')) {
1394 case 'jpg': imagejpeg($image); break;
1395 case 'png': imagepng($image); break;
1398 // Remove image from memory
1399 imagedestroy($image);
1401 // Create selection box or array of splitted timestamp
1402 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1403 // Calculate 2-seconds timestamp
1404 $stamp = round($timestamp);
1405 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1407 // Do we have a leap year?
1409 $TEST = date('Y', time()) / 4;
1410 $M1 = date('m', time());
1411 $M2 = date('m', (time() + $timestamp));
1413 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1414 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1416 // First of all years...
1417 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1418 //* DEBUG: */ print("Y={$Y}<br />");
1420 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1421 //* DEBUG: */ print("M={$M}<br />");
1423 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1424 //* DEBUG: */ print("W={$W}<br />");
1426 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1427 //* DEBUG: */ print("D={$D}<br />");
1429 $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));
1430 //* DEBUG: */ print("h={$h}<br />");
1432 $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));
1433 //* DEBUG: */ print("m={$m}<br />");
1434 // And at last seconds...
1435 $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));
1436 //* DEBUG: */ print("s={$s}<br />");
1438 // Is seconds zero and time is < 60 seconds?
1439 if (($s == '0') && ($timestamp < 60)) {
1441 $s = round($timestamp);
1445 // Now we convert them in seconds...
1447 if ($return_array) {
1448 // Just put all data in an array for later use
1460 $OUT = "<div align=\"" . $align."\">\n";
1461 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1464 if (ereg('Y', $display) || (empty($display))) {
1465 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1468 if (ereg('M', $display) || (empty($display))) {
1469 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1472 if (ereg("W", $display) || (empty($display))) {
1473 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1476 if (ereg("D", $display) || (empty($display))) {
1477 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1480 if (ereg("h", $display) || (empty($display))) {
1481 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1484 if (ereg('m', $display) || (empty($display))) {
1485 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1488 if (ereg("s", $display) || (empty($display))) {
1489 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1495 if (ereg('Y', $display) || (empty($display))) {
1496 // Generate year selection
1497 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1498 for ($idx = '0'; $idx <= 10; $idx++) {
1499 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1500 if ($idx == $Y) $OUT .= ' selected="selected"';
1501 $OUT .= ">" . $idx."</option>\n";
1503 $OUT .= " </select></td>\n";
1505 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1508 if (ereg('M', $display) || (empty($display))) {
1509 // Generate month selection
1510 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1511 for ($idx = '0'; $idx <= 11; $idx++)
1513 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1514 if ($idx == $M) $OUT .= ' selected="selected"';
1515 $OUT .= ">" . $idx."</option>\n";
1517 $OUT .= " </select></td>\n";
1519 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1522 if (ereg("W", $display) || (empty($display))) {
1523 // Generate week selection
1524 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1525 for ($idx = '0'; $idx <= 4; $idx++) {
1526 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1527 if ($idx == $W) $OUT .= ' selected="selected"';
1528 $OUT .= ">" . $idx."</option>\n";
1530 $OUT .= " </select></td>\n";
1532 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1535 if (ereg("D", $display) || (empty($display))) {
1536 // Generate day selection
1537 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1538 for ($idx = '0'; $idx <= 31; $idx++) {
1539 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1540 if ($idx == $D) $OUT .= ' selected="selected"';
1541 $OUT .= ">" . $idx."</option>\n";
1543 $OUT .= " </select></td>\n";
1545 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1548 if (ereg("h", $display) || (empty($display))) {
1549 // Generate hour selection
1550 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1551 for ($idx = '0'; $idx <= 23; $idx++) {
1552 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1553 if ($idx == $h) $OUT .= ' selected="selected"';
1554 $OUT .= ">" . $idx."</option>\n";
1556 $OUT .= " </select></td>\n";
1558 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1561 if (ereg('m', $display) || (empty($display))) {
1562 // Generate minute selection
1563 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1564 for ($idx = '0'; $idx <= 59; $idx++) {
1565 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1566 if ($idx == $m) $OUT .= ' selected="selected"';
1567 $OUT .= ">" . $idx."</option>\n";
1569 $OUT .= " </select></td>\n";
1571 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1574 if (ereg("s", $display) || (empty($display))) {
1575 // Generate second selection
1576 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1577 for ($idx = '0'; $idx <= 59; $idx++) {
1578 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1579 if ($idx == $s) $OUT .= ' selected="selected"';
1580 $OUT .= ">" . $idx."</option>\n";
1582 $OUT .= " </select></td>\n";
1584 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1587 $OUT .= "</table>\n";
1589 // Return generated HTML code
1595 function createTimestampFromSelections ($prefix, $postData) {
1596 // Initial return value
1599 // Do we have a leap year?
1601 $TEST = date('Y', time()) / 4;
1602 $M1 = date('m', time());
1603 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1604 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1605 // First add years...
1606 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1608 $ret += $postData[$prefix."_mo"] * 2628000;
1610 $ret += $postData[$prefix."_we"] * 604800;
1612 $ret += $postData[$prefix."_da"] * 86400;
1614 $ret += $postData[$prefix."_ho"] * 3600;
1616 $ret += $postData[$prefix."_mi"] * 60;
1617 // And at last seconds...
1618 $ret += $postData[$prefix."_se"];
1619 // Return calculated value
1623 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1624 function createFancyTime ($stamp) {
1625 // Get data array with years/months/weeks/days/...
1626 $data = createTimeSelections($stamp, '', '', '', true);
1628 foreach($data as $k => $v) {
1630 // Value is greater than 0 "eval" data to return string
1631 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1636 // Do we have something there?
1637 if (strlen($ret) > 0) {
1638 // Remove leading commata and space
1639 $ret = substr($ret, 2);
1642 $ret = "0 {--_SECONDS--}";
1645 // Return fancy time string
1649 // Generates a navigation row for listing emails
1650 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1651 $SEP = ''; $TOP = '';
1652 if ($show_form === false) {
1654 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1658 for ($page = 1; $page <= $PAGES; $page++) {
1659 // Is the page currently selected or shall we generate a link to it?
1660 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1661 // Is currently selected, so only highlight it
1662 $NAV .= '<strong>-';
1664 // Open anchor tag and add base URL
1665 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1667 // Add userid when we shall show all mails from a single member
1668 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1670 // Close open anchor tag
1674 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1675 // Is currently selected, so only highlight it
1676 $NAV .= '-</strong>';
1682 // Add seperator if we have not yet reached total pages
1683 if ($page < $PAGES) $NAV .= ' | ';
1686 // Define constants only once
1687 $content['nav'] = $NAV;
1688 $content['span'] = $colspan;
1689 $content['top'] = $TOP;
1690 $content['sep'] = $SEP;
1692 // Load navigation template
1693 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1695 if ($return === true) {
1696 // Return generated HTML-Code
1704 // Extract host from script name
1705 function extractHostnameFromUrl (&$script) {
1706 // Use default SERVER_URL by default... ;) So?
1707 $url = getConfig('SERVER_URL');
1709 // Is this URL valid?
1710 if (substr($script, 0, 7) == 'http://') {
1711 // Use the hostname from script URL as new hostname
1712 $url = substr($script, 7);
1713 $extract = explode('/', $url);
1715 // Done extracting the URL :)
1718 // Extract host name
1719 $host = str_replace('http://', '', $url);
1720 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1722 // Generate relative URL
1723 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1724 if (substr(strtolower($script), 0, 7) == 'http://') {
1725 // But only if http:// is in front!
1726 $script = substr($script, (strlen($url) + 7));
1727 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1729 $script = substr($script, (strlen($url) + 8));
1732 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1733 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1739 // Send a GET request
1740 function sendGetRequest ($script, $data = array()) {
1741 // Extract host name from script
1742 $host = extractHostnameFromUrl($script);
1745 $scriptData = http_build_query($data, '', '&');
1747 // Do we have a question-mark in the script?
1748 if (strpos($script, '?') === false) {
1749 // No, so first char must be question mark
1750 $scriptData = '?' . $scriptData;
1753 $scriptData = '&' . $scriptData;
1757 $script .= $scriptData;
1759 // Generate GET request header
1760 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1761 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1762 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1763 if (isConfigEntrySet('FULL_VERSION')) {
1764 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1766 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1768 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1769 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1770 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1772 // Send the raw request
1773 $response = sendRawRequest($host, $request);
1775 // Return the result to the caller function
1779 // Send a POST request
1780 function sendPostRequest ($script, $postData) {
1781 // Is postData an array?
1782 if (!is_array($postData)) {
1784 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1785 return array('', '', '');
1788 // Extract host name from script
1789 $host = extractHostnameFromUrl($script);
1791 // Construct request
1792 $data = http_build_query($postData, '', '&');
1794 // Generate POST request header
1795 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1796 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1797 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1798 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1799 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1800 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1801 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1802 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1805 // Send the raw request
1806 $response = sendRawRequest($host, $request);
1808 // Return the result to the caller function
1812 // Sends a raw request to another host
1813 function sendRawRequest ($host, $request) {
1814 // Init errno and errdesc with 'all fine' values
1815 $errno = '0'; $errdesc = '';
1818 $response = array('', '', '');
1820 // Default is not to use proxy
1823 // Are proxy settins set?
1824 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1830 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1831 if ($useProxy === true) {
1832 // Connect to host through proxy connection
1833 $fp = @fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1835 // Connect to host directly
1836 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1840 if (!is_resource($fp)) {
1846 if ($useProxy === true) {
1847 // Generate CONNECT request header
1848 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1849 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1851 // Use login data to proxy? (username at least!)
1852 if (getConfig('proxy_username') != '') {
1854 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
1855 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1858 // Add last new-line
1859 $proxyTunnel .= getConfig('HTTP_EOL');
1860 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1863 fputs($fp, $proxyTunnel);
1867 // No response received
1871 // Read the first line
1872 $resp = trim(fgets($fp, 10240));
1873 $respArray = explode(' ', $resp);
1874 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1875 // Invalid response!
1881 fputs($fp, $request);
1884 while (!feof($fp)) {
1885 $response[] = trim(fgets($fp, 1024));
1891 // Skip first empty lines
1893 foreach ($resp as $idx => $line) {
1895 $line = trim($line);
1897 // Is this line empty?
1900 array_shift($response);
1902 // Abort on first non-empty line
1907 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1909 // Proxy agent found?
1910 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1911 // Proxy header detected, so remove two lines
1912 array_shift($response);
1913 array_shift($response);
1916 // Was the request successfull?
1917 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1918 // Not found / access forbidden
1919 $response = array('', '', '');
1926 // Taken from www.php.net eregi() user comments
1927 function isEmailValid ($email) {
1928 // Check first part of email address
1929 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1932 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1935 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1937 // Return check result
1938 return preg_match($regex, $email);
1941 // Function taken from user comments on www.php.net / function eregi()
1942 function isUrlValid ($URL, $compile=true) {
1943 // Trim URL a little
1944 $URL = trim(urldecode($URL));
1945 //* DEBUG: */ outputHtml($URL.'<br />');
1947 // Compile some chars out...
1948 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1949 //* DEBUG: */ outputHtml($URL.'<br />');
1951 // Check for the extension filter
1952 if (isExtensionActive('filter')) {
1953 // Use the extension's filter set
1954 return FILTER_VALIDATE_URL($URL, false);
1957 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1958 // https:// in front of the URLs
1959 return isUrlValidSimple($URL);
1962 // Generate a list of administrative links to a given userid
1963 function generateMemberAdminActionLinks ($userid, $status = '') {
1964 // Make sure userid is a number
1965 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1967 // Define all main targets
1968 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1970 // Begin of navigation links
1973 foreach ($targetArray as $tar) {
1974 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1975 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1976 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1977 // Locked accounts shall be unlocked
1978 $OUT .= 'UNLOCK_USER';
1980 // All other status is fine
1981 $OUT .= strtoupper($tar);
1983 $OUT .= "_TITLE--}\">{--ADMIN_";
1984 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1985 // Locked accounts shall be unlocked
1986 $OUT .= 'UNLOCK_USER';
1988 // All other status is fine
1989 $OUT .= strtoupper($tar);
1991 $OUT .= "--}</a></span> | ";
1994 // Finish navigation link
1995 $OUT = substr($OUT, 0, -7) . ']';
2001 // Generate an email link
2002 function generateEmailLink ($email, $table = 'admins') {
2003 // Default email link (INSECURE! Spammer can read this by harvester programs)
2004 $EMAIL = 'mailto:' . $email;
2006 // Check for several extensions
2007 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2008 // Create email link for contacting admin in guest area
2009 $EMAIL = generateAdminEmailLink($email);
2010 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2011 // Create email link for contacting a member within admin area (or later in other areas, too?)
2012 $EMAIL = generateUserEmailLink($email, 'admin');
2013 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2014 // Create email link to contact sponsor within admin area (or like the link above?)
2015 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2018 // Shall I close the link when there is no admin?
2019 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2021 // Return email link
2025 // Generate a hash for extra-security for all passwords
2026 function generateHash ($plainText, $salt = '') {
2027 // Is the required extension 'sql_patches' there and a salt is not given?
2028 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2029 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2030 return md5($plainText);
2033 // Do we miss an arry element here?
2034 if (!isConfigEntrySet('file_hash')) {
2036 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2039 // When the salt is empty build a new one, else use the first x configured characters as the salt
2041 // Build server string (inc/databases.php is no longer updated with every commit)
2042 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2045 $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');
2048 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2050 // Calculate number for generating the code
2051 $a = time() + getConfig('_ADD') - 1;
2053 // Generate SHA1 sum from modula of number and the prime number
2054 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2055 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2056 $sha1 = scrambleString($sha1);
2057 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2058 //* DEBUG: */ $sha1b = descrambleString($sha1);
2059 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2061 // Generate the password salt string
2062 $salt = substr($sha1, 0, getConfig('salt_length'));
2063 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2066 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2067 $salt = substr($salt, 0, getConfig('salt_length'));
2068 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2070 // Sanity check on salt
2071 if (strlen($salt) != getConfig('salt_length')) {
2073 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2078 return $salt.sha1($salt . $plainText);
2081 // Scramble a string
2082 function scrambleString($str) {
2086 // Final check, in case of failture it will return unscrambled string
2087 if (strlen($str) > 40) {
2088 // The string is to long
2090 } elseif (strlen($str) == 40) {
2092 $scrambleNums = explode(':', getConfig('pass_scramble'));
2094 // Generate new numbers
2095 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2098 // Scramble string here
2099 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2100 for ($idx = '0'; $idx < strlen($str); $idx++) {
2101 // Get char on scrambled position
2102 $char = substr($str, $scrambleNums[$idx], 1);
2104 // Add it to final output string
2105 $scrambled .= $char;
2108 // Return scrambled string
2109 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2113 // De-scramble a string scrambled by scrambleString()
2114 function descrambleString($str) {
2115 // Scramble only 40 chars long strings
2116 if (strlen($str) != 40) return $str;
2118 // Load numbers from config
2119 $scrambleNums = explode(':', getConfig('pass_scramble'));
2122 if (count($scrambleNums) != 40) return $str;
2124 // Begin descrambling
2125 $orig = str_repeat(' ', 40);
2126 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2127 for ($idx = '0'; $idx < 40; $idx++) {
2128 $char = substr($str, $idx, 1);
2129 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2132 // Return scrambled string
2133 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2137 // Generated a "string" for scrambling
2138 function genScrambleString ($len) {
2139 // Prepare array for the numbers
2140 $scrambleNumbers = array();
2142 // First we need to setup randomized numbers from 0 to 31
2143 for ($idx = '0'; $idx < $len; $idx++) {
2145 $rand = mt_rand(0, ($len -1));
2147 // Check for it by creating more numbers
2148 while (array_key_exists($rand, $scrambleNumbers)) {
2149 $rand = mt_rand(0, ($len -1));
2153 $scrambleNumbers[$rand] = $rand;
2156 // So let's create the string for storing it in database
2157 $scrambleString = implode(':', $scrambleNumbers);
2158 return $scrambleString;
2161 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2162 function generatePassString ($passHash) {
2163 // Return vanilla password hash
2166 // Is a secret key and master salt already initialized?
2167 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2168 // Only calculate when the secret key is generated
2169 $newHash = ''; $start = 9;
2170 for ($idx = '0'; $idx < 10; $idx++) {
2171 $part1 = hexdec(substr($passHash, $start, 4));
2172 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2173 $mod = dechex($idx);
2174 if ($part1 > $part2) {
2175 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2176 } elseif ($part2 > $part1) {
2177 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2179 $mod = substr($mod, 0, 4);
2180 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2181 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2182 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2187 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2188 $ret = generateHash($newHash, getConfig('master_salt'));
2189 //* DEBUG: */ print('ret='.$ret.'<br />');
2192 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2193 $ret = md5($passHash);
2194 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2201 // Fix "deleted" cookies
2202 function fixDeletedCookies ($cookies) {
2203 // Is this an array with entries?
2204 if ((is_array($cookies)) && (count($cookies) > 0)) {
2205 // Then check all cookies if they are marked as deleted!
2206 foreach ($cookies as $cookieName) {
2207 // Is the cookie set to "deleted"?
2208 if (getSession($cookieName) == 'deleted') {
2209 setSession($cookieName, '');
2215 // Output error messages in a fasioned way and die...
2216 function app_die ($F, $L, $message) {
2217 // Check if Script is already dieing and not let it kill itself another 1000 times
2218 if (!isset($GLOBALS['app_died'])) {
2219 // Make sure, that the script realy realy diese here and now
2220 $GLOBALS['app_died'] = true;
2223 loadIncludeOnce('inc/header.php');
2225 // Rewrite message for output
2226 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2228 // Better log this message away
2229 logDebugMessage($F, $L, $message);
2231 // Load the message template
2232 loadTemplate('admin_settings_saved', false, $message);
2235 loadIncludeOnce('inc/footer.php');
2237 // Script tried to kill itself twice
2238 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2242 // Display parsing time and number of SQL queries in footer
2243 function displayParsingTime() {
2244 // Is the timer started?
2245 if (!isset($GLOBALS['startTime'])) {
2251 $endTime = microtime(true);
2253 // "Explode" both times
2254 $start = explode(' ', $GLOBALS['startTime']);
2255 $end = explode(' ', $endTime);
2256 $runTime = $end[0] - $start[0];
2257 if ($runTime < 0) $runTime = '0';
2261 'runtime' => translateComma($runTime),
2262 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2265 // Load the template
2266 loadTemplate('show_timings', false, $content);
2269 // Check wether a boolean constant is set
2270 // Taken from user comments in PHP documentation for function constant()
2271 function isBooleanConstantAndTrue ($constName) { // : Boolean
2272 // Failed by default
2276 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2278 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2279 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2282 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2283 if (defined($constName)) {
2285 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2286 $res = (constant($constName) === true);
2290 $GLOBALS['cache_array']['const'][$constName] = $res;
2292 //* DEBUG: */ var_dump($res);
2298 // Checks if a given apache module is loaded
2299 function isApacheModuleLoaded ($apacheModule) {
2300 // Check it and return result
2301 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2304 // Get current theme name
2305 function getCurrentTheme () {
2306 // The default theme is 'default'... ;-)
2309 // Load default theme if not empty from configuration
2310 if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
2312 if (!isSessionVariableSet('mxchange_theme')) {
2313 // Set default theme
2315 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2316 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2317 // Get theme from cookie
2318 $ret = getSession('mxchange_theme');
2321 if (getThemeId($ret) == '0') {
2322 // Fix it to default
2325 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2326 // Prepare FQFN for checking
2327 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2329 // Installation mode active
2330 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2331 // Set cookie from URL data
2332 setTheme(getRequestElement('theme'));
2333 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2334 // Set cookie from posted data
2335 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2339 $ret = getSession('mxchange_theme');
2341 // Invalid design, reset cookie
2345 // Return theme value
2349 // Setter for theme in session
2350 function setTheme ($newTheme) {
2351 setSession('mxchange_theme', $newTheme);
2354 // Get id from theme
2355 // @TODO Try to move this to inc/libs/theme_functions.php
2356 function getThemeId ($name) {
2357 // Is the extension 'theme' installed?
2358 if (!isExtensionActive('theme')) {
2366 // Is the cache entry there?
2367 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2368 // Get the version from cache
2369 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2372 incrementStatsEntry('cache_hits');
2373 } elseif (getExtensionVersion('cache') != '0.1.8') {
2374 // Check if current theme is already imported or not
2375 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2376 array($name), __FUNCTION__, __LINE__);
2379 if (SQL_NUMROWS($result) == 1) {
2381 list($id) = SQL_FETCHROW($result);
2385 SQL_FREERESULT($result);
2392 // Generates an error code from given account status
2393 function generateErrorCodeFromUserStatus ($status='') {
2394 // If no status is provided, use the default, cached
2395 if ((empty($status)) && (isMember())) {
2397 $status = getUserData('status');
2400 // Default error code if unknown account status
2401 $errorCode = getCode('UNKNOWN_STATUS');
2403 // Generate constant name
2404 $codeName = sprintf("ID_%s", $status);
2406 // Is the constant there?
2407 if (isCodeSet($codeName)) {
2409 $errorCode = getCode($codeName);
2412 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2415 // Return error code
2419 // Function to search for the last modifified file
2420 function searchDirsRecursive ($dir, &$last_changed) {
2422 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2423 // Does it match what we are looking for? (We skip a lot files already!)
2424 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2425 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2426 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2427 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2429 // Walk through all entries
2430 foreach ($ds as $d) {
2431 // Generate proper FQFN
2432 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2434 // Is it a file and readable?
2435 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2436 if (isDirectory($FQFN)) {
2437 // $FQFN is a directory so also crawl into this directory
2439 if (!empty($dir)) $newDir = $dir . '/'. $d;
2440 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2441 searchDirsRecursive($newDir, $last_changed);
2442 } elseif (isFileReadable($FQFN)) {
2443 // $FQFN is a filename and no directory
2444 $time = filemtime($FQFN);
2445 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2446 if ($last_changed['time'] < $time) {
2447 // This file is newer as the file before
2448 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2449 $last_changed['path_name'] = $FQFN;
2450 $last_changed['time'] = $time;
2456 // "Getter" for revision/version data
2457 function getActualVersion ($type = 'Revision') {
2458 // By default nothing is new... ;-)
2461 // Is the cache entry there?
2462 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2463 // Found so increase cache hit
2464 incrementStatsEntry('cache_hits');
2467 return $GLOBALS['cache_array']['revision'][$type][0];
2469 // FQFN of revision file
2470 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2472 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2473 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2474 // Forced rebuild of .revision file
2477 // Check for revision file
2478 if (!isFileReadable($FQFN)) {
2479 // Not found, so we need to create it
2482 // Revision file found
2483 $ins_vers = explode("\n", readFromFile($FQFN));
2485 // Get array for mapping information
2486 $mapper = array_flip(getSearchFor());
2487 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2489 // Is the content valid?
2490 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2491 // File needs update!
2494 // Generate fake cache entry
2495 foreach ($mapper as $map=>$idx) {
2496 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2499 // Return found value
2500 return trim($ins_vers[$mapper[$type]]);
2505 // Has it been updated?
2506 if ($new === true) {
2508 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2510 // ... and call recursive
2511 return getActualVersion($type);
2516 // Repares an array we are looking for
2517 // 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
2518 function getSearchFor () {
2519 // Add Revision, Date, Tag and Author
2520 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2522 // Return the created array
2526 // @TODO Please describe this function
2527 function getArrayFromActualVersion () {
2531 // Directory to start with search
2532 $last_changed = array(
2537 // Init return array
2538 $akt_vers = array();
2540 // Init value for counting the founded keywords
2543 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2544 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2547 $last_file = readFromFile($last_changed['path_name']);
2549 // Get all the keywords to search for
2550 $searchFor = getSearchFor();
2552 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2553 foreach ($searchFor as $search) {
2554 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2555 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2556 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2557 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2560 // Save the last-changed filename for debugging
2561 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2563 // at least 3 keyword-Tags are needed for propper values
2564 if ($res && $res >= 3
2565 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2566 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2567 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2568 // Prepare content witch need special treadment
2570 // Prepare timestamp for date
2571 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2572 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2574 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2575 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2576 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2580 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2581 $version = sendGetRequest('check-updates3.php');
2584 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2585 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2586 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2587 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2588 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2589 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2592 // Return prepared array
2593 return $GLOBALS['cache_array']['revision'];
2596 // Back-ported from the new ship-simu engine. :-)
2597 function debug_get_printable_backtrace () {
2599 $backtrace = "<ol>\n";
2601 // Get and prepare backtrace for output
2602 $backtraceArray = debug_backtrace();
2603 foreach ($backtraceArray as $key => $trace) {
2604 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2605 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2606 if (!isset($trace['args'])) $trace['args'] = array();
2607 $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";
2611 $backtrace .= "</ol>\n";
2613 // Return the backtrace
2617 // Output a debug backtrace to the user
2618 function debug_report_bug ($message = '') {
2619 // Is this already called?
2620 if (isset($GLOBALS[__FUNCTION__])) {
2622 print 'Message:'.$message.'<br />Backtrace:<pre>';
2623 debug_print_backtrace();
2627 // Set this function as called
2628 $GLOBALS[__FUNCTION__] = true;
2633 // Is the optional message set?
2634 if (!empty($message)) {
2636 $debug = sprintf("Note: %s<br />\n",
2640 // @TODO Add a little more infos here
2641 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2645 $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>";
2646 $debug .= debug_get_printable_backtrace();
2647 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2648 $debug .= "Thank you for finding bugs.";
2651 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2655 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2656 function generateSeed () {
2657 list($usec, $sec) = explode(' ', microtime());
2658 $microTime = (((float)$sec + (float)$usec)) * 100000;
2662 // Converts a message code to a human-readable message
2663 function getMessageFromErrorCode ($code) {
2667 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2668 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2669 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2670 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2671 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2672 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2673 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2674 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2675 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2676 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2677 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2678 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2679 case getCode('ID_GUEST') : $message = getMessage('LOGIN_ID_GUEST'); break;
2680 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2681 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2682 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2683 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2684 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2685 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2686 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2687 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2688 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2689 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2690 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2691 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2692 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2693 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2694 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2695 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2697 case getCode('ERROR_MAILID'):
2698 if (isExtensionActive('mailid', true)) {
2699 $message = getMessage('ERROR_CONFIRMING_MAIL');
2701 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2705 case getCode('EXTENSION_PROBLEM'):
2706 if (isGetRequestElementSet('ext')) {
2707 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2709 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2713 case getCode('URL_TLOCK'):
2714 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2715 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2717 // Load timestamp from last order
2718 list($timestamp) = SQL_FETCHROW($result);
2719 $timestamp = generateDateTime($timestamp, 1);
2722 SQL_FREERESULT($result);
2724 // Calculate hours...
2725 $STD = round(getConfig('url_tlock') / 60 / 60);
2728 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2731 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2733 // Finally contruct the message
2734 // @TODO Rewrite this old lost code to a template
2735 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2736 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2737 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2741 // Missing/invalid code
2742 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2745 logDebugMessage(__FUNCTION__, __LINE__, $message);
2749 // Return the message
2753 // Compile characters which are allowed in URLs
2754 function compileUriCode ($code, $simple = true) {
2755 // Compile constants
2756 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2758 // Compile QUOT and other non-HTML codes
2759 $code = str_replace('{DOT}', '.',
2760 str_replace('{SLASH}', '/',
2761 str_replace('{QUOT}', "'",
2762 str_replace('{DOLLAR}', '$',
2763 str_replace('{OPEN_ANCHOR}', '(',
2764 str_replace('{CLOSE_ANCHOR}', ')',
2765 str_replace('{OPEN_SQR}', '[',
2766 str_replace('{CLOSE_SQR}', ']',
2767 str_replace('{PER}', '%',
2771 // Return compiled code
2775 // Function taken from user comments on www.php.net / function eregi()
2776 function isUrlValidSimple ($url) {
2778 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2780 // Allows http and https
2781 $http = "(http|https)+(:\/\/)";
2783 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2784 // Test double-domains (e.g. .de.vu)
2785 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2787 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2789 $dir = "((/)+([-_\.[:alnum:]])+)*";
2791 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2792 // ... and the string after and including question character
2793 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2794 // Pattern for URLs like http://url/dir/doc.html?var=value
2795 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2796 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2797 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2798 // Pattern for URLs like http://url/dir/?var=value
2799 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2800 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2801 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2802 // Pattern for URLs like http://url/dir/page.ext
2803 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2804 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2805 $pattern['ipdp'] = $http . $ip . $dir . $page;
2806 // Pattern for URLs like http://url/dir
2807 $pattern['d1d'] = $http . $domain1 . $dir;
2808 $pattern['d2d'] = $http . $domain2 . $dir;
2809 $pattern['ipd'] = $http . $ip . $dir;
2810 // Pattern for URLs like http://url/?var=value
2811 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2812 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2813 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2814 // Pattern for URLs like http://url?var=value
2815 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2816 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2817 $pattern['ipg12'] = $http . $ip . $getstring1;
2818 // Test all patterns
2820 foreach ($pattern as $key => $pat) {
2822 if (isDebugRegExpressionEnabled()) {
2823 // @TODO Are these convertions still required?
2824 $pat = str_replace('.', "\.", $pat);
2825 $pat = str_replace('@', "\@", $pat);
2826 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2829 // Check if expression matches
2830 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2833 if ($reg === true) break;
2836 // Return true/false
2840 // Wtites data to a config.php-style file
2841 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2842 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2843 // Initialize some variables
2849 // Is the file there and read-/write-able?
2850 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2851 $search = 'CFG: ' . $comment;
2852 $tmp = $FQFN . '.tmp';
2854 // Open the source file
2855 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2857 // Is the resource valid?
2858 if (is_resource($fp)) {
2859 // Open temporary file
2860 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2862 // Is the resource again valid?
2863 if (is_resource($fp_tmp)) {
2864 // Mark temporary file as readable
2865 $GLOBALS['file_readable'][$tmp] = true;
2868 while (!feof($fp)) {
2869 // Read from source file
2870 $line = fgets ($fp, 1024);
2872 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2875 if ($next === $seek) {
2877 $line = $prefix . $DATA . $suffix . "\n";
2883 // Write to temp file
2884 fputs($fp_tmp, $line);
2890 // Finished writing tmp file
2894 // Close source file
2897 if (($done === true) && ($found === true)) {
2898 // Copy back tmp file and delete tmp :-)
2899 copyFileVerified($tmp, $FQFN, 0644);
2900 return removeFile($tmp);
2901 } elseif ($found === false) {
2902 outputHtml('<strong>CHANGE:</strong> 404!');
2904 outputHtml('<strong>TMP:</strong> UNDONE!');
2908 // File not found, not readable or writeable
2909 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2912 // An error was detected!
2915 // Send notification to admin
2916 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2917 if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
2919 sendAdminsEmails($subject, $templateName, $content, $userid);
2921 // Send out out-dated way
2922 $message = loadEmailTemplate($templateName, $content, $userid);
2923 sendAdminEmails($subject, $message);
2927 // Debug message logger
2928 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2929 // Is debug mode enabled?
2930 if ((isDebugModeEnabled()) || ($force === true)) {
2932 $message = str_replace("\r", '', str_replace("\n", '', $message));
2934 // Log this message away, we better don't call app_die() here to prevent an endless loop
2935 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2936 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2941 // Handle extra values
2942 function handleExtraValues ($filterFunction, $value, $extraValue) {
2943 // Default is the value itself
2946 // Do we have a special filter function?
2947 if (!empty($filterFunction)) {
2948 // Does the filter function exist?
2949 if (function_exists($filterFunction)) {
2950 // Do we have extra parameters here?
2951 if (!empty($extraValue)) {
2952 // Put both parameters in one new array by default
2953 $args = array($value, $extraValue);
2955 // If we have an array simply use it and pre-extend it with our value
2956 if (is_array($extraValue)) {
2957 // Make the new args array
2958 $args = merge_array(array($value), $extraValue);
2961 // Call the multi-parameter call-back
2962 $ret = call_user_func_array($filterFunction, $args);
2964 // One parameter call
2965 $ret = call_user_func($filterFunction, $value);
2974 // Converts timestamp selections into a timestamp
2975 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2976 // Init test variable
2980 // Get last three chars
2981 $test = substr($id, -3);
2983 // Improved way of checking! :-)
2984 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2985 // Found a multi-selection for timings?
2986 $test = substr($id, 0, -3);
2987 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)) {
2988 // Generate timestamp
2989 $postData[$test] = createTimestampFromSelections($test, $postData);
2990 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2991 $GLOBALS['skip_config'][$test] = true;
2993 // Remove data from array
2994 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2995 unset($postData[$test . '_' . $rem]);
3006 // Reverts the german decimal comma into Computer decimal dot
3007 function convertCommaToDot ($str) {
3008 // Default float is not a float... ;-)
3011 // Which language is selected?
3012 switch (getLanguage()) {
3013 case 'de': // German language
3014 // Remove german thousand dots first
3015 $str = str_replace('.', '', $str);
3017 // Replace german commata with decimal dot and cast it
3018 $float = (float)str_replace(',', '.', $str);
3021 default: // US and so on
3022 // Remove thousand dots first and cast
3023 $float = (float)str_replace(',', '', $str);
3031 // Handle menu-depending failed logins and return the rendered content
3032 function handleLoginFailtures ($accessLevel) {
3033 // Default output is empty ;-)
3036 // Is the session data set?
3037 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3038 // Ignore zero values
3039 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3040 // Non-guest has login failures found, get both data and prepare it for template
3041 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3043 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3044 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3048 $OUT = loadTemplate('login_failures', true, $content);
3051 // Reset session data
3052 setSession('mxchange_' . $accessLevel.'_failures', '');
3053 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3056 // Return rendered content
3061 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3063 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3065 // Shall I remove the cache file?
3066 if (isCacheInstanceValid()) {
3068 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3070 $GLOBALS['cache_instance']->removeCacheFile($force);
3073 // Include file given?
3076 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3078 // Is the include there?
3079 if (isIncludeReadable($inc)) {
3080 // And rebuild it from scratch
3081 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3084 // Include not found!
3085 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3091 // Determines the real remote address
3092 function determineRealRemoteAddress () {
3093 // Is a proxy in use?
3094 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3096 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3097 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3098 // Yet, another proxy
3099 $address = $_SERVER['HTTP_CLIENT_IP'];
3101 // The regular address when no proxy was used
3102 $address = $_SERVER['REMOTE_ADDR'];
3105 // This strips out the real address from proxy output
3106 if (strstr($address, ',')) {
3107 $addressArray = explode(',', $address);
3108 $address = $addressArray[0];
3111 // Return the result
3115 // Adds a bonus mail to the queue
3116 // This is a high-level function!
3117 function addNewBonusMail ($data, $mode = '', $output=true) {
3118 // Use mode from data if not set and availble ;-)
3119 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3121 // Generate receiver list
3122 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3125 if (!empty($RECEIVER)) {
3126 // Add bonus mail to queue
3127 addBonusMailToQueue(
3139 // Mail inserted into bonus pool
3140 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3141 } elseif ($output) {
3142 // More entered than can be reached!
3143 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3146 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3150 // Determines referal id and sets it
3151 function determineReferalId () {
3152 // Skip this in non-html-mode and outside ref.php
3153 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3155 // Check if refid is set
3156 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3158 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3159 // The variable user comes from the click-counter script click.php and we only accept this here
3160 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3161 } elseif (isPostRequestElementSet('refid')) {
3162 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3163 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3164 } elseif (isGetRequestElementSet('refid')) {
3165 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3166 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3167 } elseif (isGetRequestElementSet('ref')) {
3168 // Set refid=ref (the referal link uses such variable)
3169 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3170 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3171 // Set session refid als global
3172 $GLOBALS['refid'] = bigintval(getSession('refid'));
3173 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3174 // Select a random user which has confirmed enougth mails
3175 $GLOBALS['refid'] = determineRandomReferalId();
3176 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3177 // Set default refid as refid in URL
3178 $GLOBALS['refid'] = getConfig('def_refid');
3180 // No default id when sql_patches is not installed or none set
3181 $GLOBALS['refid'] = '0';
3184 // Set cookie when default refid > 0
3185 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3186 // Default is not found
3189 // Do we have nickname or userid set?
3190 if (isNicknameUsed($GLOBALS['refid'])) {
3191 // Nickname in URL, so load the id
3192 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3193 } elseif ($GLOBALS['refid'] > 0) {
3194 // Direct userid entered
3195 $found = fetchUserData($GLOBALS['refid']);
3198 // Is the record valid?
3199 if (($found === false) || (!isUserDataValid())) {
3200 // No, then reset referal id
3201 $GLOBALS['refid'] = getConfig('def_refid');
3205 setSession('refid', $GLOBALS['refid']);
3208 // Return determined refid
3209 return $GLOBALS['refid'];
3212 // Enables the reset mode and runs it
3213 function doReset () {
3214 // Enable the reset mode
3215 $GLOBALS['reset_enabled'] = true;
3218 runFilterChain('reset');
3221 // Our shutdown-function
3222 function shutdown () {
3223 // Call the filter chain 'shutdown'
3224 runFilterChain('shutdown', null);
3226 if (SQL_IS_LINK_UP()) {
3228 SQL_CLOSE(__FILE__, __LINE__);
3229 } elseif (!isInstallationPhase()) {
3231 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3234 // Stop executing here
3239 function initMemberId () {
3240 $GLOBALS['member_id'] = '0';
3243 // Setter for member id
3244 function setMemberId ($memberid) {
3245 // We should not set member id to zero
3246 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3249 $GLOBALS['member_id'] = bigintval($memberid);
3252 // Getter for member id or returns zero
3253 function getMemberId () {
3254 // Default member id
3257 // Is the member id set?
3258 if (isMemberIdSet()) {
3260 $memberid = $GLOBALS['member_id'];
3267 // Checks ether the member id is set
3268 function isMemberIdSet () {
3269 return (isset($GLOBALS['member_id']));
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 // Checks wethere there is a cache file there. This function is cached.
3646 function isTemplateCached ($template) {
3647 // Do we have cached this result?
3648 if (!isset($GLOBALS['template_cache'][$template])) {
3650 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3653 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3657 return $GLOBALS['template_cache'][$template];
3660 // Flushes non-flushed template cache to disk
3661 function flushTemplateCache ($template, $eval) {
3662 // Is this cache flushed?
3663 if ((!isTemplateCached($template)) && ($eval != '404')) {
3665 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3667 // Replace username with a call
3668 $eval = str_replace('$username', '".getUsername()."', $eval);
3671 writeToFile($FQFN, $eval, true);
3675 // Reads a template cache
3676 function readTemplateCache ($template) {
3678 if (isTemplateCached($template)) {
3680 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3683 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3687 return $GLOBALS['template_eval'][$template];
3690 //////////////////////////////////////////////////
3691 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3692 //////////////////////////////////////////////////
3694 if (!function_exists('html_entity_decode')) {
3695 // Taken from documentation on www.php.net
3696 function html_entity_decode ($string) {
3697 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3698 $trans_tbl = array_flip($trans_tbl);
3699 return strtr($string, $trans_tbl);
3703 if (!function_exists('http_build_query')) {
3704 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3705 function http_build_query($data, $prefix='', $sep='', $key='') {
3707 foreach ((array)$data as $k => $v) {
3708 if (is_int($k) && $prefix != null) {
3709 $k = urlencode($prefix . $k);
3712 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3714 if (is_array($v) || is_object($v)) {
3715 array_push($ret, http_build_query($v, '', $sep, $k));
3717 array_push($ret, $k.'='.urlencode($v));
3721 if (empty($sep)) $sep = ini_get('arg_separator.output');
3723 return implode($sep, $ret);