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'])) {
106 // Extension 'rewrite' installed?
107 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
108 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
111 // Compile and run finished rendered HTML code
112 compileFinalOutput();
114 // Send all HTTP headers
117 // Output code here, DO NOT REMOVE! ;-)
118 outputRawCode($GLOBALS['output']);
119 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
120 // Rewrite links when rewrite extension is active
121 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
122 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
125 // Compile and run finished rendered HTML code
126 compileFinalOutput();
128 // Send all HTTP headers
131 // Output code here, DO NOT REMOVE! ;-)
132 outputRawCode($GLOBALS['output']);
136 // Sends out all headers required for HTTP/1.1 reply
137 function sendHttpHeaders () {
139 $now = gmdate('D, d M Y H:i:s') . ' GMT';
142 sendHeader('HTTP/1.1 200');
144 // General headers for no caching
145 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
146 sendHeader('Last-Modified: ' . $now);
147 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
148 sendHeader('Pragma: no-cache'); // HTTP/1.0
149 sendHeader('Connection: Close');
150 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
151 sendHeader('Content-Language: ' . getLanguage());
154 // Compiles the final output
155 function compileFinalOutput () {
160 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
161 // Init common variables
166 $eval = "\$newContent = \"".compileCode(addslashes($GLOBALS['output']))."\";";
169 // Was that eval okay?
170 if (empty($newContent)) {
171 // Something went wrong!
172 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>');
174 $GLOBALS['output'] = $newContent;
181 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
184 // Output the raw HTML code
185 function outputRawCode ($htmlCode) {
186 // Output stripped HTML code to avoid broken JavaScript code, etc.
189 // Flush the output if only getPhpCaching() is not 'on'
190 if (getPhpCaching() != 'on') {
196 // Init fatal message array
197 function initFatalMessages () {
198 $GLOBALS['fatal_messages'] = array();
201 // Getter for whole fatal error messages
202 function getFatalArray () {
203 return $GLOBALS['fatal_messages'];
206 // Add a fatal error message to the queue array
207 function addFatalMessage ($F, $L, $message, $extra='') {
208 if (is_array($extra)) {
209 // Multiple extras for a message with masks
210 $message = call_user_func_array('sprintf', $extra);
211 } elseif (!empty($extra)) {
212 // $message is text with a mask plus extras to insert into the text
213 $message = sprintf($message, $extra);
216 // Add message to $GLOBALS['fatal_messages']
217 $GLOBALS['fatal_messages'][] = $message;
219 // Log fatal messages away
220 debug_report_bug($message);
221 logDebugMessage($F, $L, " message={$message}");
224 // Getter for total fatal message count
225 function getTotalFatalErrors () {
229 // Do we have at least the first entry?
230 if (!empty($GLOBALS['fatal_messages'][0])) {
232 $count = count($GLOBALS['fatal_messages']);
239 // Load a template file and return it's content (only it's name; do not use ' or ")
240 function loadTemplate ($template, $return=false, $content=array()) {
241 // @TODO Remove this sanity-check if all is fine
242 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
244 // @TODO Try to rewrite all $DATA to $content
248 if (isTemplateCached($template)) {
249 // Evaluate the cache
250 eval(readTemplateCache($template));
251 } elseif (!isset($GLOBALS['template_eval'][$template])) {
252 // Add more variables which you want to use in your template files
253 $username = getUsername();
255 // Make all template names lowercase
256 $template = strtolower($template);
258 // Count the template load
259 incrementConfigEntry('num_templates');
263 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
266 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
269 // Check for admin/guest/member templates
270 if (substr($template, 0, 6) == 'admin_') {
271 // Admin template found
273 } elseif (substr($template, 0, 6) == 'guest_') {
274 // Guest template found
276 } elseif (substr($template, 0, 7) == 'member_') {
277 // Member template found
279 } elseif (substr($template, 0, 8) == 'install_') {
280 // Installation template found
282 } elseif (substr($template, 0, 4) == 'ext_') {
283 // Extension template found
285 } elseif (substr($template, 0, 3) == 'la_') {
286 // 'Logical-area' template found
288 } elseif (substr($template, 0, 3) == 'js_') {
289 // JavaScript template found
291 } elseif (substr($template, 0, 5) == 'menu_') {
292 // Menu template found
295 // Test for extension
296 $test = substr($template, 0, strpos($template, '_'));
298 // Probe for valid extension name
299 if (isExtensionNameValid($test)) {
300 // Set extra path to extension's name
305 ////////////////////////
306 // Generate file name //
307 ////////////////////////
308 $FQFN = $basePath . $mode . $template . '.tpl';
310 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
311 // Select what depended header/footer template file for admin/guest/member area
312 $file2 = sprintf("%s%s%s_%s.tpl",
320 if (isFileReadable($file2)) $FQFN = $file2;
322 // Remove variable from memory
326 // Does the special template exists?
327 if (!isFileReadable($FQFN)) {
328 // Reset to default template
329 $FQFN = $basePath . $template . '.tpl';
332 // Now does the final template exists?
333 if (isFileReadable($FQFN)) {
334 // The local file does exists so we load it. :)
335 $GLOBALS['tpl_content'] = readFromFile($FQFN);
337 // Replace ' to our own chars to preventing them being quoted
338 while (strpos($GLOBALS['tpl_content'], "'") !== false) { $GLOBALS['tpl_content'] = str_replace("'", '{QUOT}', $GLOBALS['tpl_content']); }
340 // Do we have to compile the code?
342 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
343 // Normal HTML output?
344 if (getOutputMode() == '0') {
345 // Add surrounding HTML comments to help finding bugs faster
346 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
348 // Prepare eval() command
349 $eval = '$ret = "' . compileCode(addslashes($ret)) . '";';
350 } elseif (substr($template, 0, 3) == 'js_') {
351 // JavaScripts don't like entities and timings
352 $eval = '$ret = decodeEntities("' . compileRawCode(addslashes($GLOBALS['tpl_content'])) . '");';
354 // Prepare eval() command
355 $eval = '$ret = "' . compileCode(addslashes($GLOBALS['tpl_content'])) . '";';
358 // Add surrounding HTML comments to help finding bugs faster
359 $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
360 $eval = '$ret = "' . addslashes($ret) . '";';
363 // Cache the eval() command here
364 $GLOBALS['template_eval'][$template] = $eval;
367 eval($GLOBALS['template_eval'][$template]);
368 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
369 // Only admins shall see this warning or when installation mode is active
370 $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
371 (' . $template . ')<br />
373 {--TEMPLATE_CONTENT--}
374 <pre>' . print_r($content, true) . '</pre>
376 <pre>' . print_r($DATA, true) . '</pre>
380 $GLOBALS['template_eval'][$template] = '404';
384 eval($GLOBALS['template_eval'][$template]);
387 // Do we have some content to output or return?
389 // Not empty so let's put it out! ;)
390 if ($return === true) {
391 // Return the HTML code
397 } elseif (isDebugModeEnabled()) {
398 // Warning, empty output!
399 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
403 // Loads an email template and compiles it
404 function loadEmailTemplate ($template, $content = array(), $UID = '0') {
407 // Make sure all template names are lowercase!
408 $template = strtolower($template);
410 // Default 'nickname' if extension is not installed
413 // Prepare IP number and User Agent
414 $REMOTE_ADDR = detectRemoteAddr();
415 $HTTP_USER_AGENT = detectUserAgent();
418 $ADMIN = getConfig('MAIN_TITLE');
420 // Is the admin logged in?
423 $adminId = getCurrentAdminId();
426 $ADMIN = getAdminEmail($adminId);
429 // Neutral email address is default
430 $email = getConfig('WEBMASTER');
432 // Expiration in a nice output format
433 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
434 if (getConfig('auto_purge') == '0') {
435 // Will never expire!
436 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
438 // Create nice date string
439 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
442 // Is content an array?
443 if (is_array($content)) {
444 // Add expiration to array, $EXPIRATION is now deprecated!
445 $content['expiration'] = $EXPIRATION;
449 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content).'<br />');
450 if (($UID > 0) && (is_array($content))) {
451 // If nickname extension is installed, fetch nickname as well
452 if (isNicknameUsed($UID)) {
453 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
455 fetchUserData($UID, 'nickname');
457 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
462 // Merge data if valid
463 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
464 if (isUserDataValid()) {
465 $content = merge_array($content, getUserDataArray());
467 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
470 // Translate M to male or F to female if present
471 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
473 // Overwrite email from data if present
474 if (isset($content['email'])) $email = $content['email'];
476 // Store email for some functions in global data array
477 $DATA['email'] = $email;
480 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
482 // Check for admin/guest/member templates
483 if (substr($template, 0, 6) == 'admin_') {
484 // Admin template found
485 $FQFN = $basePath.'admin/' . $template.'.tpl';
486 } elseif (substr($template, 0, 6) == 'guest_') {
487 // Guest template found
488 $FQFN = $basePath.'guest/' . $template.'.tpl';
489 } elseif (substr($template, 0, 7) == 'member_') {
490 // Member template found
491 $FQFN = $basePath.'member/' . $template.'.tpl';
493 // Test for extension
494 $test = substr($template, 0, strpos($template, '_'));
495 if (isExtensionNameValid($test)) {
496 // Set extra path to extension's name
497 $FQFN = $basePath . $test.'/' . $template.'.tpl';
499 // No special filename
500 $FQFN = $basePath . $template.'.tpl';
504 // Does the special template exists?
505 if (!isFileReadable($FQFN)) {
506 // Reset to default template
507 $FQFN = $basePath . $template.'.tpl';
510 // Now does the final template exists?
512 if (isFileReadable($FQFN)) {
513 // The local file does exists so we load it. :)
514 $GLOBALS['tpl_content'] = readFromFile($FQFN);
517 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileRawCode(addslashes($GLOBALS['tpl_content']))."\");";
518 eval($GLOBALS['tpl_content']);
519 } elseif (!empty($template)) {
520 // Template file not found!
521 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
522 {--TEMPLATE_CONTENT--}
523 <pre>".print_r($content, true)."</pre>
525 <pre>".print_r($DATA, true)."</pre>
528 // Debug mode not active? Then remove the HTML tags
529 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
531 // No template name supplied!
532 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
535 // Is there some content?
536 if (empty($newContent)) {
538 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
539 // Add last error if the required function exists
540 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
543 // Remove content and data
547 // Compile the code and eval it
548 $eval = '$newContent = "' . compileRawCode(addslashes($newContent)) . '";';
555 // Send mail out to an email address
556 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
557 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
559 // Compile subject line (for POINTS constant etc.)
560 eval("\$subject = decodeEntities(\"".compileRawCode(addslashes($subject))."\");");
563 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
564 // Value detected, is the message extension installed?
565 // @TODO Extension 'msg' does not exist
566 if (isExtensionActive('msg')) {
567 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
570 // Does the user exist?
571 if (fetchUserData($toEmail)) {
573 $toEmail = getUserData('email');
576 $toEmail = getConfig('WEBMASTER');
579 } elseif ($toEmail == '0') {
581 $toEmail = getConfig('WEBMASTER');
583 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
585 // Check for PHPMailer or debug-mode
586 if (!checkPhpMailerUsage()) {
587 // Not in PHPMailer-Mode
588 if (empty($mailHeader)) {
589 // Load email header template
590 $mailHeader = loadEmailTemplate('header');
593 $mailHeader .= loadEmailTemplate('header');
595 } elseif (isDebugModeEnabled()) {
596 if (empty($mailHeader)) {
597 // Load email header template
598 $mailHeader = loadEmailTemplate('header');
601 $mailHeader .= loadEmailTemplate('header');
606 eval("\$toEmail = \"".compileRawCode(addslashes($toEmail))."\";");
609 eval("\$message = \"".compileRawCode(addslashes($message))."\";");
611 // Fix HTML parameter (default is no!)
612 if (empty($isHtml)) $isHtml = 'N';
613 if (isDebugModeEnabled()) {
614 // In debug mode we want to display the mail instead of sending it away so we can debug this part
616 Headers : ' . str_replace('<', '<', str_replace('>', '>', htmlentities(trim($mailHeader)))) . '
617 To : ' . $toEmail . '
618 Subject : ' . $subject . '
619 Message : ' . $message . '
621 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
622 // Send mail as HTML away
623 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
624 } elseif (!empty($toEmail)) {
626 sendRawEmail($toEmail, $subject, $message, $mailHeader);
627 } elseif ($isHtml != 'Y') {
629 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
633 // Check if legacy or PHPMailer command
634 // @TODO Rewrite this to an extension 'smtp'
636 function checkPhpMailerUsage() {
637 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
640 // Send out a raw email with PHPMailer class or legacy mail() command
641 function sendRawEmail ($toEmail, $subject, $message, $from) {
642 // Shall we use PHPMailer class or legacy mode?
643 if (checkPhpMailerUsage()) {
644 // Use PHPMailer class with SMTP enabled
645 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
646 loadIncludeOnce('inc/phpmailer/class.smtp.php');
649 $mail = new PHPMailer();
651 // Set charset to UTF-8
652 $mail->CharSet('UTF-8');
654 // Path for PHPMailer
655 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
658 $mail->SMTPAuth = true;
659 $mail->Host = getConfig('SMTP_HOSTNAME');
661 $mail->Username = getConfig('SMTP_USER');
662 $mail->Password = getConfig('SMTP_PASSWORD');
664 $mail->From = getConfig('WEBMASTER');
668 $mail->FromName = getConfig('MAIN_TITLE');
669 $mail->Subject = $subject;
670 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
671 $mail->Body = $message;
672 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
673 $mail->WordWrap = 70;
676 $mail->Body = decodeEntities($message);
678 $mail->AddAddress($toEmail, '');
679 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
680 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
681 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
684 // Use legacy mail() command
685 mail($toEmail, $subject, decodeEntities($message), $from);
689 // Generate a password in a specified length or use default password length
690 function generatePassword ($length = '0') {
691 // Auto-fix invalid length of zero
692 if ($length == '0') $length = getConfig('pass_len');
694 // Initialize array with all allowed chars
695 $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,-,+,_,/,.');
697 // Start creating password
699 for ($i = '0'; $i < $length; $i++) {
700 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
703 // When the size is below 40 we can also add additional security by scrambling
704 // it. Otherwise we may corrupt hashes
705 if (strlen($PASS) <= 40) {
706 // Also scramble the password
707 $PASS = scrambleString($PASS);
710 // Return the password
714 // Generates a human-readable timestamp from the Uni* stamp
715 function generateDateTime ($time, $mode = '0') {
716 // Filter out numbers
717 $time = bigintval($time);
719 // If the stamp is zero it mostly didn't "happen"
722 return getMessage('NEVER_HAPPENED');
725 switch (getLanguage()) {
726 case 'de': // German date / time format
728 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
729 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
730 case '2': $ret = date('d.m.Y|H:i', $time); break;
731 case '3': $ret = date('d.m.Y', $time); break;
733 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
738 default: // Default is the US date / time format!
740 case '0': $ret = date('r', $time); break;
741 case '1': $ret = date('Y-m-d - g:i A', $time); break;
742 case '2': $ret = date('y-m-d|H:i', $time); break;
743 case '3': $ret = date('y-m-d', $time); break;
745 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
754 // Translates Y/N to yes/no
755 function translateYesNo ($yn) {
757 $translated = '??? (' . $yn . ')';
759 case 'Y': $translated = getMessage('YES'); break;
760 case 'N': $translated = getMessage('NO'); break;
763 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
771 // Translates the "pool type" into human-readable
772 function translatePoolType ($type) {
773 // Default?type is unknown
774 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
777 $constName = sprintf("POOL_TYPE_%s", $type);
780 if (isMessageIdValid($constName)) {
782 $translated = getMessage($constName);
785 // Return "translation"
789 // Translates the american decimal dot into a german comma
790 function translateComma ($dotted, $cut = true, $max = '0') {
791 // Default is 3 you can change this in admin area "Misc -> Misc Options"
792 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
794 // Use from config is default
795 $maxComma = getConfig('max_comma');
797 // Use from parameter?
798 if ($max > 0) $maxComma = $max;
801 if (($cut === true) && ($max == '0')) {
802 // Test for commata if in cut-mode
803 $com = explode('.', $dotted);
804 if (count($com) < 2) {
805 // Don't display commatas even if there are none... ;-)
811 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
814 switch (getLanguage()) {
815 case 'de': // German language
816 $dotted = number_format($dotted, $maxComma, ',', '.');
819 default: // All others
820 $dotted = number_format($dotted, $maxComma, '.', ',');
824 // Return translated value
828 // Translate Uni*-like gender to human-readable
829 function translateGender ($gender) {
831 $ret = '!' . $gender . '!';
833 // Male/female or company?
835 case 'M': $ret = getMessage('GENDER_M'); break;
836 case 'F': $ret = getMessage('GENDER_F'); break;
837 case 'C': $ret = getMessage('GENDER_C'); break;
839 // Log unknown gender
840 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
844 // Return translated gender
848 // "Translates" the user status
849 function translateUserStatus ($status) {
850 // Generate message depending on status
855 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
860 $ret = getMessage('ACCOUNT_DELETED');
864 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
865 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
873 // Generates an URL for the dereferer
874 function generateDerefererUrl ($URL) {
875 // Don't de-refer our own links!
876 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
877 // De-refer this link
878 $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
885 // Generates an URL for the frametester
886 function generateFrametesterUrl ($URL) {
887 // Prepare frametester URL
888 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
889 encodeString(compileUriCode($URL))
892 // Return the new URL
893 return $frametesterUrl;
896 // Count entries from e.g. a selection box
897 function countSelection ($array) {
899 if (!is_array($array)) {
901 debug_report_bug(__FUNCTION__.': No array provided.');
908 foreach ($array as $key => $selected) {
910 if (!empty($selected)) $ret++;
913 // Return counted selections
917 // Generate XHTML code for the CAPTCHA
918 function generateCaptchaCode ($code, $type, $DATA, $userid) {
919 return '<img border="0" alt="Code ' . $code . '" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
922 // Generates a timestamp (some wrapper for mktime())
923 function makeTime ($hours, $minutes, $seconds, $stamp) {
924 // Extract day, month and year from given timestamp
925 $days = date('d', $stamp);
926 $months = date('m', $stamp);
927 $years = date('Y', $stamp);
929 // Create timestamp for wished time which depends on extracted date
940 // Redirects to an URL and if neccessarry extends it with own base URL
941 function redirectToUrl ($URL) {
943 eval('$URL = "' . compileRawCode($URL) . '";');
945 // Check if http(s):// is there
946 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
947 // Make all URLs full-qualified
948 $URL = getConfig('URL') . '/' . $URL;
951 // Three different debug ways...
952 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
953 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
954 //* DEBUG: */ die($URL);
956 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
957 $rel = ' rel="external"';
959 // Do we have internal or external URL?
960 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
961 // Own (=internal) URL
966 $GLOBALS['output'] = ob_get_contents();
968 // Clear it only if there is content
969 if (!empty($GLOBALS['output'])) {
973 // Simple probe for bots/spiders from search engines
974 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
975 // Secure the URL against bad things such als HTML insertions and so on...
976 $URL = secureString($URL);
978 // Output new location link as anchor
979 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
980 } elseif (!headers_sent()) {
981 // Load URL when headers are not sent
982 //* DEBUG: */ debug_report_bug("URL={$URL}");
983 sendHeader('Location: '.str_replace('&', '&', $URL));
985 // Output error message
986 loadInclude('inc/header.php');
987 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
988 loadInclude('inc/footer.php');
991 // Shut the mailer down here
995 // Wrapper for redirectToUrl but URL comes from a configuration entry
996 function redirectToConfiguredUrl ($configEntry) {
998 $URL = getConfig($configEntry);
1001 if (is_null($URL)) {
1003 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1007 redirectToUrl($URL);
1010 // Compiles the given HTML/mail code
1011 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1012 // Is the code a string?
1013 if (!is_string($code)) {
1014 // Silently return it
1019 $startCompile = explode(' ', microtime());
1022 $code = compileRawCode($code, $simple, $constants, $full);
1025 $compiled = explode(' ', microtime());
1028 $code .= '<!-- Compilation time: ' . ((($compiled[1] + $compiled[0]) - ($startCompile[1] + $startCompile[0])) * 1000). 'ms //-->';
1030 // Return compiled code
1034 // Compiles the code (use compileCode() only for HTML because of the comments)
1035 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1036 // Is the code a string?
1037 if (!is_string($code)) {
1038 // Silently return it
1042 // Init replacement-array with full security characters
1043 $secChars = $GLOBALS['security_chars'];
1045 // Select smaller set of chars to replace when we e.g. want to compile URLs
1046 if ($full === false) $secChars = $GLOBALS['url_chars'];
1048 // Compile more through a filter
1049 $code = runFilterChain('compile_code', $code);
1051 // Compile constants
1052 if ($constants === true) {
1053 // BEFORE 0.2.1 : Language and data constants
1054 // WITH 0.2.1+ : Only language constants
1055 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1057 // BEFORE 0.2.1 : Not used
1058 // WITH 0.2.1+ : Data constants
1059 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1062 // Compile QUOT and other non-HTML codes
1063 foreach ($secChars['to'] as $k => $to) {
1064 // Do the reversed thing as in inc/libs/security_functions.php
1065 $code = str_replace($to, $secChars['from'][$k], $code);
1068 // But shall I keep simple quotes for later use?
1069 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1071 // Find $content[bla][blub] entries
1072 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1074 // Are some matches found?
1075 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1076 // Replace all matches
1077 $matchesFound = array();
1078 foreach ($matches[0] as $key => $match) {
1079 // Fuzzy look has failed by default
1080 $fuzzyFound = false;
1082 // Fuzzy look on match if already found
1083 foreach ($matchesFound as $found => $set) {
1085 $test = substr($found, 0, strlen($match));
1087 // Does this entry exist?
1088 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1089 if ($test == $match) {
1091 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1098 if ($fuzzyFound === true) continue;
1100 // Take all string elements
1101 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1102 // Replace it in the code
1103 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1104 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1105 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1106 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1107 $matchesFound[$match] = 1;
1108 } elseif (!isset($matchesFound[$match])) {
1109 // Not yet replaced!
1110 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1111 $code = str_replace($match, "\"." . $match.".\"", $code);
1112 $matchesFound[$match] = 1;
1121 /************************************************************************
1123 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1124 * $a_sort sortiert: *
1126 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1127 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1128 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1129 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1130 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1132 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1133 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1134 * Sie, dass es doch nicht so schwer ist! :-) *
1136 ************************************************************************/
1137 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1139 while ($primary_key < count($a_sort)) {
1140 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1141 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1143 if ($nums === false) {
1144 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1145 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1146 } elseif ($key != $key2) {
1147 // Sort numbers (E.g.: 9 < 10)
1148 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1149 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1153 // We have found two different values, so let's sort whole array
1154 foreach ($dummy as $sort_key => $sort_val) {
1155 $t = $dummy[$sort_key][$key];
1156 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1157 $dummy[$sort_key][$key2] = $t;
1168 // Write back sorted array
1173 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1176 if ($type == 'yn') {
1177 // This is a yes/no selection only!
1178 if ($id > 0) $prefix .= "[" . $id."]";
1179 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1181 // Begin with regular selection box here
1182 if (!empty($prefix)) $prefix .= "_";
1184 if ($id > 0) $type2 .= "[" . $id."]";
1185 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1190 for ($idx = 1; $idx < 32; $idx++) {
1191 $OUT .= "<option value=\"" . $idx."\"";
1192 if ($default == $idx) $OUT .= ' selected="selected"';
1193 $OUT .= ">" . $idx."</option>\n";
1197 case 'month': // Month
1198 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1199 $OUT .= "<option value=\"" . $month."\"";
1200 if ($default == $month) $OUT .= ' selected="selected"';
1201 $OUT .= ">" . $descr."</option>\n";
1205 case 'year': // Year
1207 $year = date('Y', time());
1209 // Use configured min age or fixed?
1210 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1212 $startYear = $year - getConfig('min_age');
1215 $startYear = $year - 16;
1218 // Calculate earliest year (100 years old people can still enter Internet???)
1219 $minYear = $year - 100;
1221 // Check if the default value is larger than minimum and bigger than actual year
1222 if (($default > $minYear) && ($default >= $year)) {
1223 for ($idx = $year; $idx < ($year + 11); $idx++) {
1224 $OUT .= "<option value=\"" . $idx."\"";
1225 if ($default == $idx) $OUT .= ' selected="selected"';
1226 $OUT .= ">" . $idx."</option>\n";
1228 } elseif ($default == -1) {
1229 // Current year minus 1
1230 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1232 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1235 // Get current year and subtract the configured minimum age
1236 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1237 // Calculate earliest year depending on extension version
1238 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1239 // Use configured minimum age
1240 $year = date('Y', time()) - getConfig('min_age');
1242 // Use fixed 16 years age
1243 $year = date('Y', time()) - 16;
1246 // Construct year selection list
1247 for ($idx = $minYear; $idx <= $year; $idx++) {
1248 $OUT .= "<option value=\"" . $idx."\"";
1249 if ($default == $idx) $OUT .= ' selected="selected"';
1250 $OUT .= ">" . $idx."</option>\n";
1257 for ($idx = '0'; $idx < 60; $idx+=5) {
1258 if (strlen($idx) == 1) $idx = '0' . $idx;
1259 $OUT .= "<option value=\"" . $idx."\"";
1260 if ($default == $idx) $OUT .= ' selected="selected"';
1261 $OUT .= ">" . $idx."</option>\n";
1266 for ($idx = '0'; $idx < 24; $idx++) {
1267 if (strlen($idx) == 1) $idx = '0' . $idx;
1268 $OUT .= "<option value=\"" . $idx."\"";
1269 if ($default == $idx) $OUT .= ' selected="selected"';
1270 $OUT .= ">" . $idx."</option>\n";
1275 $OUT .= "<option value=\"Y\"";
1276 if ($default == 'Y') $OUT .= ' selected="selected"';
1277 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1278 if ($default != 'Y') $OUT .= ' selected="selected"';
1279 $OUT .= ">{--NO--}</option>\n";
1282 $OUT .= " </select>\n";
1287 // Deprecated : $length
1290 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1291 // Build server string
1292 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1295 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1296 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1297 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1298 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1299 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1301 // Build string from misc data
1302 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1304 // Add more additional data
1305 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1307 // Add referal id, language, theme and userid
1308 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1309 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1310 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1311 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1313 // Calculate number for generating the code
1314 $a = $code + getConfig('_ADD') - 1;
1316 if (isConfigEntrySet('master_salt')) {
1317 // Generate hash with master salt from modula of number with the prime number and other data
1318 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, getConfig('master_salt'));
1320 // Create number from hash
1321 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1323 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1324 $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')));
1326 // Create number from hash
1327 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1330 // At least 10 numbers shall be secure enought!
1331 $len = getConfig('code_length');
1332 if ($len == '0') $len = $length;
1333 if ($len == '0') $len = 10;
1335 // Cut off requested counts of number
1336 $return = substr(str_replace('.', '', $rcode), 0, $len);
1338 // Done building code
1342 // Does only allow numbers
1343 function bigintval ($num, $castValue = true) {
1344 // Filter all numbers out
1345 $ret = preg_replace('/[^0123456789]/', '', $num);
1348 if ($castValue === true) $ret = (double)$ret;
1350 // Has the whole value changed?
1351 if ('' . $ret . '' != '' . $num . '') {
1353 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1360 // Insert the code in $img_code into jpeg or PNG image
1361 function generateImageOrCode ($img_code, $headerSent = true) {
1362 // Is the code size oversized or shouldn't we display it?
1363 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1364 // Stop execution of function here because of over-sized code length
1365 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1366 } elseif ($headerSent === false) {
1367 // Return an HTML code here
1368 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1372 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1375 getConfig('img_type')
1379 if (isFileReadable($img)) {
1380 // Switch image type
1381 switch (getConfig('img_type'))
1384 // Okay, load image and hide all errors
1385 $image = imagecreatefromjpeg($img);
1389 // Okay, load image and hide all errors
1390 $image = imagecreatefrompng($img);
1394 // Exit function here
1395 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1399 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1400 $text_color = imagecolorallocate($image, 0, 0, 0);
1402 // Insert code into image
1403 imagestring($image, 5, 14, 2, $img_code, $text_color);
1405 // Return to browser
1406 sendHeader('Content-Type: image/' . getConfig('img_type'));
1408 // Output image with matching image factory
1409 switch (getConfig('img_type')) {
1410 case 'jpg': imagejpeg($image); break;
1411 case 'png': imagepng($image); break;
1414 // Remove image from memory
1415 imagedestroy($image);
1417 // Create selection box or array of splitted timestamp
1418 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1419 // Calculate 2-seconds timestamp
1420 $stamp = round($timestamp);
1421 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1423 // Do we have a leap year?
1425 $TEST = date('Y', time()) / 4;
1426 $M1 = date('m', time());
1427 $M2 = date('m', (time() + $timestamp));
1429 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1430 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1432 // First of all years...
1433 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1434 //* DEBUG: */ print("Y={$Y}<br />");
1436 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1437 //* DEBUG: */ print("M={$M}<br />");
1439 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1440 //* DEBUG: */ print("W={$W}<br />");
1442 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1443 //* DEBUG: */ print("D={$D}<br />");
1445 $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));
1446 //* DEBUG: */ print("h={$h}<br />");
1448 $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));
1449 //* DEBUG: */ print("m={$m}<br />");
1450 // And at last seconds...
1451 $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));
1452 //* DEBUG: */ print("s={$s}<br />");
1454 // Is seconds zero and time is < 60 seconds?
1455 if (($s == '0') && ($timestamp < 60)) {
1457 $s = round($timestamp);
1461 // Now we convert them in seconds...
1463 if ($return_array) {
1464 // Just put all data in an array for later use
1476 $OUT = "<div align=\"" . $align."\">\n";
1477 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1480 if (ereg('Y', $display) || (empty($display))) {
1481 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1484 if (ereg('M', $display) || (empty($display))) {
1485 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1488 if (ereg("W", $display) || (empty($display))) {
1489 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1492 if (ereg("D", $display) || (empty($display))) {
1493 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1496 if (ereg("h", $display) || (empty($display))) {
1497 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1500 if (ereg('m', $display) || (empty($display))) {
1501 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1504 if (ereg("s", $display) || (empty($display))) {
1505 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1511 if (ereg('Y', $display) || (empty($display))) {
1512 // Generate year selection
1513 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1514 for ($idx = '0'; $idx <= 10; $idx++) {
1515 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1516 if ($idx == $Y) $OUT .= ' selected="selected"';
1517 $OUT .= ">" . $idx."</option>\n";
1519 $OUT .= " </select></td>\n";
1521 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1524 if (ereg('M', $display) || (empty($display))) {
1525 // Generate month selection
1526 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1527 for ($idx = '0'; $idx <= 11; $idx++)
1529 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1530 if ($idx == $M) $OUT .= ' selected="selected"';
1531 $OUT .= ">" . $idx."</option>\n";
1533 $OUT .= " </select></td>\n";
1535 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1538 if (ereg("W", $display) || (empty($display))) {
1539 // Generate week selection
1540 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1541 for ($idx = '0'; $idx <= 4; $idx++) {
1542 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1543 if ($idx == $W) $OUT .= ' selected="selected"';
1544 $OUT .= ">" . $idx."</option>\n";
1546 $OUT .= " </select></td>\n";
1548 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1551 if (ereg("D", $display) || (empty($display))) {
1552 // Generate day selection
1553 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1554 for ($idx = '0'; $idx <= 31; $idx++) {
1555 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1556 if ($idx == $D) $OUT .= ' selected="selected"';
1557 $OUT .= ">" . $idx."</option>\n";
1559 $OUT .= " </select></td>\n";
1561 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1564 if (ereg("h", $display) || (empty($display))) {
1565 // Generate hour selection
1566 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1567 for ($idx = '0'; $idx <= 23; $idx++) {
1568 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1569 if ($idx == $h) $OUT .= ' selected="selected"';
1570 $OUT .= ">" . $idx."</option>\n";
1572 $OUT .= " </select></td>\n";
1574 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1577 if (ereg('m', $display) || (empty($display))) {
1578 // Generate minute selection
1579 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1580 for ($idx = '0'; $idx <= 59; $idx++) {
1581 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1582 if ($idx == $m) $OUT .= ' selected="selected"';
1583 $OUT .= ">" . $idx."</option>\n";
1585 $OUT .= " </select></td>\n";
1587 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1590 if (ereg("s", $display) || (empty($display))) {
1591 // Generate second selection
1592 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1593 for ($idx = '0'; $idx <= 59; $idx++) {
1594 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1595 if ($idx == $s) $OUT .= ' selected="selected"';
1596 $OUT .= ">" . $idx."</option>\n";
1598 $OUT .= " </select></td>\n";
1600 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1603 $OUT .= "</table>\n";
1605 // Return generated HTML code
1611 function createTimestampFromSelections ($prefix, $postData) {
1612 // Initial return value
1615 // Do we have a leap year?
1617 $TEST = date('Y', time()) / 4;
1618 $M1 = date('m', time());
1619 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1620 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1621 // First add years...
1622 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1624 $ret += $postData[$prefix."_mo"] * 2628000;
1626 $ret += $postData[$prefix."_we"] * 604800;
1628 $ret += $postData[$prefix."_da"] * 86400;
1630 $ret += $postData[$prefix."_ho"] * 3600;
1632 $ret += $postData[$prefix."_mi"] * 60;
1633 // And at last seconds...
1634 $ret += $postData[$prefix."_se"];
1635 // Return calculated value
1639 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1640 function createFancyTime ($stamp) {
1641 // Get data array with years/months/weeks/days/...
1642 $data = createTimeSelections($stamp, '', '', '', true);
1644 foreach($data as $k => $v) {
1646 // Value is greater than 0 "eval" data to return string
1647 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1652 // Do we have something there?
1653 if (strlen($ret) > 0) {
1654 // Remove leading commata and space
1655 $ret = substr($ret, 2);
1658 $ret = "0 {--_SECONDS--}";
1661 // Return fancy time string
1665 // Generates a navigation row for listing emails
1666 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1667 $SEP = ''; $TOP = '';
1668 if ($show_form === false) {
1670 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1674 for ($page = 1; $page <= $PAGES; $page++) {
1675 // Is the page currently selected or shall we generate a link to it?
1676 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1677 // Is currently selected, so only highlight it
1678 $NAV .= '<strong>-';
1680 // Open anchor tag and add base URL
1681 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1683 // Add userid when we shall show all mails from a single member
1684 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1686 // Close open anchor tag
1690 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1691 // Is currently selected, so only highlight it
1692 $NAV .= '-</strong>';
1698 // Add seperator if we have not yet reached total pages
1699 if ($page < $PAGES) $NAV .= ' | ';
1702 // Define constants only once
1703 $content['nav'] = $NAV;
1704 $content['span'] = $colspan;
1705 $content['top'] = $TOP;
1706 $content['sep'] = $SEP;
1708 // Load navigation template
1709 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1711 if ($return === true) {
1712 // Return generated HTML-Code
1720 // Extract host from script name
1721 function extractHostnameFromUrl (&$script) {
1722 // Use default SERVER_URL by default... ;) So?
1723 $url = getConfig('SERVER_URL');
1725 // Is this URL valid?
1726 if (substr($script, 0, 7) == 'http://') {
1727 // Use the hostname from script URL as new hostname
1728 $url = substr($script, 7);
1729 $extract = explode('/', $url);
1731 // Done extracting the URL :)
1734 // Extract host name
1735 $host = str_replace('http://', '', $url);
1736 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1738 // Generate relative URL
1739 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1740 if (substr(strtolower($script), 0, 7) == 'http://') {
1741 // But only if http:// is in front!
1742 $script = substr($script, (strlen($url) + 7));
1743 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1745 $script = substr($script, (strlen($url) + 8));
1748 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1749 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1755 // Send a GET request
1756 function sendGetRequest ($script, $data = array()) {
1757 // Extract host name from script
1758 $host = extractHostnameFromUrl($script);
1761 $scriptData = http_build_query($data, '', '&');
1763 // Do we have a question-mark in the script?
1764 if (strpos($script, '?') === false) {
1765 // No, so first char must be question mark
1766 $scriptData = '?' . $scriptData;
1769 $scriptData = '&' . $scriptData;
1773 $script .= $scriptData;
1775 // Generate GET request header
1776 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1777 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1778 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1779 if (isConfigEntrySet('FULL_VERSION')) {
1780 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1782 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1784 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1785 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1786 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1788 // Send the raw request
1789 $response = sendRawRequest($host, $request);
1791 // Return the result to the caller function
1795 // Send a POST request
1796 function sendPostRequest ($script, $postData) {
1797 // Is postData an array?
1798 if (!is_array($postData)) {
1800 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1801 return array('', '', '');
1804 // Extract host name from script
1805 $host = extractHostnameFromUrl($script);
1807 // Construct request
1808 $data = http_build_query($postData, '', '&');
1810 // Generate POST request header
1811 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1812 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1813 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1814 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1815 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1816 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1817 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1818 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1821 // Send the raw request
1822 $response = sendRawRequest($host, $request);
1824 // Return the result to the caller function
1828 // Sends a raw request to another host
1829 function sendRawRequest ($host, $request) {
1830 // Init errno and errdesc with 'all fine' values
1831 $errno = '0'; $errdesc = '';
1834 $response = array('', '', '');
1836 // Default is not to use proxy
1839 // Are proxy settins set?
1840 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1846 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1847 if ($useProxy === true) {
1848 // Connect to host through proxy connection
1849 $fp = @fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1851 // Connect to host directly
1852 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1856 if (!is_resource($fp)) {
1862 if ($useProxy === true) {
1863 // Generate CONNECT request header
1864 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1865 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1867 // Use login data to proxy? (username at least!)
1868 if (getConfig('proxy_username') != '') {
1870 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
1871 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1874 // Add last new-line
1875 $proxyTunnel .= getConfig('HTTP_EOL');
1876 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1879 fputs($fp, $proxyTunnel);
1883 // No response received
1887 // Read the first line
1888 $resp = trim(fgets($fp, 10240));
1889 $respArray = explode(' ', $resp);
1890 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1891 // Invalid response!
1897 fputs($fp, $request);
1900 while (!feof($fp)) {
1901 $response[] = trim(fgets($fp, 1024));
1907 // Skip first empty lines
1909 foreach ($resp as $idx => $line) {
1911 $line = trim($line);
1913 // Is this line empty?
1916 array_shift($response);
1918 // Abort on first non-empty line
1923 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1925 // Proxy agent found?
1926 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1927 // Proxy header detected, so remove two lines
1928 array_shift($response);
1929 array_shift($response);
1932 // Was the request successfull?
1933 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1934 // Not found / access forbidden
1935 $response = array('', '', '');
1942 // Taken from www.php.net eregi() user comments
1943 function isEmailValid ($email) {
1944 // Check first part of email address
1945 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1948 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1951 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1953 // Return check result
1954 return preg_match($regex, $email);
1957 // Function taken from user comments on www.php.net / function eregi()
1958 function isUrlValid ($URL, $compile=true) {
1959 // Trim URL a little
1960 $URL = trim(urldecode($URL));
1961 //* DEBUG: */ outputHtml($URL.'<br />');
1963 // Compile some chars out...
1964 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1965 //* DEBUG: */ outputHtml($URL.'<br />');
1967 // Check for the extension filter
1968 if (isExtensionActive('filter')) {
1969 // Use the extension's filter set
1970 return FILTER_VALIDATE_URL($URL, false);
1973 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1974 // https:// in front of the URLs
1975 return isUrlValidSimple($URL);
1978 // Generate a list of administrative links to a given userid
1979 function generateMemberAdminActionLinks ($userid, $status = '') {
1980 // Make sure userid is a number
1981 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1983 // Define all main targets
1984 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1986 // Begin of navigation links
1989 foreach ($targetArray as $tar) {
1990 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1991 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1992 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1993 // Locked accounts shall be unlocked
1994 $OUT .= 'UNLOCK_USER';
1996 // All other status is fine
1997 $OUT .= strtoupper($tar);
1999 $OUT .= "_TITLE--}\">{--ADMIN_";
2000 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2001 // Locked accounts shall be unlocked
2002 $OUT .= 'UNLOCK_USER';
2004 // All other status is fine
2005 $OUT .= strtoupper($tar);
2007 $OUT .= "--}</a></span> | ";
2010 // Finish navigation link
2011 $OUT = substr($OUT, 0, -7) . ']';
2017 // Generate an email link
2018 function generateEmailLink ($email, $table = 'admins') {
2019 // Default email link (INSECURE! Spammer can read this by harvester programs)
2020 $EMAIL = 'mailto:' . $email;
2022 // Check for several extensions
2023 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2024 // Create email link for contacting admin in guest area
2025 $EMAIL = generateAdminEmailLink($email);
2026 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2027 // Create email link for contacting a member within admin area (or later in other areas, too?)
2028 $EMAIL = generateUserEmailLink($email, 'admin');
2029 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2030 // Create email link to contact sponsor within admin area (or like the link above?)
2031 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2034 // Shall I close the link when there is no admin?
2035 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2037 // Return email link
2041 // Generate a hash for extra-security for all passwords
2042 function generateHash ($plainText, $salt = '') {
2043 // Is the required extension 'sql_patches' there and a salt is not given?
2044 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2045 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2046 return md5($plainText);
2049 // Do we miss an arry element here?
2050 if (!isConfigEntrySet('file_hash')) {
2052 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2055 // When the salt is empty build a new one, else use the first x configured characters as the salt
2057 // Build server string (inc/databases.php is no longer updated with every commit)
2058 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2061 $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');
2064 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2066 // Calculate number for generating the code
2067 $a = time() + getConfig('_ADD') - 1;
2069 // Generate SHA1 sum from modula of number and the prime number
2070 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2071 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2072 $sha1 = scrambleString($sha1);
2073 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2074 //* DEBUG: */ $sha1b = descrambleString($sha1);
2075 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2077 // Generate the password salt string
2078 $salt = substr($sha1, 0, getConfig('salt_length'));
2079 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2082 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2083 $salt = substr($salt, 0, getConfig('salt_length'));
2084 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2086 // Sanity check on salt
2087 if (strlen($salt) != getConfig('salt_length')) {
2089 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2094 return $salt.sha1($salt . $plainText);
2097 // Scramble a string
2098 function scrambleString($str) {
2102 // Final check, in case of failture it will return unscrambled string
2103 if (strlen($str) > 40) {
2104 // The string is to long
2106 } elseif (strlen($str) == 40) {
2108 $scrambleNums = explode(':', getConfig('pass_scramble'));
2110 // Generate new numbers
2111 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2114 // Scramble string here
2115 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2116 for ($idx = '0'; $idx < strlen($str); $idx++) {
2117 // Get char on scrambled position
2118 $char = substr($str, $scrambleNums[$idx], 1);
2120 // Add it to final output string
2121 $scrambled .= $char;
2124 // Return scrambled string
2125 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2129 // De-scramble a string scrambled by scrambleString()
2130 function descrambleString($str) {
2131 // Scramble only 40 chars long strings
2132 if (strlen($str) != 40) return $str;
2134 // Load numbers from config
2135 $scrambleNums = explode(':', getConfig('pass_scramble'));
2138 if (count($scrambleNums) != 40) return $str;
2140 // Begin descrambling
2141 $orig = str_repeat(' ', 40);
2142 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2143 for ($idx = '0'; $idx < 40; $idx++) {
2144 $char = substr($str, $idx, 1);
2145 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2148 // Return scrambled string
2149 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2153 // Generated a "string" for scrambling
2154 function genScrambleString ($len) {
2155 // Prepare array for the numbers
2156 $scrambleNumbers = array();
2158 // First we need to setup randomized numbers from 0 to 31
2159 for ($idx = '0'; $idx < $len; $idx++) {
2161 $rand = mt_rand(0, ($len -1));
2163 // Check for it by creating more numbers
2164 while (array_key_exists($rand, $scrambleNumbers)) {
2165 $rand = mt_rand(0, ($len -1));
2169 $scrambleNumbers[$rand] = $rand;
2172 // So let's create the string for storing it in database
2173 $scrambleString = implode(':', $scrambleNumbers);
2174 return $scrambleString;
2177 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2178 function generatePassString ($passHash) {
2179 // Return vanilla password hash
2182 // Is a secret key and master salt already initialized?
2183 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2184 // Only calculate when the secret key is generated
2185 $newHash = ''; $start = 9;
2186 for ($idx = '0'; $idx < 10; $idx++) {
2187 $part1 = hexdec(substr($passHash, $start, 4));
2188 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2189 $mod = dechex($idx);
2190 if ($part1 > $part2) {
2191 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2192 } elseif ($part2 > $part1) {
2193 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2195 $mod = substr($mod, 0, 4);
2196 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2197 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2198 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2203 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2204 $ret = generateHash($newHash, getConfig('master_salt'));
2205 //* DEBUG: */ print('ret='.$ret.'<br />');
2208 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2209 $ret = md5($passHash);
2210 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2217 // Fix "deleted" cookies
2218 function fixDeletedCookies ($cookies) {
2219 // Is this an array with entries?
2220 if ((is_array($cookies)) && (count($cookies) > 0)) {
2221 // Then check all cookies if they are marked as deleted!
2222 foreach ($cookies as $cookieName) {
2223 // Is the cookie set to "deleted"?
2224 if (getSession($cookieName) == 'deleted') {
2225 setSession($cookieName, '');
2231 // Output error messages in a fasioned way and die...
2232 function app_die ($F, $L, $message) {
2233 // Check if Script is already dieing and not let it kill itself another 1000 times
2234 if (!isset($GLOBALS['app_died'])) {
2235 // Make sure, that the script realy realy diese here and now
2236 $GLOBALS['app_died'] = true;
2239 loadIncludeOnce('inc/header.php');
2241 // Rewrite message for output
2242 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2244 // Better log this message away
2245 logDebugMessage($F, $L, $message);
2247 // Load the message template
2248 loadTemplate('admin_settings_saved', false, $message);
2251 loadIncludeOnce('inc/footer.php');
2253 // Script tried to kill itself twice
2254 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2258 // Display parsing time and number of SQL queries in footer
2259 function displayParsingTime() {
2260 // Is the timer started?
2261 if (!isset($GLOBALS['startTime'])) {
2267 $endTime = microtime(true);
2269 // "Explode" both times
2270 $start = explode(' ', $GLOBALS['startTime']);
2271 $end = explode(' ', $endTime);
2272 $runTime = $end[0] - $start[0];
2273 if ($runTime < 0) $runTime = '0';
2277 'runtime' => translateComma($runTime),
2278 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2281 // Load the template
2282 loadTemplate('show_timings', false, $content);
2285 // Check wether a boolean constant is set
2286 // Taken from user comments in PHP documentation for function constant()
2287 function isBooleanConstantAndTrue ($constName) { // : Boolean
2288 // Failed by default
2292 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2294 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2295 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2298 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2299 if (defined($constName)) {
2301 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2302 $res = (constant($constName) === true);
2306 $GLOBALS['cache_array']['const'][$constName] = $res;
2308 //* DEBUG: */ var_dump($res);
2314 // Checks if a given apache module is loaded
2315 function isApacheModuleLoaded ($apacheModule) {
2316 // Check it and return result
2317 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2320 // Get current theme name
2321 function getCurrentTheme () {
2322 // The default theme is 'default'... ;-)
2325 // Load default theme if not empty from configuration
2326 if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
2328 if (!isSessionVariableSet('mxchange_theme')) {
2329 // Set default theme
2331 } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
2332 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2333 // Get theme from cookie
2334 $ret = getSession('mxchange_theme');
2337 if (getThemeId($ret) == '0') {
2338 // Fix it to default
2341 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
2342 // Prepare FQFN for checking
2343 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
2345 // Installation mode active
2346 if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
2347 // Set cookie from URL data
2348 setTheme(getRequestElement('theme'));
2349 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
2350 // Set cookie from posted data
2351 setTheme(SQL_ESCAPE(postRequestElement('theme')));
2355 $ret = getSession('mxchange_theme');
2357 // Invalid design, reset cookie
2361 // Return theme value
2365 // Setter for theme in session
2366 function setTheme ($newTheme) {
2367 setSession('mxchange_theme', $newTheme);
2370 // Get id from theme
2371 // @TODO Try to move this to inc/libs/theme_functions.php
2372 function getThemeId ($name) {
2373 // Is the extension 'theme' installed?
2374 if (!isExtensionActive('theme')) {
2382 // Is the cache entry there?
2383 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2384 // Get the version from cache
2385 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2388 incrementStatsEntry('cache_hits');
2389 } elseif (getExtensionVersion('cache') != '0.1.8') {
2390 // Check if current theme is already imported or not
2391 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
2392 array($name), __FUNCTION__, __LINE__);
2395 if (SQL_NUMROWS($result) == 1) {
2397 list($id) = SQL_FETCHROW($result);
2401 SQL_FREERESULT($result);
2408 // Generates an error code from given account status
2409 function generateErrorCodeFromUserStatus ($status='') {
2410 // If no status is provided, use the default, cached
2411 if ((empty($status)) && (isMember())) {
2413 $status = getUserData('status');
2416 // Default error code if unknown account status
2417 $errorCode = getCode('UNKNOWN_STATUS');
2419 // Generate constant name
2420 $codeName = sprintf("ID_%s", $status);
2422 // Is the constant there?
2423 if (isCodeSet($codeName)) {
2425 $errorCode = getCode($codeName);
2428 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2431 // Return error code
2435 // Function to search for the last modifified file
2436 function searchDirsRecursive ($dir, &$last_changed) {
2438 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2439 // Does it match what we are looking for? (We skip a lot files already!)
2440 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2441 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2442 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2443 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2445 // Walk through all entries
2446 foreach ($ds as $d) {
2447 // Generate proper FQFN
2448 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2450 // Is it a file and readable?
2451 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2452 if (isDirectory($FQFN)) {
2453 // $FQFN is a directory so also crawl into this directory
2455 if (!empty($dir)) $newDir = $dir . '/'. $d;
2456 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2457 searchDirsRecursive($newDir, $last_changed);
2458 } elseif (isFileReadable($FQFN)) {
2459 // $FQFN is a filename and no directory
2460 $time = filemtime($FQFN);
2461 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2462 if ($last_changed['time'] < $time) {
2463 // This file is newer as the file before
2464 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2465 $last_changed['path_name'] = $FQFN;
2466 $last_changed['time'] = $time;
2472 // "Getter" for revision/version data
2473 function getActualVersion ($type = 'Revision') {
2474 // By default nothing is new... ;-)
2477 // Is the cache entry there?
2478 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2479 // Found so increase cache hit
2480 incrementStatsEntry('cache_hits');
2483 return $GLOBALS['cache_array']['revision'][$type][0];
2485 // FQFN of revision file
2486 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2488 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2489 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2490 // Forced rebuild of .revision file
2493 // Check for revision file
2494 if (!isFileReadable($FQFN)) {
2495 // Not found, so we need to create it
2498 // Revision file found
2499 $ins_vers = explode("\n", readFromFile($FQFN));
2501 // Get array for mapping information
2502 $mapper = array_flip(getSearchFor());
2503 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2505 // Is the content valid?
2506 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2507 // File needs update!
2510 // Generate fake cache entry
2511 foreach ($mapper as $map=>$idx) {
2512 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2515 // Return found value
2516 return trim($ins_vers[$mapper[$type]]);
2521 // Has it been updated?
2522 if ($new === true) {
2524 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2526 // ... and call recursive
2527 return getActualVersion($type);
2532 // Repares an array we are looking for
2533 // 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
2534 function getSearchFor () {
2535 // Add Revision, Date, Tag and Author
2536 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2538 // Return the created array
2542 // @TODO Please describe this function
2543 function getArrayFromActualVersion () {
2547 // Directory to start with search
2548 $last_changed = array(
2553 // Init return array
2554 $akt_vers = array();
2556 // Init value for counting the founded keywords
2559 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2560 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2563 $last_file = readFromFile($last_changed['path_name']);
2565 // Get all the keywords to search for
2566 $searchFor = getSearchFor();
2568 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2569 foreach ($searchFor as $search) {
2570 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2571 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2572 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2573 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2576 // Save the last-changed filename for debugging
2577 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2579 // at least 3 keyword-Tags are needed for propper values
2580 if ($res && $res >= 3
2581 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2582 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2583 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2584 // Prepare content witch need special treadment
2586 // Prepare timestamp for date
2587 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2588 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2590 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2591 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2592 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2596 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2597 $version = sendGetRequest('check-updates3.php');
2600 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2601 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2602 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2603 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2604 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2605 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2608 // Return prepared array
2609 return $GLOBALS['cache_array']['revision'];
2612 // Back-ported from the new ship-simu engine. :-)
2613 function debug_get_printable_backtrace () {
2615 $backtrace = "<ol>\n";
2617 // Get and prepare backtrace for output
2618 $backtraceArray = debug_backtrace();
2619 foreach ($backtraceArray as $key => $trace) {
2620 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2621 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2622 if (!isset($trace['args'])) $trace['args'] = array();
2623 $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";
2627 $backtrace .= "</ol>\n";
2629 // Return the backtrace
2633 // Output a debug backtrace to the user
2634 function debug_report_bug ($message = '') {
2635 // Is this already called?
2636 if (isset($GLOBALS[__FUNCTION__])) {
2638 print 'Message:'.$message.'<br />Backtrace:<pre>';
2639 debug_print_backtrace();
2643 // Set this function as called
2644 $GLOBALS[__FUNCTION__] = true;
2649 // Is the optional message set?
2650 if (!empty($message)) {
2652 $debug = sprintf("Note: %s<br />\n",
2656 // @TODO Add a little more infos here
2657 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2661 $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>";
2662 $debug .= debug_get_printable_backtrace();
2663 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2664 $debug .= "Thank you for finding bugs.";
2667 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2671 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2672 function generateSeed () {
2673 list($usec, $sec) = explode(' ', microtime());
2674 $microTime = (((float)$sec + (float)$usec)) * 100000;
2678 // Converts a message code to a human-readable message
2679 function getMessageFromErrorCode ($code) {
2683 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2684 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2685 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2686 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2687 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2688 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2689 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2690 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2691 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2692 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2693 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2694 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2695 case getCode('ID_GUEST') : $message = getMessage('LOGIN_ID_GUEST'); break;
2696 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2697 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2698 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2699 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2700 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2701 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2702 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2703 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2704 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2705 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2706 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2707 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2708 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2709 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2710 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2711 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2713 case getCode('ERROR_MAILID'):
2714 if (isExtensionActive('mailid', true)) {
2715 $message = getMessage('ERROR_CONFIRMING_MAIL');
2717 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2721 case getCode('EXTENSION_PROBLEM'):
2722 if (isGetRequestElementSet('ext')) {
2723 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2725 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2729 case getCode('URL_TLOCK'):
2730 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2731 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2733 // Load timestamp from last order
2734 list($timestamp) = SQL_FETCHROW($result);
2735 $timestamp = generateDateTime($timestamp, 1);
2738 SQL_FREERESULT($result);
2740 // Calculate hours...
2741 $STD = round(getConfig('url_tlock') / 60 / 60);
2744 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2747 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2749 // Finally contruct the message
2750 // @TODO Rewrite this old lost code to a template
2751 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2752 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2753 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2757 // Missing/invalid code
2758 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2761 logDebugMessage(__FUNCTION__, __LINE__, $message);
2765 // Return the message
2769 // Compile characters which are allowed in URLs
2770 function compileUriCode ($code, $simple = true) {
2771 // Compile constants
2772 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2774 // Compile QUOT and other non-HTML codes
2775 $code = str_replace('{DOT}', '.',
2776 str_replace('{SLASH}', '/',
2777 str_replace('{QUOT}', "'",
2778 str_replace('{DOLLAR}', '$',
2779 str_replace('{OPEN_ANCHOR}', '(',
2780 str_replace('{CLOSE_ANCHOR}', ')',
2781 str_replace('{OPEN_SQR}', '[',
2782 str_replace('{CLOSE_SQR}', ']',
2783 str_replace('{PER}', '%',
2787 // Return compiled code
2791 // Function taken from user comments on www.php.net / function eregi()
2792 function isUrlValidSimple ($url) {
2794 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2796 // Allows http and https
2797 $http = "(http|https)+(:\/\/)";
2799 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2800 // Test double-domains (e.g. .de.vu)
2801 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2803 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2805 $dir = "((/)+([-_\.[:alnum:]])+)*";
2807 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2808 // ... and the string after and including question character
2809 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2810 // Pattern for URLs like http://url/dir/doc.html?var=value
2811 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2812 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2813 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2814 // Pattern for URLs like http://url/dir/?var=value
2815 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2816 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2817 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2818 // Pattern for URLs like http://url/dir/page.ext
2819 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2820 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2821 $pattern['ipdp'] = $http . $ip . $dir . $page;
2822 // Pattern for URLs like http://url/dir
2823 $pattern['d1d'] = $http . $domain1 . $dir;
2824 $pattern['d2d'] = $http . $domain2 . $dir;
2825 $pattern['ipd'] = $http . $ip . $dir;
2826 // Pattern for URLs like http://url/?var=value
2827 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2828 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2829 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2830 // Pattern for URLs like http://url?var=value
2831 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2832 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2833 $pattern['ipg12'] = $http . $ip . $getstring1;
2834 // Test all patterns
2836 foreach ($pattern as $key => $pat) {
2838 if (isDebugRegExpressionEnabled()) {
2839 // @TODO Are these convertions still required?
2840 $pat = str_replace('.', "\.", $pat);
2841 $pat = str_replace('@', "\@", $pat);
2842 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2845 // Check if expression matches
2846 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2849 if ($reg === true) break;
2852 // Return true/false
2856 // Wtites data to a config.php-style file
2857 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2858 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2859 // Initialize some variables
2865 // Is the file there and read-/write-able?
2866 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2867 $search = 'CFG: ' . $comment;
2868 $tmp = $FQFN . '.tmp';
2870 // Open the source file
2871 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2873 // Is the resource valid?
2874 if (is_resource($fp)) {
2875 // Open temporary file
2876 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2878 // Is the resource again valid?
2879 if (is_resource($fp_tmp)) {
2880 // Mark temporary file as readable
2881 $GLOBALS['file_readable'][$tmp] = true;
2884 while (!feof($fp)) {
2885 // Read from source file
2886 $line = fgets ($fp, 1024);
2888 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2891 if ($next === $seek) {
2893 $line = $prefix . $DATA . $suffix . "\n";
2899 // Write to temp file
2900 fputs($fp_tmp, $line);
2906 // Finished writing tmp file
2910 // Close source file
2913 if (($done === true) && ($found === true)) {
2914 // Copy back tmp file and delete tmp :-)
2915 copyFileVerified($tmp, $FQFN, 0644);
2916 return removeFile($tmp);
2917 } elseif ($found === false) {
2918 outputHtml('<strong>CHANGE:</strong> 404!');
2920 outputHtml('<strong>TMP:</strong> UNDONE!');
2924 // File not found, not readable or writeable
2925 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2928 // An error was detected!
2931 // Send notification to admin
2932 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2933 if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
2935 sendAdminsEmails($subject, $templateName, $content, $userid);
2937 // Send out out-dated way
2938 $message = loadEmailTemplate($templateName, $content, $userid);
2939 sendAdminEmails($subject, $message);
2943 // Debug message logger
2944 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2945 // Is debug mode enabled?
2946 if ((isDebugModeEnabled()) || ($force === true)) {
2948 $message = str_replace("\r", '', str_replace("\n", '', $message));
2950 // Log this message away, we better don't call app_die() here to prevent an endless loop
2951 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2952 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2957 // Handle extra values
2958 function handleExtraValues ($filterFunction, $value, $extraValue) {
2959 // Default is the value itself
2962 // Do we have a special filter function?
2963 if (!empty($filterFunction)) {
2964 // Does the filter function exist?
2965 if (function_exists($filterFunction)) {
2966 // Do we have extra parameters here?
2967 if (!empty($extraValue)) {
2968 // Put both parameters in one new array by default
2969 $args = array($value, $extraValue);
2971 // If we have an array simply use it and pre-extend it with our value
2972 if (is_array($extraValue)) {
2973 // Make the new args array
2974 $args = merge_array(array($value), $extraValue);
2977 // Call the multi-parameter call-back
2978 $ret = call_user_func_array($filterFunction, $args);
2980 // One parameter call
2981 $ret = call_user_func($filterFunction, $value);
2990 // Converts timestamp selections into a timestamp
2991 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2992 // Init test variable
2996 // Get last three chars
2997 $test = substr($id, -3);
2999 // Improved way of checking! :-)
3000 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3001 // Found a multi-selection for timings?
3002 $test = substr($id, 0, -3);
3003 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)) {
3004 // Generate timestamp
3005 $postData[$test] = createTimestampFromSelections($test, $postData);
3006 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
3007 $GLOBALS['skip_config'][$test] = true;
3009 // Remove data from array
3010 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3011 unset($postData[$test . '_' . $rem]);
3022 // Reverts the german decimal comma into Computer decimal dot
3023 function convertCommaToDot ($str) {
3024 // Default float is not a float... ;-)
3027 // Which language is selected?
3028 switch (getLanguage()) {
3029 case 'de': // German language
3030 // Remove german thousand dots first
3031 $str = str_replace('.', '', $str);
3033 // Replace german commata with decimal dot and cast it
3034 $float = (float)str_replace(',', '.', $str);
3037 default: // US and so on
3038 // Remove thousand dots first and cast
3039 $float = (float)str_replace(',', '', $str);
3047 // Handle menu-depending failed logins and return the rendered content
3048 function handleLoginFailtures ($accessLevel) {
3049 // Default output is empty ;-)
3052 // Is the session data set?
3053 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3054 // Ignore zero values
3055 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3056 // Non-guest has login failures found, get both data and prepare it for template
3057 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3059 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3060 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3064 $OUT = loadTemplate('login_failures', true, $content);
3067 // Reset session data
3068 setSession('mxchange_' . $accessLevel.'_failures', '');
3069 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3072 // Return rendered content
3077 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3079 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3081 // Shall I remove the cache file?
3082 if (isCacheInstanceValid()) {
3084 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3086 $GLOBALS['cache_instance']->removeCacheFile($force);
3089 // Include file given?
3092 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3094 // Is the include there?
3095 if (isIncludeReadable($inc)) {
3096 // And rebuild it from scratch
3097 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3100 // Include not found!
3101 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3107 // Determines the real remote address
3108 function determineRealRemoteAddress () {
3109 // Is a proxy in use?
3110 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3112 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3113 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3114 // Yet, another proxy
3115 $address = $_SERVER['HTTP_CLIENT_IP'];
3117 // The regular address when no proxy was used
3118 $address = $_SERVER['REMOTE_ADDR'];
3121 // This strips out the real address from proxy output
3122 if (strstr($address, ',')) {
3123 $addressArray = explode(',', $address);
3124 $address = $addressArray[0];
3127 // Return the result
3131 // Adds a bonus mail to the queue
3132 // This is a high-level function!
3133 function addNewBonusMail ($data, $mode = '', $output=true) {
3134 // Use mode from data if not set and availble ;-)
3135 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3137 // Generate receiver list
3138 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3141 if (!empty($RECEIVER)) {
3142 // Add bonus mail to queue
3143 addBonusMailToQueue(
3155 // Mail inserted into bonus pool
3156 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3157 } elseif ($output) {
3158 // More entered than can be reached!
3159 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3162 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3166 // Determines referal id and sets it
3167 function determineReferalId () {
3168 // Skip this in non-html-mode and outside ref.php
3169 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3171 // Check if refid is set
3172 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3174 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3175 // The variable user comes from the click-counter script click.php and we only accept this here
3176 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3177 } elseif (isPostRequestElementSet('refid')) {
3178 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3179 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3180 } elseif (isGetRequestElementSet('refid')) {
3181 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3182 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3183 } elseif (isGetRequestElementSet('ref')) {
3184 // Set refid=ref (the referal link uses such variable)
3185 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3186 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3187 // Set session refid als global
3188 $GLOBALS['refid'] = bigintval(getSession('refid'));
3189 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
3190 // Select a random user which has confirmed enougth mails
3191 $GLOBALS['refid'] = determineRandomReferalId();
3192 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3193 // Set default refid as refid in URL
3194 $GLOBALS['refid'] = getConfig('def_refid');
3196 // No default id when sql_patches is not installed or none set
3197 $GLOBALS['refid'] = '0';
3200 // Set cookie when default refid > 0
3201 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3202 // Default is not found
3205 // Do we have nickname or userid set?
3206 if (isNicknameUsed($GLOBALS['refid'])) {
3207 // Nickname in URL, so load the id
3208 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3209 } elseif ($GLOBALS['refid'] > 0) {
3210 // Direct userid entered
3211 $found = fetchUserData($GLOBALS['refid']);
3214 // Is the record valid?
3215 if (($found === false) || (!isUserDataValid())) {
3216 // No, then reset referal id
3217 $GLOBALS['refid'] = getConfig('def_refid');
3221 setSession('refid', $GLOBALS['refid']);
3224 // Return determined refid
3225 return $GLOBALS['refid'];
3228 // Enables the reset mode and runs it
3229 function doReset () {
3230 // Enable the reset mode
3231 $GLOBALS['reset_enabled'] = true;
3234 runFilterChain('reset');
3237 // Our shutdown-function
3238 function shutdown () {
3239 // Call the filter chain 'shutdown'
3240 runFilterChain('shutdown', null);
3242 if (SQL_IS_LINK_UP()) {
3244 SQL_CLOSE(__FILE__, __LINE__);
3245 } elseif (!isInstallationPhase()) {
3247 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3250 // Stop executing here
3255 function initMemberId () {
3256 $GLOBALS['member_id'] = '0';
3259 // Setter for member id
3260 function setMemberId ($memberid) {
3261 // We should not set member id to zero
3262 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3265 $GLOBALS['member_id'] = bigintval($memberid);
3268 // Getter for member id or returns zero
3269 function getMemberId () {
3270 // Default member id
3273 // Is the member id set?
3274 if (isMemberIdSet()) {
3276 $memberid = $GLOBALS['member_id'];
3283 // Checks ether the member id is set
3284 function isMemberIdSet () {
3285 return (isset($GLOBALS['member_id']));
3288 // Handle message codes from URL
3289 function handleCodeMessage () {
3290 if (isGetRequestElementSet('code')) {
3291 // Default extension is 'unknown'
3294 // Is extension given?
3295 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3297 // Convert the 'code' parameter from URL to a human-readable message
3298 $message = getMessageFromErrorCode(getRequestElement('code'));
3300 // Load message template
3301 loadTemplate('message', false, $message);
3305 // Setter for extra title
3306 function setExtraTitle ($extraTitle) {
3307 $GLOBALS['extra_title'] = $extraTitle;
3310 // Getter for extra title
3311 function getExtraTitle () {
3312 // Is the extra title set?
3313 if (!isExtraTitleSet()) {
3314 // No, then abort here
3315 debug_report_bug('extra_title is not set!');
3319 return $GLOBALS['extra_title'];
3322 // Checks if the extra title is set
3323 function isExtraTitleSet () {
3324 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3327 // Generates a 'extension foo inactive' message
3328 function generateExtensionInactiveMessage ($ext_name) {
3329 // Is the extension empty?
3330 if (empty($ext_name)) {
3331 // This should not happen
3332 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3336 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3338 // Is an admin logged in?
3340 // Then output admin message
3341 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3344 // Return prepared message
3348 // Generates a 'extension foo not installed' message
3349 function generateExtensionNotInstalledMessage ($ext_name) {
3350 // Is the extension empty?
3351 if (empty($ext_name)) {
3352 // This should not happen
3353 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3357 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3359 // Is an admin logged in?
3361 // Then output admin message
3362 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3365 // Return prepared message
3369 // Generates a message depending on if the extension is not installed or not
3371 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3375 // Is the extension not installed or just deactivated?
3376 switch (isExtensionInstalled($ext_name)) {
3377 case true; // Deactivated!
3378 $message = generateExtensionInactiveMessage($ext_name);
3381 case false; // Not installed!
3382 $message = generateExtensionNotInstalledMessage($ext_name);
3385 default: // Should not happen!
3386 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3387 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3391 // Return the message
3395 // Reads a directory recursively by default and searches for files not matching
3396 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3397 // a whole directory.
3398 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3399 // Add default entries we should exclude
3400 $excludeArray[] = '.';
3401 $excludeArray[] = '..';
3402 $excludeArray[] = '.svn';
3403 $excludeArray[] = '.htaccess';
3405 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3410 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3413 while ($baseFile = readdir($dirPointer)) {
3414 // Exclude '.', '..' and entries in $excludeArray automatically
3415 if (in_array($baseFile, $excludeArray, true)) {
3417 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3421 // Construct include filename and FQFN
3422 $fileName = $baseDir . $baseFile;
3423 $FQFN = getConfig('PATH') . $fileName;
3425 // Remove double slashes
3426 $FQFN = str_replace('//', '/', $FQFN);
3428 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3429 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3430 // These Lines are only for debugging!!
3431 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3432 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3433 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3439 // Skip also files with non-matching prefix genericly
3440 if (($recursive === true) && (isDirectory($FQFN))) {
3441 // Is a redirectory so read it as well
3442 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3444 // And skip further processing
3446 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3448 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3450 } elseif (!isFileReadable($FQFN)) {
3451 // Not readable so skip it
3452 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3456 // Is the file a PHP script or other?
3457 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3458 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3459 // Is this a valid include file?
3460 if ($extension == '.php') {
3461 // Remove both for extension name
3462 $extName = substr($baseFile, strlen($prefix), -4);
3464 // Is the extension valid and active?
3465 if (isExtensionNameValid($extName)) {
3466 // Then add this file
3467 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3468 $files[] = $fileName;
3470 // Add non-extension files as well
3471 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3472 if ($addBaseDir === true) {
3473 $files[] = $fileName;
3475 $files[] = $baseFile;
3479 // We found .php file but should not search for them, why?
3480 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3482 } elseif (substr($baseFile, -4, 4) == $extension) {
3483 // Other, generic file found
3484 $files[] = $fileName;
3489 closedir($dirPointer);
3494 // Return array with include files
3495 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3499 // Maps a module name into a database table name
3500 function mapModuleToTable ($moduleName) {
3501 // Map only these, still lame code...
3502 switch ($moduleName) {
3503 // 'index' is the guest's menu
3504 case 'index': $moduleName = 'guest'; break;
3505 // ... and 'login' the member's menu
3506 case 'login': $moduleName = 'member'; break;
3507 // Anything else will not be mapped, silently.
3514 // Add SQL debug data to array for later output
3515 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3516 // Already executed?
3517 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3518 // Then abort here, we don't need to profile a query twice
3522 // Remeber this as profiled (or not, but we don't care here)
3523 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3525 // Do we have cache?
3526 if (!isset($GLOBALS['debug_sql_available'])) {
3527 // Check it and cache it in $GLOBALS
3528 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3531 // Don't execute anything here if we don't need or ext-other is missing
3532 if ($GLOBALS['debug_sql_available'] === false) {
3538 'num_rows' => SQL_NUMROWS($result),
3539 'affected' => SQL_AFFECTEDROWS(),
3540 'sql_str' => $sqlString,
3541 'timing' => $timing,
3542 'file' => basename($F),
3547 $GLOBALS['debug_sqls'][] = $record;
3550 // Initializes the cache instance
3551 function initCacheInstance () {
3552 // Load include for CacheSystem class
3553 loadIncludeOnce('inc/classes/cachesystem.class.php');
3555 // Initialize cache system only when it's needed
3556 $GLOBALS['cache_instance'] = new CacheSystem();
3557 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3558 // Failed to initialize cache sustem
3559 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3563 // Getter for message from array or raw message
3564 function getMessageFromIndexedArray ($message, $pos, $array) {
3565 // Check if the requested message was found in array
3566 if (isset($array[$pos])) {
3567 // ... if yes then use it!
3568 $ret = $array[$pos];
3570 // ... else use default message
3578 // Print code with line numbers
3579 function linenumberCode ($code) {
3580 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3581 $count_lines = count($codeE);
3583 $r = 'Line | Code:<br />';
3584 foreach($codeE as $line => $c) {
3585 $r .= '<div class="line"><span class="linenum">';
3586 if ($count_lines == 1) {
3589 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3594 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3597 return '<div class="code">' . $r . '</div>';
3600 // Convert ';' to ', ' for e.g. receiver list
3601 function convertReceivers ($old) {
3602 return str_replace(';', ', ', $old);
3605 // Determines the right page title
3606 function determinePageTitle () {
3607 // Config and database connection valid?
3608 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3612 // Title decoration enabled?
3613 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
3615 // Do we have some extra title?
3616 if (isExtraTitleSet()) {
3618 $TITLE .= getExtraTitle() . ' by ';
3622 $TITLE .= getConfig('MAIN_TITLE');
3624 // Add title of module? (middle decoration will also be added!)
3625 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3626 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3629 // Add title from what file
3631 if (getModule() == 'login') $mode = 'member';
3632 elseif (getModule() == 'index') $mode = 'guest';
3633 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= " ".trim(getConfig('title_middle'))." ".getModuleDescription($mode, getWhat());
3635 // Add title decorations? (right)
3636 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= " ".trim(getConfig('title_right'));
3638 // Remember title in constant for the template
3639 $pageTitle = $TITLE;
3640 } elseif ((isInstalled()) && (isAdminRegistered())) {
3641 // Installed, admin registered but no ext-sql_patches
3642 $pageTitle = '[-- ' . getConfig('MAIN_TITLE').' - '.getModuleTitle(getModule()) . ' --]';
3643 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3644 // Installed but no admin registered
3645 $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
3646 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3647 // Installation mode
3648 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3650 // Configuration not found!
3651 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3653 // Do not add the fatal message in installation mode
3654 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3661 // Checks wethere there is a cache file there. This function is cached.
3662 function isTemplateCached ($template) {
3663 // Do we have cached this result?
3664 if (!isset($GLOBALS['template_cache'][$template])) {
3666 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3669 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3673 return $GLOBALS['template_cache'][$template];
3676 // Flushes non-flushed template cache to disk
3677 function flushTemplateCache ($template, $eval) {
3678 // Is this cache flushed?
3679 if ((!isTemplateCached($template)) && ($eval != '404')) {
3681 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3683 // Replace username with a call
3684 $eval = str_replace('$username', '".getUsername()."', $eval);
3687 writeToFile($FQFN, $eval, true);
3691 // Reads a template cache
3692 function readTemplateCache ($template) {
3694 if (isTemplateCached($template)) {
3696 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3699 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3703 return $GLOBALS['template_eval'][$template];
3706 //////////////////////////////////////////////////
3707 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3708 //////////////////////////////////////////////////
3710 if (!function_exists('html_entity_decode')) {
3711 // Taken from documentation on www.php.net
3712 function html_entity_decode ($string) {
3713 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3714 $trans_tbl = array_flip($trans_tbl);
3715 return strtr($string, $trans_tbl);
3719 if (!function_exists('http_build_query')) {
3720 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3721 function http_build_query($data, $prefix='', $sep='', $key='') {
3723 foreach ((array)$data as $k => $v) {
3724 if (is_int($k) && $prefix != null) {
3725 $k = urlencode($prefix . $k);
3728 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3730 if (is_array($v) || is_object($v)) {
3731 array_push($ret, http_build_query($v, '', $sep, $k));
3733 array_push($ret, $k.'='.urlencode($v));
3737 if (empty($sep)) $sep = ini_get('arg_separator.output');
3739 return implode($sep, $ret);