2 /************************************************************************
3 * Mailer v0.2.1-FINAL 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 === true) 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(escapeQuotes($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.
187 print(str_replace('{BACK}', "\\", $htmlCode));
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, 'Fatal error 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);
260 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
263 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
264 $extraPath = detectExtraTemplatePath($template);;
266 ////////////////////////
267 // Generate file name //
268 ////////////////////////
269 $FQFN = $basePath . $extraPath . $template . '.tpl';
271 // Does the special template exists?
272 if (!isFileReadable($FQFN)) {
273 // Reset to default template
274 $FQFN = $basePath . $template . '.tpl';
277 // Now does the final template exists?
278 if (isFileReadable($FQFN)) {
279 // Count the template load
280 incrementConfigEntry('num_templates');
282 // The local file does exists so we load it. :)
283 $GLOBALS['tpl_content'] = readFromFile($FQFN);
285 // Do we have to compile the code?
287 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
288 // Normal HTML output?
289 if (getOutputMode() == '0') {
290 // Add surrounding HTML comments to help finding bugs faster
291 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
293 // Prepare eval() command
294 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
295 } elseif (substr($template, 0, 3) == 'js_') {
296 // JavaScripts don't like entities and timings
297 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
299 // Prepare eval() command, other output doesn't like entities, maybe
300 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
303 // Add surrounding HTML comments to help finding bugs faster
304 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
305 $eval = '$ret = "' . escapeQuotes($ret) . '";';
308 // Cache the eval() command here
309 $GLOBALS['template_eval'][$template] = $eval;
312 eval($GLOBALS['template_eval'][$template]);
313 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
314 // Only admins shall see this warning or when installation mode is active
315 $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
316 (' . $template . ')<br />
318 {--TEMPLATE_CONTENT--}
319 <pre>' . print_r($content, true) . '</pre>
321 <pre>' . print_r($DATA, true) . '</pre>
325 $GLOBALS['template_eval'][$template] = '404';
329 eval($GLOBALS['template_eval'][$template]);
332 // Do we have some content to output or return?
334 // Not empty so let's put it out! ;)
335 if ($return === true) {
336 // Return the HTML code
342 } elseif (isDebugModeEnabled()) {
343 // Warning, empty output!
344 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
348 // Detects the extra template path from given template name
349 function detectExtraTemplatePath ($template) {
354 if (!isset($GLOBALS['extra_path'][$template])) {
355 // Check for admin/guest/member/etc. templates
356 if (substr($template, 0, 6) == 'admin_') {
357 // Admin template found
358 $extraPath = 'admin/';
359 } elseif (substr($template, 0, 6) == 'guest_') {
360 // Guest template found
361 $extraPath = 'guest/';
362 } elseif (substr($template, 0, 7) == 'member_') {
363 // Member template found
364 $extraPath = 'member/';
365 } elseif (substr($template, 0, 7) == 'select_') {
366 // Selection template found
367 $extraPath = 'select/';
368 } elseif (substr($template, 0, 8) == 'install_') {
369 // Installation template found
370 $extraPath = 'install/';
371 } elseif (substr($template, 0, 4) == 'ext_') {
372 // Extension template found
374 } elseif (substr($template, 0, 3) == 'la_') {
375 // 'Logical-area' template found
377 } elseif (substr($template, 0, 3) == 'js_') {
378 // JavaScript template found
380 } elseif (substr($template, 0, 5) == 'menu_') {
381 // Menu template found
382 $extraPath = 'menu/';
384 // Test for extension
385 $test = substr($template, 0, strpos($template, '_'));
387 // Probe for valid extension name
388 if (isExtensionNameValid($test)) {
389 // Set extra path to extension's name
390 $extraPath = $test . '/';
395 $GLOBALS['extra_path'][$template] = $extraPath;
399 return $GLOBALS['extra_path'][$template];
402 // Loads an email template and compiles it
403 function loadEmailTemplate ($template, $content = array(), $UID = '0') {
406 // Make sure all template names are lowercase!
407 $template = strtolower($template);
409 // Default 'nickname' if extension is not installed
412 // Prepare IP number and User Agent
413 $REMOTE_ADDR = detectRemoteAddr();
414 $HTTP_USER_AGENT = detectUserAgent();
417 $ADMIN = getConfig('MAIN_TITLE');
419 // Is the admin logged in?
422 $adminId = getCurrentAdminId();
425 $ADMIN = getAdminEmail($adminId);
428 // Neutral email address is default
429 $email = getConfig('WEBMASTER');
431 // Expiration in a nice output format
432 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
433 if (getConfig('auto_purge') == '0') {
434 // Will never expire!
435 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
437 // Create nice date string
438 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
441 // Is content an array?
442 if (is_array($content)) {
443 // Add expiration to array, $EXPIRATION is now deprecated!
444 $content['expiration'] = $EXPIRATION;
448 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content).'<br />');
449 if (($UID > 0) && (is_array($content))) {
450 // If nickname extension is installed, fetch nickname as well
451 if ((isExtensionActive('nickname')) && (isNicknameUsed($UID))) {
452 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
454 fetchUserData($UID, 'nickname');
456 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
461 // Merge data if valid
462 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
463 if (isUserDataValid()) {
464 $content = merge_array($content, getUserDataArray());
466 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
469 // Translate M to male or F to female if present
470 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
472 // Overwrite email from data if present
473 if (isset($content['email'])) $email = $content['email'];
475 // Store email for some functions in global data array
476 // @TODO Do only use $contentn, not $DATA or raw variables
477 $DATA['email'] = $email;
480 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
483 $extraPath = detectExtraTemplatePath($template);
485 // Generate full FQFN
486 $FQFN = $basePath . $extraPath . $template . '.tpl';
488 // Does the special template exists?
489 if (!isFileReadable($FQFN)) {
490 // Reset to default template
491 $FQFN = $basePath . $template . '.tpl';
494 // Now does the final template exists?
496 if (isFileReadable($FQFN)) {
497 // The local file does exists so we load it. :)
498 $GLOBALS['tpl_content'] = readFromFile($FQFN);
501 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileRawCode(escapeQuotes($GLOBALS['tpl_content']))."\");";
502 eval($GLOBALS['tpl_content']);
503 } elseif (!empty($template)) {
504 // Template file not found!
505 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
506 {--TEMPLATE_CONTENT--}
507 <pre>' . print_r($content, true) . '</pre>
509 <pre>' . print_r($DATA, true) . '</pre>
512 // Debug mode not active? Then remove the HTML tags
513 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
515 // No template name supplied!
516 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
519 // Is there some content?
520 if (empty($newContent)) {
522 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
524 // Add last error if the required function exists
525 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
528 // Remove content and data
536 // Send mail out to an email address
537 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
538 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
540 // Compile subject line (for POINTS constant etc.)
541 eval("\$subject = decodeEntities(\"".compileRawCode(escapeQuotes($subject))."\");");
544 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
545 // Value detected, is the message extension installed?
546 // @TODO Extension 'msg' does not exist
547 if (isExtensionActive('msg')) {
548 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
551 // Does the user exist?
552 if (fetchUserData($toEmail)) {
554 $toEmail = getUserData('email');
557 $toEmail = getConfig('WEBMASTER');
560 } elseif ($toEmail == '0') {
562 $toEmail = getConfig('WEBMASTER');
564 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
566 // Check for PHPMailer or debug-mode
567 if (!checkPhpMailerUsage()) {
568 // Not in PHPMailer-Mode
569 if (empty($mailHeader)) {
570 // Load email header template
571 $mailHeader = loadEmailTemplate('header');
574 $mailHeader .= loadEmailTemplate('header');
576 } elseif (isDebugModeEnabled()) {
577 if (empty($mailHeader)) {
578 // Load email header template
579 $mailHeader = loadEmailTemplate('header');
582 $mailHeader .= loadEmailTemplate('header');
587 eval("\$toEmail = \"".compileRawCode(escapeQuotes($toEmail))."\";");
590 eval("\$message = \"".compileRawCode(escapeQuotes($message))."\";");
592 // Fix HTML parameter (default is no!)
593 if (empty($isHtml)) $isHtml = 'N';
594 if (isDebugModeEnabled()) {
595 // In debug mode we want to display the mail instead of sending it away so we can debug this part
597 Headers : ' . str_replace('<', '<', str_replace('>', '>', secureString(trim($mailHeader)))) . '
598 To : ' . $toEmail . '
599 Subject : ' . $subject . '
600 Message : ' . $message . '
602 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
603 // Send mail as HTML away
604 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
605 } elseif (!empty($toEmail)) {
607 sendRawEmail($toEmail, $subject, $message, $mailHeader);
608 } elseif ($isHtml != 'Y') {
610 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
614 // Check to use wether legacy mail() command or PHPMailer class
615 // @TODO Rewrite this to an extension 'smtp'
617 function checkPhpMailerUsage() {
618 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
621 // Send out a raw email with PHPMailer class or legacy mail() command
622 function sendRawEmail ($toEmail, $subject, $message, $from) {
623 // Just compile all again, to put out all configs, etc.
624 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
625 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
626 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
627 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
629 // Shall we use PHPMailer class or legacy mode?
630 if (checkPhpMailerUsage()) {
631 // Use PHPMailer class with SMTP enabled
632 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
633 loadIncludeOnce('inc/phpmailer/class.smtp.php');
636 $mail = new PHPMailer();
638 // Set charset to UTF-8
639 $mail->CharSet('UTF-8');
641 // Path for PHPMailer
642 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
645 $mail->SMTPAuth = true;
646 $mail->Host = getConfig('SMTP_HOSTNAME');
648 $mail->Username = getConfig('SMTP_USER');
649 $mail->Password = getConfig('SMTP_PASSWORD');
651 $mail->From = getConfig('WEBMASTER');
655 $mail->FromName = getConfig('MAIN_TITLE');
656 $mail->Subject = $subject;
657 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
658 $mail->Body = $message;
659 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
660 $mail->WordWrap = 70;
663 $mail->Body = decodeEntities($message);
665 $mail->AddAddress($toEmail, '');
666 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
667 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
668 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
671 // Use legacy mail() command
672 mail($toEmail, $subject, decodeEntities($message), $from);
676 // Generate a password in a specified length or use default password length
677 function generatePassword ($length = '0') {
678 // Auto-fix invalid length of zero
679 if ($length == '0') $length = getConfig('pass_len');
681 // Initialize array with all allowed chars
682 $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,-,+,_,/,.');
684 // Start creating password
686 for ($i = '0'; $i < $length; $i++) {
687 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
690 // When the size is below 40 we can also add additional security by scrambling
691 // it. Otherwise we may corrupt hashes
692 if (strlen($PASS) <= 40) {
693 // Also scramble the password
694 $PASS = scrambleString($PASS);
697 // Return the password
701 // Generates a human-readable timestamp from the Uni* stamp
702 function generateDateTime ($time, $mode = '0') {
703 // Filter out numbers
704 $time = bigintval($time);
706 // If the stamp is zero it mostly didn't "happen"
709 return getMessage('NEVER_HAPPENED');
712 switch (getLanguage()) {
713 case 'de': // German date / time format
715 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
716 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
717 case '2': $ret = date('d.m.Y|H:i', $time); break;
718 case '3': $ret = date('d.m.Y', $time); break;
720 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
725 default: // Default is the US date / time format!
727 case '0': $ret = date('r', $time); break;
728 case '1': $ret = date('Y-m-d - g:i A', $time); break;
729 case '2': $ret = date('y-m-d|H:i', $time); break;
730 case '3': $ret = date('y-m-d', $time); break;
732 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
741 // Translates Y/N to yes/no
742 function translateYesNo ($yn) {
744 $translated = '??? (' . $yn . ')';
746 case 'Y': $translated = getMessage('YES'); break;
747 case 'N': $translated = getMessage('NO'); break;
750 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
758 // Translates the "pool type" into human-readable
759 function translatePoolType ($type) {
760 // Default?type is unknown
761 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
764 $constName = sprintf("POOL_TYPE_%s", $type);
767 if (isMessageIdValid($constName)) {
769 $translated = getMessage($constName);
772 // Return "translation"
776 // Translates the american decimal dot into a german comma
777 function translateComma ($dotted, $cut = true, $max = '0') {
778 // Default is 3 you can change this in admin area "Misc -> Misc Options"
779 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
781 // Use from config is default
782 $maxComma = getConfig('max_comma');
784 // Use from parameter?
785 if ($max > 0) $maxComma = $max;
788 if (($cut === true) && ($max == '0')) {
789 // Test for commata if in cut-mode
790 $com = explode('.', $dotted);
791 if (count($com) < 2) {
792 // Don't display commatas even if there are none... ;-)
798 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
801 switch (getLanguage()) {
802 case 'de': // German language
803 $dotted = number_format($dotted, $maxComma, ',', '.');
806 default: // All others
807 $dotted = number_format($dotted, $maxComma, '.', ',');
811 // Return translated value
815 // Translate Uni*-like gender to human-readable
816 function translateGender ($gender) {
818 $ret = '!' . $gender . '!';
820 // Male/female or company?
822 case 'M': $ret = getMessage('GENDER_M'); break;
823 case 'F': $ret = getMessage('GENDER_F'); break;
824 case 'C': $ret = getMessage('GENDER_C'); break;
826 // Log unknown gender
827 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
831 // Return translated gender
835 // "Translates" the user status
836 function translateUserStatus ($status) {
837 // Generate message depending on status
842 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
847 $ret = getMessage('ACCOUNT_DELETED');
851 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
852 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
860 // Generates an URL for the dereferer
861 function generateDerefererUrl ($URL) {
862 // Don't de-refer our own links!
863 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
864 // De-refer this link
865 $URL = '{?URL?}/modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
872 // Generates an URL for the frametester
873 function generateFrametesterUrl ($URL) {
874 // Prepare frametester URL
875 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
876 encodeString(compileUriCode($URL))
879 // Return the new URL
880 return $frametesterUrl;
883 // Count entries from e.g. a selection box
884 function countSelection ($array) {
886 if (!is_array($array)) {
888 debug_report_bug(__FUNCTION__.': No array provided.');
895 foreach ($array as $key => $selected) {
897 if (!empty($selected)) $ret++;
900 // Return counted selections
904 // Generate XHTML code for the CAPTCHA
905 function generateCaptchaCode ($code, $type, $DATA, $userid) {
906 return '<img border="0" alt="Code ' . $code . '" src="{?URL?}/mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
909 // Generates a timestamp (some wrapper for mktime())
910 function makeTime ($hours, $minutes, $seconds, $stamp) {
911 // Extract day, month and year from given timestamp
912 $days = date('d', $stamp);
913 $months = date('m', $stamp);
914 $years = date('Y', $stamp);
916 // Create timestamp for wished time which depends on extracted date
927 // Redirects to an URL and if neccessarry extends it with own base URL
928 function redirectToUrl ($URL) {
930 eval('$URL = "' . compileRawCode($URL) . '";');
932 // Check if http(s):// is there
933 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
934 // Make all URLs full-qualified
935 $URL = getConfig('URL') . '/' . $URL;
938 // Three different debug ways...
939 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
940 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
941 //* DEBUG: */ die($URL);
943 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
944 $rel = ' rel="external"';
946 // Do we have internal or external URL?
947 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
948 // Own (=internal) URL
953 $GLOBALS['output'] = ob_get_contents();
955 // Clear it only if there is content
956 if (!empty($GLOBALS['output'])) {
960 // Simple probe for bots/spiders from search engines
961 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
962 // Secure the URL against bad things such als HTML insertions and so on...
963 $URL = secureString($URL);
965 // Output new location link as anchor
966 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
967 } elseif (!headers_sent()) {
968 //* DEBUG: */ debug_report_bug("URL={$URL}");
969 // Clear own output buffer
970 $GLOBALS['output'] = '';
972 // Load URL when headers are not sent
973 sendHeader('Location: '.str_replace('&', '&', $URL));
975 // Output error message
976 loadInclude('inc/header.php');
977 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
978 loadInclude('inc/footer.php');
981 // Shut the mailer down here
985 // Wrapper for redirectToUrl but URL comes from a configuration entry
986 function redirectToConfiguredUrl ($configEntry) {
988 $URL = getConfig($configEntry);
993 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1000 // Compiles the given HTML/mail code
1001 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1002 // Is the code a string?
1003 if (!is_string($code)) {
1004 // Silently return it
1009 $startCompile = microtime(true);
1012 $code = compileRawCode($code, $simple, $constants, $full);
1015 $compiled = microtime(true);
1018 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1020 // Return compiled code
1024 // Compiles the code (use compileCode() only for HTML because of the comments)
1025 // @TODO $simple is deprecated
1026 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1027 // Is the code a string?
1028 if (!is_string($code)) {
1029 // Silently return it
1033 // Init replacement-array with smaller set of security characters
1034 $secChars = $GLOBALS['url_chars'];
1036 // Select full set of chars to replace when we e.g. want to compile URLs
1037 if ($full === true) $secChars = $GLOBALS['security_chars'];
1039 // Compile more through a filter
1040 $code = runFilterChain('compile_code', $code);
1042 // Compile constants
1043 if ($constants === true) {
1044 // BEFORE 0.2.1 : Language and data constants
1045 // WITH 0.2.1+ : Only language constants
1046 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1048 // BEFORE 0.2.1 : Not used
1049 // WITH 0.2.1+ : Data constants
1050 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1053 // Compile QUOT and other non-HTML codes
1054 foreach ($secChars['to'] as $k => $to) {
1055 // Do the reversed thing as in inc/libs/security_functions.php
1056 $code = str_replace($to, $secChars['from'][$k], $code);
1059 // Find $content[bla][blub] entries
1060 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1061 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1063 // Are some matches found?
1064 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1065 // Replace all matches
1066 $matchesFound = array();
1067 foreach ($matches[0] as $key => $match) {
1068 // Fuzzy look has failed by default
1069 $fuzzyFound = false;
1071 // Fuzzy look on match if already found
1072 foreach ($matchesFound as $found => $set) {
1074 $test = substr($found, 0, strlen($match));
1076 // Does this entry exist?
1077 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1078 if ($test == $match) {
1080 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1087 if ($fuzzyFound === true) continue;
1089 // Take all string elements
1090 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1091 // Replace it in the code
1092 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1093 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1094 $code = str_replace($match, '".' . $newMatch . '."', $code);
1095 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1096 $matchesFound[$match] = 1;
1097 } elseif (!isset($matchesFound[$match])) {
1098 // Not yet replaced!
1099 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1100 $code = str_replace($match, '".' . $match . '."', $code);
1101 $matchesFound[$match] = 1;
1110 /************************************************************************
1112 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1113 * $a_sort sortiert: *
1115 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1116 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1117 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1118 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1119 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1121 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1122 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1123 * Sie, dass es doch nicht so schwer ist! :-) *
1125 ************************************************************************/
1126 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1128 while ($primary_key < count($a_sort)) {
1129 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1130 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1132 if ($nums === false) {
1133 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1134 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1135 } elseif ($key != $key2) {
1136 // Sort numbers (E.g.: 9 < 10)
1137 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1138 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1142 // We have found two different values, so let's sort whole array
1143 foreach ($dummy as $sort_key => $sort_val) {
1144 $t = $dummy[$sort_key][$key];
1145 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1146 $dummy[$sort_key][$key2] = $t;
1157 // Write back sorted array
1162 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1165 if ($type == 'yn') {
1166 // This is a yes/no selection only!
1167 if ($id > 0) $prefix .= "[" . $id."]";
1168 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1170 // Begin with regular selection box here
1171 if (!empty($prefix)) $prefix .= "_";
1173 if ($id > 0) $type2 .= "[" . $id."]";
1174 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1179 for ($idx = 1; $idx < 32; $idx++) {
1180 $OUT .= "<option value=\"" . $idx."\"";
1181 if ($default == $idx) $OUT .= ' selected="selected"';
1182 $OUT .= ">" . $idx."</option>\n";
1186 case 'month': // Month
1187 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1188 $OUT .= "<option value=\"" . $month."\"";
1189 if ($default == $month) $OUT .= ' selected="selected"';
1190 $OUT .= ">" . $descr."</option>\n";
1194 case 'year': // Year
1196 $year = date('Y', time());
1198 // Use configured min age or fixed?
1199 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1201 $startYear = $year - getConfig('min_age');
1204 $startYear = $year - 16;
1207 // Calculate earliest year (100 years old people can still enter Internet???)
1208 $minYear = $year - 100;
1210 // Check if the default value is larger than minimum and bigger than actual year
1211 if (($default > $minYear) && ($default >= $year)) {
1212 for ($idx = $year; $idx < ($year + 11); $idx++) {
1213 $OUT .= "<option value=\"" . $idx."\"";
1214 if ($default == $idx) $OUT .= ' selected="selected"';
1215 $OUT .= ">" . $idx."</option>\n";
1217 } elseif ($default == -1) {
1218 // Current year minus 1
1219 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1221 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1224 // Get current year and subtract the configured minimum age
1225 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1226 // Calculate earliest year depending on extension version
1227 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1228 // Use configured minimum age
1229 $year = date('Y', time()) - getConfig('min_age');
1231 // Use fixed 16 years age
1232 $year = date('Y', time()) - 16;
1235 // Construct year selection list
1236 for ($idx = $minYear; $idx <= $year; $idx++) {
1237 $OUT .= "<option value=\"" . $idx."\"";
1238 if ($default == $idx) $OUT .= ' selected="selected"';
1239 $OUT .= ">" . $idx."</option>\n";
1246 for ($idx = '0'; $idx < 60; $idx+=5) {
1247 if (strlen($idx) == 1) $idx = '0' . $idx;
1248 $OUT .= "<option value=\"" . $idx."\"";
1249 if ($default == $idx) $OUT .= ' selected="selected"';
1250 $OUT .= ">" . $idx."</option>\n";
1255 for ($idx = '0'; $idx < 24; $idx++) {
1256 if (strlen($idx) == 1) $idx = '0' . $idx;
1257 $OUT .= "<option value=\"" . $idx."\"";
1258 if ($default == $idx) $OUT .= ' selected="selected"';
1259 $OUT .= ">" . $idx."</option>\n";
1264 $OUT .= "<option value=\"Y\"";
1265 if ($default == 'Y') $OUT .= ' selected="selected"';
1266 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1267 if ($default != 'Y') $OUT .= ' selected="selected"';
1268 $OUT .= ">{--NO--}</option>\n";
1271 $OUT .= " </select>\n";
1276 // Deprecated : $length
1279 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1280 // Build server string
1281 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1284 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1285 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1286 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1287 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1288 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1290 // Build string from misc data
1291 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1293 // Add more additional data
1294 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1296 // Add referal id, language, theme and userid
1297 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1298 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1299 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1300 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1302 // Calculate number for generating the code
1303 $a = $code + getConfig('_ADD') - 1;
1305 if (isConfigEntrySet('master_salt')) {
1306 // Generate hash with master salt from modula of number with the prime number and other data
1307 $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'));
1309 // Create number from hash
1310 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1312 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1313 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, getConfig('salt_length')));
1315 // Create number from hash
1316 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1319 // At least 10 numbers shall be secure enought!
1320 $len = getConfig('code_length');
1321 if ($len == '0') $len = $length;
1322 if ($len == '0') $len = 10;
1324 // Cut off requested counts of number
1325 $return = substr(str_replace('.', '', $rcode), 0, $len);
1327 // Done building code
1331 // Does only allow numbers
1332 function bigintval ($num, $castValue = true) {
1333 // Filter all numbers out
1334 $ret = preg_replace('/[^0123456789]/', '', $num);
1337 if ($castValue === true) $ret = (double)$ret;
1339 // Has the whole value changed?
1340 if ('' . $ret . '' != '' . $num . '') {
1342 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1349 // Insert the code in $img_code into jpeg or PNG image
1350 function generateImageOrCode ($img_code, $headerSent = true) {
1351 // Is the code size oversized or shouldn't we display it?
1352 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1353 // Stop execution of function here because of over-sized code length
1354 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1355 } elseif ($headerSent === false) {
1356 // Return an HTML code here
1357 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1361 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1364 getConfig('img_type')
1368 if (isFileReadable($img)) {
1369 // Switch image type
1370 switch (getConfig('img_type'))
1373 // Okay, load image and hide all errors
1374 $image = imagecreatefromjpeg($img);
1378 // Okay, load image and hide all errors
1379 $image = imagecreatefrompng($img);
1383 // Exit function here
1384 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1388 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1389 $text_color = imagecolorallocate($image, 0, 0, 0);
1391 // Insert code into image
1392 imagestring($image, 5, 14, 2, $img_code, $text_color);
1394 // Return to browser
1395 sendHeader('Content-Type: image/' . getConfig('img_type'));
1397 // Output image with matching image factory
1398 switch (getConfig('img_type')) {
1399 case 'jpg': imagejpeg($image); break;
1400 case 'png': imagepng($image); break;
1403 // Remove image from memory
1404 imagedestroy($image);
1406 // Create selection box or array of splitted timestamp
1407 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1408 // Calculate 2-seconds timestamp
1409 $stamp = round($timestamp);
1410 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1412 // Do we have a leap year?
1414 $TEST = date('Y', time()) / 4;
1415 $M1 = date('m', time());
1416 $M2 = date('m', (time() + $timestamp));
1418 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1419 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1421 // First of all years...
1422 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1423 //* DEBUG: */ print("Y={$Y}<br />");
1425 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1426 //* DEBUG: */ print("M={$M}<br />");
1428 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1429 //* DEBUG: */ print("W={$W}<br />");
1431 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1432 //* DEBUG: */ print("D={$D}<br />");
1434 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24) - $W * 7 * 24 - $D * 24));
1435 //* DEBUG: */ print("h={$h}<br />");
1437 $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1438 //* DEBUG: */ print("m={$m}<br />");
1439 // And at last seconds...
1440 $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1441 //* DEBUG: */ print("s={$s}<br />");
1443 // Is seconds zero and time is < 60 seconds?
1444 if (($s == '0') && ($timestamp < 60)) {
1446 $s = round($timestamp);
1450 // Now we convert them in seconds...
1452 if ($return_array) {
1453 // Just put all data in an array for later use
1465 $OUT = "<div align=\"" . $align."\">\n";
1466 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"timebox_table dashed\">\n";
1469 if (ereg('Y', $display) || (empty($display))) {
1470 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1473 if (ereg('M', $display) || (empty($display))) {
1474 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1477 if (ereg('W', $display) || (empty($display))) {
1478 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1481 if (ereg('D', $display) || (empty($display))) {
1482 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1485 if (ereg('h', $display) || (empty($display))) {
1486 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1489 if (ereg('m', $display) || (empty($display))) {
1490 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1493 if (ereg('s', $display) || (empty($display))) {
1494 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1500 if (ereg('Y', $display) || (empty($display))) {
1501 // Generate year selection
1502 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1503 for ($idx = '0'; $idx <= 10; $idx++) {
1504 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1505 if ($idx == $Y) $OUT .= ' selected="selected"';
1506 $OUT .= ">" . $idx."</option>\n";
1508 $OUT .= " </select></td>\n";
1510 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1513 if (ereg('M', $display) || (empty($display))) {
1514 // Generate month selection
1515 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1516 for ($idx = '0'; $idx <= 11; $idx++)
1518 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1519 if ($idx == $M) $OUT .= ' selected="selected"';
1520 $OUT .= ">" . $idx."</option>\n";
1522 $OUT .= " </select></td>\n";
1524 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1527 if (ereg('W', $display) || (empty($display))) {
1528 // Generate week selection
1529 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1530 for ($idx = '0'; $idx <= 4; $idx++) {
1531 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1532 if ($idx == $W) $OUT .= ' selected="selected"';
1533 $OUT .= ">" . $idx."</option>\n";
1535 $OUT .= " </select></td>\n";
1537 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1540 if (ereg('D', $display) || (empty($display))) {
1541 // Generate day selection
1542 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1543 for ($idx = '0'; $idx <= 31; $idx++) {
1544 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1545 if ($idx == $D) $OUT .= ' selected="selected"';
1546 $OUT .= ">" . $idx."</option>\n";
1548 $OUT .= " </select></td>\n";
1550 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\" />\n";
1553 if (ereg('h', $display) || (empty($display))) {
1554 // Generate hour selection
1555 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1556 for ($idx = '0'; $idx <= 23; $idx++) {
1557 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1558 if ($idx == $h) $OUT .= ' selected="selected"';
1559 $OUT .= ">" . $idx."</option>\n";
1561 $OUT .= " </select></td>\n";
1563 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\" />\n";
1566 if (ereg('m', $display) || (empty($display))) {
1567 // Generate minute selection
1568 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1569 for ($idx = '0'; $idx <= 59; $idx++) {
1570 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1571 if ($idx == $m) $OUT .= ' selected="selected"';
1572 $OUT .= ">" . $idx."</option>\n";
1574 $OUT .= " </select></td>\n";
1576 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\" />\n";
1579 if (ereg('s', $display) || (empty($display))) {
1580 // Generate second selection
1581 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1582 for ($idx = '0'; $idx <= 59; $idx++) {
1583 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1584 if ($idx == $s) $OUT .= ' selected="selected"';
1585 $OUT .= ">" . $idx."</option>\n";
1587 $OUT .= " </select></td>\n";
1589 $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\" />\n";
1592 $OUT .= "</table>\n";
1594 // Return generated HTML code
1600 function createTimestampFromSelections ($prefix, $postData) {
1601 // Initial return value
1604 // Do we have a leap year?
1606 $TEST = date('Y', time()) / 4;
1607 $M1 = date('m', time());
1608 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1609 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
1610 // First add years...
1611 $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
1613 $ret += $postData[$prefix."_mo"] * 2628000;
1615 $ret += $postData[$prefix."_we"] * 604800;
1617 $ret += $postData[$prefix."_da"] * 86400;
1619 $ret += $postData[$prefix."_ho"] * 3600;
1621 $ret += $postData[$prefix."_mi"] * 60;
1622 // And at last seconds...
1623 $ret += $postData[$prefix."_se"];
1624 // Return calculated value
1628 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1629 function createFancyTime ($stamp) {
1630 // Get data array with years/months/weeks/days/...
1631 $data = createTimeSelections($stamp, '', '', '', true);
1633 foreach($data as $k => $v) {
1635 // Value is greater than 0 "eval" data to return string
1636 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1641 // Do we have something there?
1642 if (strlen($ret) > 0) {
1643 // Remove leading commata and space
1644 $ret = substr($ret, 2);
1647 $ret = "0 {--_SECONDS--}";
1650 // Return fancy time string
1654 // Generates a navigation row for listing emails
1655 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1656 $SEP = ''; $TOP = '';
1657 if ($show_form === false) {
1659 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1663 for ($page = 1; $page <= $PAGES; $page++) {
1664 // Is the page currently selected or shall we generate a link to it?
1665 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1666 // Is currently selected, so only highlight it
1667 $NAV .= '<strong>-';
1669 // Open anchor tag and add base URL
1670 $NAV .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1672 // Add userid when we shall show all mails from a single member
1673 if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1675 // Close open anchor tag
1679 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1680 // Is currently selected, so only highlight it
1681 $NAV .= '-</strong>';
1687 // Add seperator if we have not yet reached total pages
1688 if ($page < $PAGES) $NAV .= ' | ';
1691 // Define constants only once
1692 $content['nav'] = $NAV;
1693 $content['span'] = $colspan;
1694 $content['top'] = $TOP;
1695 $content['sep'] = $SEP;
1697 // Load navigation template
1698 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1700 if ($return === true) {
1701 // Return generated HTML-Code
1709 // Extract host from script name
1710 function extractHostnameFromUrl (&$script) {
1711 // Use default SERVER_URL by default... ;) So?
1712 $url = getConfig('SERVER_URL');
1714 // Is this URL valid?
1715 if (substr($script, 0, 7) == 'http://') {
1716 // Use the hostname from script URL as new hostname
1717 $url = substr($script, 7);
1718 $extract = explode('/', $url);
1720 // Done extracting the URL :)
1723 // Extract host name
1724 $host = str_replace('http://', '', $url);
1725 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1727 // Generate relative URL
1728 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1729 if (substr(strtolower($script), 0, 7) == 'http://') {
1730 // But only if http:// is in front!
1731 $script = substr($script, (strlen($url) + 7));
1732 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1734 $script = substr($script, (strlen($url) + 8));
1737 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1738 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1744 // Send a GET request
1745 function sendGetRequest ($script, $data = array()) {
1746 // Extract host name from script
1747 $host = extractHostnameFromUrl($script);
1750 $scriptData = http_build_query($data, '', '&');
1752 // Do we have a question-mark in the script?
1753 if (strpos($script, '?') === false) {
1754 // No, so first char must be question mark
1755 $scriptData = '?' . $scriptData;
1758 $scriptData = '&' . $scriptData;
1762 $script .= $scriptData;
1764 // Generate GET request header
1765 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1766 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1767 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1768 if (isConfigEntrySet('FULL_VERSION')) {
1769 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1771 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1773 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1774 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1775 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1777 // Send the raw request
1778 $response = sendRawRequest($host, $request);
1780 // Return the result to the caller function
1784 // Send a POST request
1785 function sendPostRequest ($script, $postData) {
1786 // Is postData an array?
1787 if (!is_array($postData)) {
1789 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1790 return array('', '', '');
1793 // Extract host name from script
1794 $host = extractHostnameFromUrl($script);
1796 // Construct request
1797 $data = http_build_query($postData, '', '&');
1799 // Generate POST request header
1800 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1801 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1802 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1803 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1804 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1805 $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1806 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1807 $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1810 // Send the raw request
1811 $response = sendRawRequest($host, $request);
1813 // Return the result to the caller function
1817 // Sends a raw request to another host
1818 function sendRawRequest ($host, $request) {
1819 // Init errno and errdesc with 'all fine' values
1820 $errno = '0'; $errdesc = '';
1823 $response = array('', '', '');
1825 // Default is not to use proxy
1828 // Are proxy settins set?
1829 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1835 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1836 if ($useProxy === true) {
1837 // Connect to host through proxy connection
1838 $fp = @fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1840 // Connect to host directly
1841 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1845 if (!is_resource($fp)) {
1851 if ($useProxy === true) {
1852 // Generate CONNECT request header
1853 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1854 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1856 // Use login data to proxy? (username at least!)
1857 if (getConfig('proxy_username') != '') {
1859 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
1860 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1863 // Add last new-line
1864 $proxyTunnel .= getConfig('HTTP_EOL');
1865 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1868 fputs($fp, $proxyTunnel);
1872 // No response received
1876 // Read the first line
1877 $resp = trim(fgets($fp, 10240));
1878 $respArray = explode(' ', $resp);
1879 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1880 // Invalid response!
1886 fputs($fp, $request);
1889 while (!feof($fp)) {
1890 $response[] = trim(fgets($fp, 1024));
1896 // Skip first empty lines
1898 foreach ($resp as $idx => $line) {
1900 $line = trim($line);
1902 // Is this line empty?
1905 array_shift($response);
1907 // Abort on first non-empty line
1912 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1914 // Proxy agent found?
1915 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1916 // Proxy header detected, so remove two lines
1917 array_shift($response);
1918 array_shift($response);
1921 // Was the request successfull?
1922 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1923 // Not found / access forbidden
1924 $response = array('', '', '');
1931 // Taken from www.php.net eregi() user comments
1932 function isEmailValid ($email) {
1933 // Check first part of email address
1934 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1937 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1940 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1942 // Return check result
1943 return preg_match($regex, $email);
1946 // Function taken from user comments on www.php.net / function eregi()
1947 function isUrlValid ($URL, $compile=true) {
1948 // Trim URL a little
1949 $URL = trim(urldecode($URL));
1950 //* DEBUG: */ outputHtml($URL.'<br />');
1952 // Compile some chars out...
1953 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1954 //* DEBUG: */ outputHtml($URL.'<br />');
1956 // Check for the extension filter
1957 if (isExtensionActive('filter')) {
1958 // Use the extension's filter set
1959 return FILTER_VALIDATE_URL($URL, false);
1962 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1963 // https:// in front of the URLs
1964 return isUrlValidSimple($URL);
1967 // Generate a list of administrative links to a given userid
1968 function generateMemberAdminActionLinks ($userid, $status = '') {
1969 // Make sure userid is a number
1970 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1972 // Define all main targets
1973 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1975 // Begin of navigation links
1978 foreach ($targetArray as $tar) {
1979 $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&what=" . $tar . "&userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
1980 //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
1981 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1982 // Locked accounts shall be unlocked
1983 $OUT .= 'UNLOCK_USER';
1985 // All other status is fine
1986 $OUT .= strtoupper($tar);
1988 $OUT .= "_TITLE--}\">{--ADMIN_";
1989 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1990 // Locked accounts shall be unlocked
1991 $OUT .= 'UNLOCK_USER';
1993 // All other status is fine
1994 $OUT .= strtoupper($tar);
1996 $OUT .= "--}</a></span> | ";
1999 // Finish navigation link
2000 $OUT = substr($OUT, 0, -7) . ']';
2006 // Generate an email link
2007 function generateEmailLink ($email, $table = 'admins') {
2008 // Default email link (INSECURE! Spammer can read this by harvester programs)
2009 $EMAIL = 'mailto:' . $email;
2011 // Check for several extensions
2012 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2013 // Create email link for contacting admin in guest area
2014 $EMAIL = generateAdminEmailLink($email);
2015 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2016 // Create email link for contacting a member within admin area (or later in other areas, too?)
2017 $EMAIL = generateUserEmailLink($email, 'admin');
2018 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2019 // Create email link to contact sponsor within admin area (or like the link above?)
2020 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2023 // Shall I close the link when there is no admin?
2024 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2026 // Return email link
2030 // Generate a hash for extra-security for all passwords
2031 function generateHash ($plainText, $salt = '') {
2032 // Is the required extension 'sql_patches' there and a salt is not given?
2033 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2034 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2035 return md5($plainText);
2038 // Do we miss an arry element here?
2039 if (!isConfigEntrySet('file_hash')) {
2041 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2044 // When the salt is empty build a new one, else use the first x configured characters as the salt
2046 // Build server string (inc/databases.php is no longer updated with every commit)
2047 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2050 $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');
2053 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2055 // Calculate number for generating the code
2056 $a = time() + getConfig('_ADD') - 1;
2058 // Generate SHA1 sum from modula of number and the prime number
2059 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2060 //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2061 $sha1 = scrambleString($sha1);
2062 //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2063 //* DEBUG: */ $sha1b = descrambleString($sha1);
2064 //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2066 // Generate the password salt string
2067 $salt = substr($sha1, 0, getConfig('salt_length'));
2068 //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
2071 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2072 $salt = substr($salt, 0, getConfig('salt_length'));
2073 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2075 // Sanity check on salt
2076 if (strlen($salt) != getConfig('salt_length')) {
2078 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2083 return $salt.sha1($salt . $plainText);
2086 // Scramble a string
2087 function scrambleString($str) {
2091 // Final check, in case of failture it will return unscrambled string
2092 if (strlen($str) > 40) {
2093 // The string is to long
2095 } elseif (strlen($str) == 40) {
2097 $scrambleNums = explode(':', getConfig('pass_scramble'));
2099 // Generate new numbers
2100 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2103 // Scramble string here
2104 //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
2105 for ($idx = '0'; $idx < strlen($str); $idx++) {
2106 // Get char on scrambled position
2107 $char = substr($str, $scrambleNums[$idx], 1);
2109 // Add it to final output string
2110 $scrambled .= $char;
2113 // Return scrambled string
2114 //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
2118 // De-scramble a string scrambled by scrambleString()
2119 function descrambleString($str) {
2120 // Scramble only 40 chars long strings
2121 if (strlen($str) != 40) return $str;
2123 // Load numbers from config
2124 $scrambleNums = explode(':', getConfig('pass_scramble'));
2127 if (count($scrambleNums) != 40) return $str;
2129 // Begin descrambling
2130 $orig = str_repeat(' ', 40);
2131 //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
2132 for ($idx = '0'; $idx < 40; $idx++) {
2133 $char = substr($str, $idx, 1);
2134 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2137 // Return scrambled string
2138 //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
2142 // Generated a "string" for scrambling
2143 function genScrambleString ($len) {
2144 // Prepare array for the numbers
2145 $scrambleNumbers = array();
2147 // First we need to setup randomized numbers from 0 to 31
2148 for ($idx = '0'; $idx < $len; $idx++) {
2150 $rand = mt_rand(0, ($len -1));
2152 // Check for it by creating more numbers
2153 while (array_key_exists($rand, $scrambleNumbers)) {
2154 $rand = mt_rand(0, ($len -1));
2158 $scrambleNumbers[$rand] = $rand;
2161 // So let's create the string for storing it in database
2162 $scrambleString = implode(':', $scrambleNumbers);
2163 return $scrambleString;
2166 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2167 function generatePassString ($passHash) {
2168 // Return vanilla password hash
2171 // Is a secret key and master salt already initialized?
2172 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2173 // Only calculate when the secret key is generated
2174 $newHash = ''; $start = 9;
2175 for ($idx = '0'; $idx < 10; $idx++) {
2176 $part1 = hexdec(substr($passHash, $start, 4));
2177 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2178 $mod = dechex($idx);
2179 if ($part1 > $part2) {
2180 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2181 } elseif ($part2 > $part1) {
2182 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2184 $mod = substr($mod, 0, 4);
2185 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2186 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2187 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2192 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2193 $ret = generateHash($newHash, getConfig('master_salt'));
2194 //* DEBUG: */ print('ret='.$ret.'<br />');
2197 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2198 $ret = md5($passHash);
2199 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2206 // Fix "deleted" cookies
2207 function fixDeletedCookies ($cookies) {
2208 // Is this an array with entries?
2209 if ((is_array($cookies)) && (count($cookies) > 0)) {
2210 // Then check all cookies if they are marked as deleted!
2211 foreach ($cookies as $cookieName) {
2212 // Is the cookie set to "deleted"?
2213 if (getSession($cookieName) == 'deleted') {
2214 setSession($cookieName, '');
2220 // Output error messages in a fasioned way and die...
2221 function app_die ($F, $L, $message) {
2222 // Check if Script is already dieing and not let it kill itself another 1000 times
2223 if (!isset($GLOBALS['app_died'])) {
2224 // Make sure, that the script realy realy diese here and now
2225 $GLOBALS['app_died'] = true;
2228 loadIncludeOnce('inc/header.php');
2230 // Rewrite message for output
2231 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2233 // Better log this message away
2234 logDebugMessage($F, $L, $message);
2236 // Load the message template
2237 loadTemplate('admin_settings_saved', false, $message);
2240 loadIncludeOnce('inc/footer.php');
2242 // Script tried to kill itself twice
2243 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2247 // Display parsing time and number of SQL queries in footer
2248 function displayParsingTime() {
2249 // Is the timer started?
2250 if (!isset($GLOBALS['startTime'])) {
2256 $endTime = microtime(true);
2258 // "Explode" both times
2259 $start = explode(' ', $GLOBALS['startTime']);
2260 $end = explode(' ', $endTime);
2261 $runTime = $end[0] - $start[0];
2262 if ($runTime < 0) $runTime = '0';
2266 'runtime' => translateComma($runTime),
2267 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2270 // Load the template
2271 loadTemplate('show_timings', false, $content);
2274 // Check wether a boolean constant is set
2275 // Taken from user comments in PHP documentation for function constant()
2276 function isBooleanConstantAndTrue ($constName) { // : Boolean
2277 // Failed by default
2281 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2283 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2284 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2287 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2288 if (defined($constName)) {
2290 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2291 $res = (constant($constName) === true);
2295 $GLOBALS['cache_array']['const'][$constName] = $res;
2297 //* DEBUG: */ var_dump($res);
2303 // Checks if a given apache module is loaded
2304 function isApacheModuleLoaded ($apacheModule) {
2305 // Check it and return result
2306 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2309 // Get current theme name
2310 function getCurrentTheme () {
2311 // The default theme is 'default'... ;-)
2314 // Do we have ext-theme installed and active?
2315 if (isExtensionActive('theme')) {
2316 // Call inner method
2317 $ret = getActualTheme();
2320 // Return theme value
2324 // Generates an error code from given account status
2325 function generateErrorCodeFromUserStatus ($status='') {
2326 // If no status is provided, use the default, cached
2327 if ((empty($status)) && (isMember())) {
2329 $status = getUserData('status');
2332 // Default error code if unknown account status
2333 $errorCode = getCode('UNKNOWN_STATUS');
2335 // Generate constant name
2336 $codeName = sprintf("ID_%s", $status);
2338 // Is the constant there?
2339 if (isCodeSet($codeName)) {
2341 $errorCode = getCode($codeName);
2344 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2347 // Return error code
2351 // Function to search for the last modifified file
2352 function searchDirsRecursive ($dir, &$last_changed) {
2354 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2355 // Does it match what we are looking for? (We skip a lot files already!)
2356 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2357 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2358 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2359 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2361 // Walk through all entries
2362 foreach ($ds as $d) {
2363 // Generate proper FQFN
2364 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2366 // Is it a file and readable?
2367 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2368 if (isDirectory($FQFN)) {
2369 // $FQFN is a directory so also crawl into this directory
2371 if (!empty($dir)) $newDir = $dir . '/'. $d;
2372 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2373 searchDirsRecursive($newDir, $last_changed);
2374 } elseif (isFileReadable($FQFN)) {
2375 // $FQFN is a filename and no directory
2376 $time = filemtime($FQFN);
2377 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2378 if ($last_changed['time'] < $time) {
2379 // This file is newer as the file before
2380 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2381 $last_changed['path_name'] = $FQFN;
2382 $last_changed['time'] = $time;
2388 // "Getter" for revision/version data
2389 function getActualVersion ($type = 'Revision') {
2390 // By default nothing is new... ;-)
2393 // Is the cache entry there?
2394 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2395 // Found so increase cache hit
2396 incrementStatsEntry('cache_hits');
2399 return $GLOBALS['cache_array']['revision'][$type][0];
2401 // FQFN of revision file
2402 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2404 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2405 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2406 // Forced rebuild of .revision file
2409 // Check for revision file
2410 if (!isFileReadable($FQFN)) {
2411 // Not found, so we need to create it
2414 // Revision file found
2415 $ins_vers = explode("\n", readFromFile($FQFN));
2417 // Get array for mapping information
2418 $mapper = array_flip(getSearchFor());
2419 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2421 // Is the content valid?
2422 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2423 // File needs update!
2426 // Generate fake cache entry
2427 foreach ($mapper as $map => $idx) {
2428 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2431 // Return found value
2432 return trim($ins_vers[$mapper[$type]]);
2437 // Has it been updated?
2438 if ($new === true) {
2440 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2442 // ... and call recursive
2443 return getActualVersion($type);
2448 // Repares an array we are looking for
2449 // 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
2450 function getSearchFor () {
2451 // Add Revision, Date, Tag and Author
2452 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2454 // Return the created array
2458 // @TODO Please describe this function
2459 function getArrayFromActualVersion () {
2463 // Directory to start with search
2464 $last_changed = array(
2469 // Init return array
2470 $akt_vers = array();
2472 // Init value for counting the founded keywords
2475 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2476 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2479 $last_file = readFromFile($last_changed['path_name']);
2481 // Get all the keywords to search for
2482 $searchFor = getSearchFor();
2484 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2485 foreach ($searchFor as $search) {
2486 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2487 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2488 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2489 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2492 // Save the last-changed filename for debugging
2493 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2495 // at least 3 keyword-Tags are needed for propper values
2496 if ($res && $res >= 3
2497 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2498 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2499 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2500 // Prepare content witch need special treadment
2502 // Prepare timestamp for date
2503 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2504 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2506 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2507 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2508 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2512 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2513 $version = sendGetRequest('check-updates3.php');
2516 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2517 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2518 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2519 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2520 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2521 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2524 // Return prepared array
2525 return $GLOBALS['cache_array']['revision'];
2528 // Back-ported from the new ship-simu engine. :-)
2529 function debug_get_printable_backtrace () {
2531 $backtrace = "<ol>\n";
2533 // Get and prepare backtrace for output
2534 $backtraceArray = debug_backtrace();
2535 foreach ($backtraceArray as $key => $trace) {
2536 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2537 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2538 if (!isset($trace['args'])) $trace['args'] = array();
2539 $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";
2543 $backtrace .= "</ol>\n";
2545 // Return the backtrace
2549 // A mail-able backtrace
2550 function debug_get_mailable_backtrace () {
2554 // Get and prepare backtrace for output
2555 $backtraceArray = debug_backtrace();
2556 foreach ($backtraceArray as $key => $trace) {
2557 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2558 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2559 if (!isset($trace['args'])) $trace['args'] = array();
2560 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2563 // Return the backtrace
2567 // Output a debug backtrace to the user
2568 function debug_report_bug ($message = '') {
2569 // Is this already called?
2570 if (isset($GLOBALS[__FUNCTION__])) {
2572 print 'Message:'.$message.'<br />Backtrace:<pre>';
2573 debug_print_backtrace();
2577 // Set this function as called
2578 $GLOBALS[__FUNCTION__] = true;
2583 // Is the optional message set?
2584 if (!empty($message)) {
2586 $debug = sprintf("Note: %s<br />\n",
2590 // @TODO Add a little more infos here
2591 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2595 $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">http://bugs.mxchange.org</a> and include the logfile from <strong>" . str_replace(getConfig('PATH'), '', getConfig('CACHE_PATH')) . "debug.log</strong> in your report (you can now attach files):<pre>";
2596 $debug .= debug_get_printable_backtrace();
2597 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2598 $debug .= "Thank you for finding bugs.";
2602 'message' => trim($message),
2603 'backtrace' => trim(debug_get_mailable_backtrace()),
2604 'request_uri' => trim(getRequestUri())
2607 // Send email to webmaster
2608 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2611 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2615 // Generates a ***weak*** seed
2616 function generateSeed () {
2617 return microtime(true) * 100000;
2620 // Converts a message code to a human-readable message
2621 function getMessageFromErrorCode ($code) {
2625 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2626 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2627 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2628 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2629 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2630 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2631 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2632 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2633 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2634 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2635 case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
2636 case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
2637 case getCode('ID_GUEST') : $message = getMessage('LOGIN_ID_GUEST'); break;
2638 case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2639 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2640 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2641 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2642 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2643 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2644 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2645 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2646 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2647 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2648 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2649 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2650 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2651 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2652 case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2653 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2655 case getCode('ERROR_MAILID'):
2656 if (isExtensionActive('mailid', true)) {
2657 $message = getMessage('ERROR_CONFIRMING_MAIL');
2659 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2663 case getCode('EXTENSION_PROBLEM'):
2664 if (isGetRequestElementSet('ext')) {
2665 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2667 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2671 case getCode('URL_TLOCK'):
2672 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2673 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2675 // Load timestamp from last order
2676 list($timestamp) = SQL_FETCHROW($result);
2677 $timestamp = generateDateTime($timestamp, 1);
2680 SQL_FREERESULT($result);
2682 // Calculate hours...
2683 $STD = round(getConfig('url_tlock') / 60 / 60);
2686 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2689 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2691 // Finally contruct the message
2692 // @TODO Rewrite this old lost code to a template
2693 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2694 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2695 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2699 // Missing/invalid code
2700 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2703 logDebugMessage(__FUNCTION__, __LINE__, $message);
2707 // Return the message
2711 // Compile characters which are allowed in URLs
2712 function compileUriCode ($code, $simple = true) {
2713 // Compile constants
2714 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2716 // Compile QUOT and other non-HTML codes
2717 $code = str_replace('{DOT}', '.',
2718 str_replace('{SLASH}', '/',
2719 str_replace('{QUOT}', "'",
2720 str_replace('{DOLLAR}', '$',
2721 str_replace('{OPEN_ANCHOR}', '(',
2722 str_replace('{CLOSE_ANCHOR}', ')',
2723 str_replace('{OPEN_SQR}', '[',
2724 str_replace('{CLOSE_SQR}', ']',
2725 str_replace('{PER}', '%',
2729 // Return compiled code
2733 // Function taken from user comments on www.php.net / function eregi()
2734 function isUrlValidSimple ($url) {
2736 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2738 // Allows http and https
2739 $http = "(http|https)+(:\/\/)";
2741 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2742 // Test double-domains (e.g. .de.vu)
2743 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2745 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2747 $dir = "((/)+([-_\.[:alnum:]])+)*";
2749 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2750 // ... and the string after and including question character
2751 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2752 // Pattern for URLs like http://url/dir/doc.html?var=value
2753 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2754 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2755 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2756 // Pattern for URLs like http://url/dir/?var=value
2757 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2758 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2759 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2760 // Pattern for URLs like http://url/dir/page.ext
2761 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2762 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2763 $pattern['ipdp'] = $http . $ip . $dir . $page;
2764 // Pattern for URLs like http://url/dir
2765 $pattern['d1d'] = $http . $domain1 . $dir;
2766 $pattern['d2d'] = $http . $domain2 . $dir;
2767 $pattern['ipd'] = $http . $ip . $dir;
2768 // Pattern for URLs like http://url/?var=value
2769 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2770 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2771 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2772 // Pattern for URLs like http://url?var=value
2773 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2774 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2775 $pattern['ipg12'] = $http . $ip . $getstring1;
2776 // Test all patterns
2778 foreach ($pattern as $key => $pat) {
2780 if (isDebugRegExpressionEnabled()) {
2781 // @TODO Are these convertions still required?
2782 $pat = str_replace('.', "\.", $pat);
2783 $pat = str_replace('@', "\@", $pat);
2784 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2787 // Check if expression matches
2788 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2791 if ($reg === true) break;
2794 // Return true/false
2798 // Wtites data to a config.php-style file
2799 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2800 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2801 // Initialize some variables
2807 // Is the file there and read-/write-able?
2808 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2809 $search = 'CFG: ' . $comment;
2810 $tmp = $FQFN . '.tmp';
2812 // Open the source file
2813 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2815 // Is the resource valid?
2816 if (is_resource($fp)) {
2817 // Open temporary file
2818 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2820 // Is the resource again valid?
2821 if (is_resource($fp_tmp)) {
2822 // Mark temporary file as readable
2823 $GLOBALS['file_readable'][$tmp] = true;
2826 while (!feof($fp)) {
2827 // Read from source file
2828 $line = fgets ($fp, 1024);
2830 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2833 if ($next === $seek) {
2835 $line = $prefix . $DATA . $suffix . "\n";
2841 // Write to temp file
2842 fputs($fp_tmp, $line);
2848 // Finished writing tmp file
2852 // Close source file
2855 if (($done === true) && ($found === true)) {
2856 // Copy back tmp file and delete tmp :-)
2857 copyFileVerified($tmp, $FQFN, 0644);
2858 return removeFile($tmp);
2859 } elseif ($found === false) {
2860 outputHtml('<strong>CHANGE:</strong> 404!');
2862 outputHtml('<strong>TMP:</strong> UNDONE!');
2866 // File not found, not readable or writeable
2867 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2870 // An error was detected!
2873 // Send notification to admin
2874 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2875 if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
2877 sendAdminsEmails($subject, $templateName, $content, $userid);
2879 // Send out out-dated way
2880 $message = loadEmailTemplate($templateName, $content, $userid);
2881 sendAdminEmails($subject, $message);
2885 // Debug message logger
2886 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2887 // Is debug mode enabled?
2888 if ((isDebugModeEnabled()) || ($force === true)) {
2890 $message = str_replace("\r", '', str_replace("\n", '', $message));
2892 // Log this message away, we better don't call app_die() here to prevent an endless loop
2893 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2894 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2899 // Handle extra values
2900 function handleExtraValues ($filterFunction, $value, $extraValue) {
2901 // Default is the value itself
2904 // Do we have a special filter function?
2905 if (!empty($filterFunction)) {
2906 // Does the filter function exist?
2907 if (function_exists($filterFunction)) {
2908 // Do we have extra parameters here?
2909 if (!empty($extraValue)) {
2910 // Put both parameters in one new array by default
2911 $args = array($value, $extraValue);
2913 // If we have an array simply use it and pre-extend it with our value
2914 if (is_array($extraValue)) {
2915 // Make the new args array
2916 $args = merge_array(array($value), $extraValue);
2919 // Call the multi-parameter call-back
2920 $ret = call_user_func_array($filterFunction, $args);
2922 // One parameter call
2923 $ret = call_user_func($filterFunction, $value);
2932 // Converts timestamp selections into a timestamp
2933 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2934 // Init test variable
2938 // Get last three chars
2939 $test = substr($id, -3);
2941 // Improved way of checking! :-)
2942 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2943 // Found a multi-selection for timings?
2944 $test = substr($id, 0, -3);
2945 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)) {
2946 // Generate timestamp
2947 $postData[$test] = createTimestampFromSelections($test, $postData);
2948 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2949 $GLOBALS['skip_config'][$test] = true;
2951 // Remove data from array
2952 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2953 unset($postData[$test . '_' . $rem]);
2964 // Reverts the german decimal comma into Computer decimal dot
2965 function convertCommaToDot ($str) {
2966 // Default float is not a float... ;-)
2969 // Which language is selected?
2970 switch (getLanguage()) {
2971 case 'de': // German language
2972 // Remove german thousand dots first
2973 $str = str_replace('.', '', $str);
2975 // Replace german commata with decimal dot and cast it
2976 $float = (float)str_replace(',', '.', $str);
2979 default: // US and so on
2980 // Remove thousand dots first and cast
2981 $float = (float)str_replace(',', '', $str);
2989 // Handle menu-depending failed logins and return the rendered content
2990 function handleLoginFailtures ($accessLevel) {
2991 // Default output is empty ;-)
2994 // Is the session data set?
2995 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
2996 // Ignore zero values
2997 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
2998 // Non-guest has login failures found, get both data and prepare it for template
2999 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3001 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3002 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3006 $OUT = loadTemplate('login_failures', true, $content);
3009 // Reset session data
3010 setSession('mxchange_' . $accessLevel.'_failures', '');
3011 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3014 // Return rendered content
3019 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3021 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3023 // Shall I remove the cache file?
3024 if (isCacheInstanceValid()) {
3026 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3028 $GLOBALS['cache_instance']->removeCacheFile($force);
3031 // Include file given?
3034 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3036 // Is the include there?
3037 if (isIncludeReadable($inc)) {
3038 // And rebuild it from scratch
3039 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3042 // Include not found!
3043 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3049 // Determines the real remote address
3050 function determineRealRemoteAddress () {
3051 // Is a proxy in use?
3052 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3054 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3055 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3056 // Yet, another proxy
3057 $address = $_SERVER['HTTP_CLIENT_IP'];
3059 // The regular address when no proxy was used
3060 $address = $_SERVER['REMOTE_ADDR'];
3063 // This strips out the real address from proxy output
3064 if (strstr($address, ',')) {
3065 $addressArray = explode(',', $address);
3066 $address = $addressArray[0];
3069 // Return the result
3073 // Adds a bonus mail to the queue
3074 // This is a high-level function!
3075 function addNewBonusMail ($data, $mode = '', $output=true) {
3076 // Use mode from data if not set and availble ;-)
3077 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3079 // Generate receiver list
3080 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3083 if (!empty($RECEIVER)) {
3084 // Add bonus mail to queue
3085 addBonusMailToQueue(
3097 // Mail inserted into bonus pool
3098 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3099 } elseif ($output) {
3100 // More entered than can be reached!
3101 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3104 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3108 // Determines referal id and sets it
3109 function determineReferalId () {
3110 // Skip this in non-html-mode and outside ref.php
3111 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3113 // Check if refid is set
3114 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3116 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3117 // The variable user comes from the click-counter script click.php and we only accept this here
3118 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3119 } elseif (isPostRequestElementSet('refid')) {
3120 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3121 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3122 } elseif (isGetRequestElementSet('refid')) {
3123 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3124 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3125 } elseif (isGetRequestElementSet('ref')) {
3126 // Set refid=ref (the referal link uses such variable)
3127 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3128 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3129 // Set session refid als global
3130 $GLOBALS['refid'] = bigintval(getSession('refid'));
3131 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3132 // Select a random user which has confirmed enougth mails
3133 $GLOBALS['refid'] = determineRandomReferalId();
3134 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3135 // Set default refid as refid in URL
3136 $GLOBALS['refid'] = getConfig('def_refid');
3138 // No default id when sql_patches is not installed or none set
3139 $GLOBALS['refid'] = '0';
3142 // Set cookie when default refid > 0
3143 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3144 // Default is not found
3147 // Do we have nickname or userid set?
3148 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3149 // Nickname in URL, so load the id
3150 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3151 } elseif ($GLOBALS['refid'] > 0) {
3152 // Direct userid entered
3153 $found = fetchUserData($GLOBALS['refid']);
3156 // Is the record valid?
3157 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3158 // No, then reset referal id
3159 $GLOBALS['refid'] = getConfig('def_refid');
3163 setSession('refid', $GLOBALS['refid']);
3166 // Return determined refid
3167 return $GLOBALS['refid'];
3170 // Enables the reset mode and runs it
3171 function doReset () {
3172 // Enable the reset mode
3173 $GLOBALS['reset_enabled'] = true;
3176 runFilterChain('reset');
3179 // Our shutdown-function
3180 function shutdown () {
3181 // Call the filter chain 'shutdown'
3182 runFilterChain('shutdown', null);
3184 if (SQL_IS_LINK_UP()) {
3186 SQL_CLOSE(__FILE__, __LINE__);
3187 } elseif (!isInstallationPhase()) {
3189 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3192 // Stop executing here
3197 function initMemberId () {
3198 $GLOBALS['member_id'] = '0';
3201 // Setter for member id
3202 function setMemberId ($memberid) {
3203 // We should not set member id to zero
3204 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3207 $GLOBALS['member_id'] = bigintval($memberid);
3210 // Getter for member id or returns zero
3211 function getMemberId () {
3212 // Default member id
3215 // Is the member id set?
3216 if (isMemberIdSet()) {
3218 $memberid = $GLOBALS['member_id'];
3225 // Checks ether the member id is set
3226 function isMemberIdSet () {
3227 return (isset($GLOBALS['member_id']));
3230 // Handle message codes from URL
3231 function handleCodeMessage () {
3232 if (isGetRequestElementSet('code')) {
3233 // Default extension is 'unknown'
3236 // Is extension given?
3237 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3239 // Convert the 'code' parameter from URL to a human-readable message
3240 $message = getMessageFromErrorCode(getRequestElement('code'));
3242 // Load message template
3243 loadTemplate('message', false, $message);
3247 // Setter for extra title
3248 function setExtraTitle ($extraTitle) {
3249 $GLOBALS['extra_title'] = $extraTitle;
3252 // Getter for extra title
3253 function getExtraTitle () {
3254 // Is the extra title set?
3255 if (!isExtraTitleSet()) {
3256 // No, then abort here
3257 debug_report_bug('extra_title is not set!');
3261 return $GLOBALS['extra_title'];
3264 // Checks if the extra title is set
3265 function isExtraTitleSet () {
3266 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3269 // Generates a 'extension foo inactive' message
3270 function generateExtensionInactiveMessage ($ext_name) {
3271 // Is the extension empty?
3272 if (empty($ext_name)) {
3273 // This should not happen
3274 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3278 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3280 // Is an admin logged in?
3282 // Then output admin message
3283 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3286 // Return prepared message
3290 // Generates a 'extension foo not installed' message
3291 function generateExtensionNotInstalledMessage ($ext_name) {
3292 // Is the extension empty?
3293 if (empty($ext_name)) {
3294 // This should not happen
3295 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3299 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3301 // Is an admin logged in?
3303 // Then output admin message
3304 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3307 // Return prepared message
3311 // Generates a message depending on if the extension is not installed or not
3313 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3317 // Is the extension not installed or just deactivated?
3318 switch (isExtensionInstalled($ext_name)) {
3319 case true; // Deactivated!
3320 $message = generateExtensionInactiveMessage($ext_name);
3323 case false; // Not installed!
3324 $message = generateExtensionNotInstalledMessage($ext_name);
3327 default: // Should not happen!
3328 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3329 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3333 // Return the message
3337 // Reads a directory recursively by default and searches for files not matching
3338 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3339 // a whole directory.
3340 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3341 // Add default entries we should exclude
3342 $excludeArray[] = '.';
3343 $excludeArray[] = '..';
3344 $excludeArray[] = '.svn';
3345 $excludeArray[] = '.htaccess';
3347 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3352 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3355 while ($baseFile = readdir($dirPointer)) {
3356 // Exclude '.', '..' and entries in $excludeArray automatically
3357 if (in_array($baseFile, $excludeArray, true)) {
3359 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3363 // Construct include filename and FQFN
3364 $fileName = $baseDir . $baseFile;
3365 $FQFN = getConfig('PATH') . $fileName;
3367 // Remove double slashes
3368 $FQFN = str_replace('//', '/', $FQFN);
3370 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3371 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3372 // These Lines are only for debugging!!
3373 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3374 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3375 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3381 // Skip also files with non-matching prefix genericly
3382 if (($recursive === true) && (isDirectory($FQFN))) {
3383 // Is a redirectory so read it as well
3384 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3386 // And skip further processing
3388 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3390 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3392 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3393 // Skip wrong suffix as well
3394 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3396 } elseif (!isFileReadable($FQFN)) {
3397 // Not readable so skip it
3398 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3402 // Is the file a PHP script or other?
3403 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3404 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3405 // Is this a valid include file?
3406 if ($extension == '.php') {
3407 // Remove both for extension name
3408 $extName = substr($baseFile, strlen($prefix), -4);
3410 // Is the extension valid and active?
3411 if (isExtensionNameValid($extName)) {
3412 // Then add this file
3413 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3414 $files[] = $fileName;
3416 // Add non-extension files as well
3417 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3418 if ($addBaseDir === true) {
3419 $files[] = $fileName;
3421 $files[] = $baseFile;
3425 // We found .php file but should not search for them, why?
3426 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3428 } elseif (substr($baseFile, -4, 4) == $extension) {
3429 // Other, generic file found
3430 $files[] = $fileName;
3435 closedir($dirPointer);
3440 // Return array with include files
3441 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3445 // Maps a module name into a database table name
3446 function mapModuleToTable ($moduleName) {
3447 // Map only these, still lame code...
3448 switch ($moduleName) {
3449 // 'index' is the guest's menu
3450 case 'index': $moduleName = 'guest'; break;
3451 // ... and 'login' the member's menu
3452 case 'login': $moduleName = 'member'; break;
3453 // Anything else will not be mapped, silently.
3460 // Add SQL debug data to array for later output
3461 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3462 // Already executed?
3463 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3464 // Then abort here, we don't need to profile a query twice
3468 // Remeber this as profiled (or not, but we don't care here)
3469 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3471 // Do we have cache?
3472 if (!isset($GLOBALS['debug_sql_available'])) {
3473 // Check it and cache it in $GLOBALS
3474 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3477 // Don't execute anything here if we don't need or ext-other is missing
3478 if ($GLOBALS['debug_sql_available'] === false) {
3484 'num_rows' => SQL_NUMROWS($result),
3485 'affected' => SQL_AFFECTEDROWS(),
3486 'sql_str' => $sqlString,
3487 'timing' => $timing,
3488 'file' => basename($F),
3493 $GLOBALS['debug_sqls'][] = $record;
3496 // Initializes the cache instance
3497 function initCacheInstance () {
3498 // Load include for CacheSystem class
3499 loadIncludeOnce('inc/classes/cachesystem.class.php');
3501 // Initialize cache system only when it's needed
3502 $GLOBALS['cache_instance'] = new CacheSystem();
3503 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3504 // Failed to initialize cache sustem
3505 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3509 // Getter for message from array or raw message
3510 function getMessageFromIndexedArray ($message, $pos, $array) {
3511 // Check if the requested message was found in array
3512 if (isset($array[$pos])) {
3513 // ... if yes then use it!
3514 $ret = $array[$pos];
3516 // ... else use default message
3524 // Print code with line numbers
3525 function linenumberCode ($code) {
3526 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3527 $count_lines = count($codeE);
3529 $r = 'Line | Code:<br />';
3530 foreach($codeE as $line => $c) {
3531 $r .= '<div class="line"><span class="linenum">';
3532 if ($count_lines == 1) {
3535 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3540 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3543 return '<div class="code">' . $r . '</div>';
3546 // Convert ';' to ', ' for e.g. receiver list
3547 function convertReceivers ($old) {
3548 return str_replace(';', ', ', $old);
3551 // Determines the right page title
3552 function determinePageTitle () {
3553 // Config and database connection valid?
3554 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3558 // Title decoration enabled?
3559 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
3561 // Do we have some extra title?
3562 if (isExtraTitleSet()) {
3564 $TITLE .= getExtraTitle() . ' by ';
3568 $TITLE .= getConfig('MAIN_TITLE');
3570 // Add title of module? (middle decoration will also be added!)
3571 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3572 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3575 // Add title from what file
3577 if (getModule() == 'login') $mode = 'member';
3578 elseif (getModule() == 'index') $mode = 'guest';
3579 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3581 // Add title decorations? (right)
3582 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3584 // Remember title in constant for the template
3585 $pageTitle = $TITLE;
3586 } elseif ((isInstalled()) && (isAdminRegistered())) {
3587 // Installed, admin registered but no ext-sql_patches
3588 $pageTitle = '[-- ' . getConfig('MAIN_TITLE').' - '.getModuleTitle(getModule()) . ' --]';
3589 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3590 // Installed but no admin registered
3591 $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
3592 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3593 // Installation mode
3594 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3596 // Configuration not found!
3597 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3599 // Do not add the fatal message in installation mode
3600 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3607 // Checks wethere there is a cache file there. This function is cached.
3608 function isTemplateCached ($template) {
3609 // Do we have cached this result?
3610 if (!isset($GLOBALS['template_cache'][$template])) {
3612 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3615 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3619 return $GLOBALS['template_cache'][$template];
3622 // Flushes non-flushed template cache to disk
3623 function flushTemplateCache ($template, $eval) {
3624 // Is this cache flushed?
3625 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3627 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3629 // Replace username with a call
3630 $eval = str_replace('$username', '".getUsername()."', $eval);
3633 writeToFile($FQFN, $eval, true);
3637 // Reads a template cache
3638 function readTemplateCache ($template) {
3640 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3642 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3645 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3649 return $GLOBALS['template_eval'][$template];
3652 // Escapes quotes (default is only double-quotes)
3653 function escapeQuotes ($str, $single = false) {
3654 // Should we escape all?
3655 if ($single === true) {
3656 // Escape all (including null)
3657 $str = addslashes($str);
3659 // Escape only double-quotes but prevent double-quoting
3660 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3663 // Return the escaped string
3667 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3668 function escapeJavaScriptQuotes ($str) {
3669 // Replace all double-quotes and secure back-ticks
3670 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3676 // Send out mails depending on the 'mod/modes' combination
3677 // @TODO Lame description for this function
3678 function sendModeMails ($mod, $modes) {
3680 if (fetchUserData(getMemberId())) {
3681 // Extract salt from cookie
3682 $salt = substr(getSession('u_hash'), 0, -40);
3684 // Now let's compare passwords
3685 $hash = generatePassString(getUserData('password'));
3687 // Does the hash match or should we change it?
3688 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
3690 $content = getUserDataArray();
3693 $content['gender'] = translateGender($content['gender']);
3695 // Clear/init the content variable
3696 $content['message'] = '';
3699 // @TODO Move this in a filter
3702 foreach ($modes as $mode) {
3704 case 'normal': break; // Do not add any special lines
3705 case 'email': // Email was changed!
3706 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestElement('old_email')."\n";
3709 case 'pass': // Password was changed
3710 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3714 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3715 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3720 if (isExtensionActive('country')) {
3721 // Replace code with description
3722 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
3725 // Merge content with data from POST
3726 $content = merge_array($content, postRequestArray());
3729 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3731 if (getConfig('admin_notify') == 'Y') {
3732 // The admin needs to be notified about a profile change
3733 $message_admin = 'admin_mydata_notify';
3734 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3737 $message_admin = '';
3741 // Set subject lines
3742 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3744 // Output success message
3745 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3748 default: // Unsupported module!
3749 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3750 $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
3754 // Passwords mismatch
3755 $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
3758 // Could not load profile
3759 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
3762 // Send email to user if required
3763 if ((!empty($sub_mem)) && (!empty($message))) {
3765 sendEmail($content['email'], $sub_mem, $message);
3768 // Send only if no other error has occured
3769 if (empty($content)) {
3770 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3772 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3773 } elseif (getConfig('admin_notify') == 'Y') {
3774 // Cannot send mails to admin!
3775 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3778 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3783 loadTemplate('admin_settings_saved', false, $content);
3786 // Generates a 'selection box' from given array
3787 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent) {
3789 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3790 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3792 // Walk through all options
3793 foreach ($options as $option) {
3794 // Add the <option> entry
3795 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3798 // Finish selection box
3799 $OUT .= '</select>';
3803 'selection_box' => $OUT,
3804 'module' => getModule(),
3808 // Load template and return it
3809 return loadTemplate('select_' . $name . '_box', true, $content);
3812 // Get a module from filename and access level
3813 function getModuleFromFileName ($file, $accessLevel) {
3814 // Default is 'invalid';
3815 $modCheck = 'invalid';
3817 // @TODO This is still very static, rewrite it somehow
3818 switch ($accessLevel) {
3820 $modCheck = 'admin';
3826 $modCheck = getModule();
3829 default: // Unsupported file name / access level
3830 debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3838 //////////////////////////////////////////////////
3839 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3840 //////////////////////////////////////////////////
3842 if (!function_exists('html_entity_decode')) {
3843 // Taken from documentation on www.php.net
3844 function html_entity_decode ($string) {
3845 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3846 $trans_tbl = array_flip($trans_tbl);
3847 return strtr($string, $trans_tbl);
3851 if (!function_exists('http_build_query')) {
3852 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3853 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
3855 foreach ((array)$data as $k => $v) {
3856 if (is_int($k) && $prefix != null) {
3857 $k = urlencode($prefix . $k);
3860 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
3862 if (is_array($v) || is_object($v)) {
3863 array_push($ret, http_build_query($v, '', $sep, $k));
3865 array_push($ret, $k.'='.urlencode($v));
3869 if (empty($sep)) $sep = ini_get('arg_separator.output');
3871 return implode($sep, $ret);