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 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
46 function outputHtml ($htmlCode, $newLine = true) {
48 if (!isset($GLOBALS['output'])) $GLOBALS['output'] = '';
51 $username = getMessage('USERNAME_UNKNOWN');
52 if (isset($GLOBALS['username'])) $username = getUsername();
54 // Do we have HTML-Code here?
55 if (!empty($htmlCode)) {
56 // Yes, so we handle it as you have configured
57 switch (getConfig('OUTPUT_MODE')) {
59 // That's why you don't need any \n at the end of your HTML code... :-)
60 if (getPhpCaching() == 'on') {
61 // Output into PHP's internal buffer
62 outputRawCode($htmlCode);
64 // That's why you don't need any \n at the end of your HTML code... :-)
65 if ($newLine === true) print("\n");
67 // Render mode for old or lame servers...
68 $GLOBALS['output'] .= $htmlCode;
70 // That's why you don't need any \n at the end of your HTML code... :-)
71 if ($newLine === true) $GLOBALS['output'] .= "\n";
76 // If we are switching from render to direct output rendered code
77 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
79 // The same as above... ^
80 outputRawCode($htmlCode);
81 if ($newLine === true) print("\n");
85 // Huh, something goes wrong or maybe you have edited config.php ???
86 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
89 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
90 // Output cached HTML code
91 $GLOBALS['output'] = ob_get_contents();
93 // Clear output buffer for later output if output is found
94 if (!empty($GLOBALS['output'])) {
98 // Extension 'rewrite' installed?
99 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
100 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
103 // Send all HTTP headers
106 // Compile and run finished rendered HTML code
107 compileFinalOutput();
109 // Output code here, DO NOT REMOVE! ;-)
110 outputRawCode($GLOBALS['output']);
111 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
112 // Rewrite links when rewrite extension is active
113 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
114 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
117 // Send all HTTP headers
120 // Compile and run finished rendered HTML code
121 compileFinalOutput();
123 // Output code here, DO NOT REMOVE! ;-)
124 outputRawCode($GLOBALS['output']);
126 // And flush all headers
131 // Sends out all headers required for HTTP/1.1 reply
132 function sendHttpHeaders () {
134 $now = gmdate('D, d M Y H:i:s') . ' GMT';
137 sendHeader('HTTP/1.1 200');
139 // General headers for no caching
140 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
141 sendHeader('Last-Modified: ' . $now);
142 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
143 sendHeader('Pragma: no-cache'); // HTTP/1.0
144 sendHeader('Connection: Close');
145 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
146 sendHeader('Content-Language: ' . getLanguage());
149 // Compiles the final output
150 function compileFinalOutput () {
154 // Add page header and footer
155 addPageHeaderFooter();
158 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
159 // Init common variables
164 $eval = "\$newContent = \"".compileCode(escapeQuotes($GLOBALS['output']))."\";";
167 // Was that eval okay?
168 if (empty($newContent)) {
169 // Something went wrong!
170 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
172 $GLOBALS['output'] = $newContent;
179 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
180 // Compress it for HTTP gzip
181 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
184 sendHeader('Content-Encoding: gzip');
185 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
186 // Compress it for HTTP deflate
187 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
190 sendHeader('Content-Encoding: deflate');
194 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
200 // Output the raw HTML code
201 function outputRawCode ($htmlCode) {
202 // Output stripped HTML code to avoid broken JavaScript code, etc.
203 print(str_replace('{BACK}', "\\", $htmlCode));
205 // Flush the output if only getPhpCaching() is not 'on'
206 if (getPhpCaching() != 'on') {
212 // Init fatal message array
213 function initFatalMessages () {
214 $GLOBALS['fatal_messages'] = array();
217 // Getter for whole fatal error messages
218 function getFatalArray () {
219 return $GLOBALS['fatal_messages'];
222 // Add a fatal error message to the queue array
223 function addFatalMessage ($F, $L, $message, $extra = '') {
224 if (is_array($extra)) {
225 // Multiple extras for a message with masks
226 $message = call_user_func_array('sprintf', $extra);
227 } elseif (!empty($extra)) {
228 // $message is text with a mask plus extras to insert into the text
229 $message = sprintf($message, $extra);
232 // Add message to $GLOBALS['fatal_messages']
233 $GLOBALS['fatal_messages'][] = $message;
235 // Log fatal messages away
236 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
239 // Getter for total fatal message count
240 function getTotalFatalErrors () {
244 // Do we have at least the first entry?
245 if (!empty($GLOBALS['fatal_messages'][0])) {
247 $count = count($GLOBALS['fatal_messages']);
254 // Load a template file and return it's content (only it's name; do not use ' or ")
255 function loadTemplate ($template, $return = false, $content = array()) {
256 // @TODO Remove this sanity-check if all is fine
257 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
259 // @TODO Try to rewrite all $DATA to $content
263 if (isTemplateCached($template)) {
264 // Evaluate the cache
265 eval(readTemplateCache($template));
266 } elseif (!isset($GLOBALS['template_eval'][$template])) {
267 // Add more variables which you want to use in your template files
268 $username = getUsername();
270 // Make all template names lowercase
271 $template = strtolower($template);
275 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
278 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
279 $extraPath = detectExtraTemplatePath($template);;
281 ////////////////////////
282 // Generate file name //
283 ////////////////////////
284 $FQFN = $basePath . $extraPath . $template . '.tpl';
286 // Does the special template exists?
287 if (!isFileReadable($FQFN)) {
288 // Reset to default template
289 $FQFN = $basePath . $template . '.tpl';
292 // Now does the final template exists?
293 if (isFileReadable($FQFN)) {
294 // Count the template load
295 incrementConfigEntry('num_templates');
297 // The local file does exists so we load it. :)
298 $GLOBALS['tpl_content'] = readFromFile($FQFN);
300 // Do we have to compile the code?
302 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false) || (strpos($GLOBALS['tpl_content'], '{%') !== false)) {
303 // Normal HTML output?
304 if (getOutputMode() == '0') {
305 // Add surrounding HTML comments to help finding bugs faster
306 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
308 // Prepare eval() command
309 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
310 } elseif (substr($template, 0, 3) == 'js_') {
311 // JavaScripts don't like entities and timings
312 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
314 // Prepare eval() command, other output doesn't like entities, maybe
315 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
318 // Add surrounding HTML comments to help finding bugs faster
319 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
320 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
323 // Cache the eval() command here
324 $GLOBALS['template_eval'][$template] = $eval;
327 eval($GLOBALS['template_eval'][$template]);
328 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
329 // Only admins shall see this warning or when installation mode is active
330 $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
331 (' . $template . ')<br />
333 {--TEMPLATE_CONTENT--}
334 <pre>' . print_r($content, true) . '</pre>
336 <pre>' . print_r($DATA, true) . '</pre>
340 $GLOBALS['template_eval'][$template] = '404';
344 eval($GLOBALS['template_eval'][$template]);
347 // Do we have some content to output or return?
349 // Not empty so let's put it out! ;)
350 if ($return === true) {
351 // Return the HTML code
357 } elseif (isDebugModeEnabled()) {
358 // Warning, empty output!
359 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
363 // Detects the extra template path from given template name
364 function detectExtraTemplatePath ($template) {
369 if (!isset($GLOBALS['extra_path'][$template])) {
370 // Check for admin/guest/member/etc. templates
371 if (substr($template, 0, 6) == 'admin_') {
372 // Admin template found
373 $extraPath = 'admin/';
374 } elseif (substr($template, 0, 6) == 'guest_') {
375 // Guest template found
376 $extraPath = 'guest/';
377 } elseif (substr($template, 0, 7) == 'member_') {
378 // Member template found
379 $extraPath = 'member/';
380 } elseif (substr($template, 0, 7) == 'select_') {
381 // Selection template found
382 $extraPath = 'select/';
383 } elseif (substr($template, 0, 8) == 'install_') {
384 // Installation template found
385 $extraPath = 'install/';
386 } elseif (substr($template, 0, 4) == 'ext_') {
387 // Extension template found
389 } elseif (substr($template, 0, 3) == 'la_') {
390 // 'Logical-area' template found
392 } elseif (substr($template, 0, 3) == 'js_') {
393 // JavaScript template found
395 } elseif (substr($template, 0, 5) == 'menu_') {
396 // Menu template found
397 $extraPath = 'menu/';
399 // Test for extension
400 $test = substr($template, 0, strpos($template, '_'));
402 // Probe for valid extension name
403 if (isExtensionNameValid($test)) {
404 // Set extra path to extension's name
405 $extraPath = $test . '/';
410 $GLOBALS['extra_path'][$template] = $extraPath;
414 return $GLOBALS['extra_path'][$template];
417 // Loads an email template and compiles it
418 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
421 // Make sure all template names are lowercase!
422 $template = strtolower($template);
424 // Default 'nickname' if extension is not installed
427 // Neutral email address is default
428 $email = getConfig('WEBMASTER');
430 // Is content an array?
431 if (is_array($content)) {
432 // Add expiration to array
433 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
434 // Will never expire!
435 $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
436 } elseif (isConfigEntrySet('auto_purge')) {
437 // Create nice date string
438 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
441 $content['expiration'] = getMessage('MAIL_NO_CONFIG_AUTO_PURGE');
446 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content).'<br />');
447 if (($userid > 0) && (is_array($content))) {
448 // If nickname extension is installed, fetch nickname as well
449 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
450 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
452 fetchUserData($userid, 'nickname');
454 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
456 fetchUserData($userid);
459 // Merge data if valid
460 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
461 if (isUserDataValid()) {
462 $content = merge_array($content, getUserDataArray());
464 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
467 // Translate M to male or F to female if present
468 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
470 // Overwrite email from data if present
471 if (isset($content['email'])) $email = $content['email'];
473 // Store email for some functions in global $DATA array
474 // @TODO Do only use $content, not $DATA or raw variables
475 $DATA['email'] = $email;
478 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
481 $extraPath = detectExtraTemplatePath($template);
483 // Generate full FQFN
484 $FQFN = $basePath . $extraPath . $template . '.tpl';
486 // Does the special template exists?
487 if (!isFileReadable($FQFN)) {
488 // Reset to default template
489 $FQFN = $basePath . $template . '.tpl';
492 // Now does the final template exists?
494 if (isFileReadable($FQFN)) {
495 // The local file does exists so we load it. :)
496 $GLOBALS['tpl_content'] = readFromFile($FQFN);
499 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileRawCode(escapeQuotes($GLOBALS['tpl_content']))."\");";
500 eval($GLOBALS['tpl_content']);
501 } elseif (!empty($template)) {
502 // Template file not found!
503 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
504 {--TEMPLATE_CONTENT--}
505 <pre>' . print_r($content, true) . '</pre>
507 <pre>' . print_r($DATA, true) . '</pre>
510 // Debug mode not active? Then remove the HTML tags
511 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
513 // No template name supplied!
514 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
517 // Is there some content?
518 if (empty($newContent)) {
520 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
522 // Add last error if the required function exists
523 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
526 // Remove content and data
534 // Send mail out to an email address
535 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
536 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail},SUBJECT={$subject}<br />");
538 // Compile subject line (for POINTS constant etc.)
539 eval("\$subject = decodeEntities(\"".compileRawCode(escapeQuotes($subject))."\");");
542 if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
543 // Value detected, is the message extension installed?
544 // @TODO Extension 'msg' does not exist
545 if (isExtensionActive('msg')) {
546 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
549 // Does the user exist?
550 if (fetchUserData($toEmail)) {
552 $toEmail = getUserData('email');
555 $toEmail = getConfig('WEBMASTER');
558 } elseif ($toEmail == '0') {
560 $toEmail = getConfig('WEBMASTER');
562 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
564 // Check for PHPMailer or debug-mode
565 if (!checkPhpMailerUsage()) {
566 // Not in PHPMailer-Mode
567 if (empty($mailHeader)) {
568 // Load email header template
569 $mailHeader = loadEmailTemplate('header');
572 $mailHeader .= loadEmailTemplate('header');
574 } elseif (isDebugModeEnabled()) {
575 if (empty($mailHeader)) {
576 // Load email header template
577 $mailHeader = loadEmailTemplate('header');
580 $mailHeader .= loadEmailTemplate('header');
585 eval("\$toEmail = \"".compileRawCode(escapeQuotes($toEmail))."\";");
588 eval("\$message = \"".str_replace('$', '$', compileRawCode(escapeQuotes($message)))."\";");
590 // Fix HTML parameter (default is no!)
591 if (empty($isHtml)) $isHtml = 'N';
592 if (isDebugModeEnabled()) {
593 // In debug mode we want to display the mail instead of sending it away so we can debug this part
595 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
596 To : ' . htmlentities(utf8_decode($toEmail)) . '
597 Subject : ' . htmlentities(utf8_decode($subject)) . '
598 Message : ' . htmlentities(utf8_decode($message)) . '
600 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
601 // Send mail as HTML away
602 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
603 } elseif (!empty($toEmail)) {
605 sendRawEmail($toEmail, $subject, $message, $mailHeader);
606 } elseif ($isHtml != 'Y') {
608 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
612 // Check to use wether legacy mail() command or PHPMailer class
613 // @TODO Rewrite this to an extension 'smtp'
615 function checkPhpMailerUsage() {
616 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
619 // Send out a raw email with PHPMailer class or legacy mail() command
620 function sendRawEmail ($toEmail, $subject, $message, $from) {
621 // Just compile all again, to put out all configs, etc.
622 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
623 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
624 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
625 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
627 // Shall we use PHPMailer class or legacy mode?
628 if (checkPhpMailerUsage()) {
629 // Use PHPMailer class with SMTP enabled
630 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
631 loadIncludeOnce('inc/phpmailer/class.smtp.php');
634 $mail = new PHPMailer();
636 // Set charset to UTF-8
637 $mail->CharSet('UTF-8');
639 // Path for PHPMailer
640 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
643 $mail->SMTPAuth = true;
644 $mail->Host = getConfig('SMTP_HOSTNAME');
646 $mail->Username = getConfig('SMTP_USER');
647 $mail->Password = getConfig('SMTP_PASSWORD');
649 $mail->From = getConfig('WEBMASTER');
653 $mail->FromName = getConfig('MAIN_TITLE');
654 $mail->Subject = $subject;
655 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
656 $mail->Body = $message;
657 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
658 $mail->WordWrap = 70;
661 $mail->Body = decodeEntities($message);
663 $mail->AddAddress($toEmail, '');
664 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
665 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
666 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
669 // Use legacy mail() command
670 mail($toEmail, $subject, decodeEntities($message), $from);
674 // Generate a password in a specified length or use default password length
675 function generatePassword ($length = '0') {
676 // Auto-fix invalid length of zero
677 if ($length == '0') $length = getConfig('pass_len');
679 // Initialize array with all allowed chars
680 $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,-,+,_,/,.');
682 // Start creating password
684 for ($i = '0'; $i < $length; $i++) {
685 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
688 // When the size is below 40 we can also add additional security by scrambling
689 // it. Otherwise we may corrupt hashes
690 if (strlen($PASS) <= 40) {
691 // Also scramble the password
692 $PASS = scrambleString($PASS);
695 // Return the password
699 // Generates a human-readable timestamp from the Uni* stamp
700 function generateDateTime ($time, $mode = '0') {
701 // Filter out numbers
702 $time = bigintval($time);
704 // If the stamp is zero it mostly didn't "happen"
707 return getMessage('NEVER_HAPPENED');
710 switch (getLanguage()) {
711 case 'de': // German date / time format
713 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
714 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
715 case '2': $ret = date('d.m.Y|H:i', $time); break;
716 case '3': $ret = date('d.m.Y', $time); break;
718 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
723 default: // Default is the US date / time format!
725 case '0': $ret = date('r', $time); break;
726 case '1': $ret = date('Y-m-d - g:i A', $time); break;
727 case '2': $ret = date('y-m-d|H:i', $time); break;
728 case '3': $ret = date('y-m-d', $time); break;
730 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
739 // Translates Y/N to yes/no
740 function translateYesNo ($yn) {
742 $translated = '??? (' . $yn . ')';
744 case 'Y': $translated = getMessage('YES'); break;
745 case 'N': $translated = getMessage('NO'); break;
748 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
756 // Translates the "pool type" into human-readable
757 function translatePoolType ($type) {
758 // Default?type is unknown
759 $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
762 $constName = sprintf("POOL_TYPE_%s", $type);
765 if (isMessageIdValid($constName)) {
767 $translated = getMessage($constName);
770 // Return "translation"
774 // Translates the american decimal dot into a german comma
775 function translateComma ($dotted, $cut = true, $max = '0') {
776 // Default is 3 you can change this in admin area "Misc -> Misc Options"
777 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
779 // Use from config is default
780 $maxComma = getConfig('max_comma');
782 // Use from parameter?
783 if ($max > 0) $maxComma = $max;
786 if (($cut === true) && ($max == '0')) {
787 // Test for commata if in cut-mode
788 $com = explode('.', $dotted);
789 if (count($com) < 2) {
790 // Don't display commatas even if there are none... ;-)
796 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
799 switch (getLanguage()) {
800 case 'de': // German language
801 $dotted = number_format($dotted, $maxComma, ',', '.');
804 default: // All others
805 $dotted = number_format($dotted, $maxComma, '.', ',');
809 // Return translated value
813 // Translate Uni*-like gender to human-readable
814 function translateGender ($gender) {
816 $ret = '!' . $gender . '!';
818 // Male/female or company?
820 case 'M': $ret = getMessage('GENDER_M'); break;
821 case 'F': $ret = getMessage('GENDER_F'); break;
822 case 'C': $ret = getMessage('GENDER_C'); break;
824 // Please report bugs on unknown genders
825 debug_report_bug(sprintf("Unknown gender %s detected.", $gender));
829 // Return translated gender
833 // "Translates" the user status
834 function translateUserStatus ($status) {
835 // Generate message depending on status
840 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
845 $ret = getMessage('ACCOUNT_DELETED');
849 // Please report all unknown status
850 debug_report_bug(sprintf("Unknown status %s detected.", $status));
858 // Generates an URL for the dereferer
859 function generateDerefererUrl ($URL) {
860 // Don't de-refer our own links!
861 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
862 // De-refer this link
863 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
870 // Generates an URL for the frametester
871 function generateFrametesterUrl ($URL) {
872 // Prepare frametester URL
873 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
874 encodeString(compileUriCode($URL))
877 // Return the new URL
878 return $frametesterUrl;
881 // Count entries from e.g. a selection box
882 function countSelection ($array) {
884 if (!is_array($array)) {
886 debug_report_bug(__FUNCTION__.': No array provided.');
893 foreach ($array as $key => $selected) {
895 if (!empty($selected)) $ret++;
898 // Return counted selections
902 // Generate XHTML code for the CAPTCHA
903 function generateCaptchaCode ($code, $type, $DATA, $userid) {
904 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
907 // Generates a timestamp (some wrapper for mktime())
908 function makeTime ($hours, $minutes, $seconds, $stamp) {
909 // Extract day, month and year from given timestamp
910 $days = date('d', $stamp);
911 $months = date('m', $stamp);
912 $years = date('Y', $stamp);
914 // Create timestamp for wished time which depends on extracted date
925 // Redirects to an URL and if neccessarry extends it with own base URL
926 function redirectToUrl ($URL, $allowSpider = true) {
928 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
930 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
931 $rel = ' rel="external"';
933 // Do we have internal or external URL?
934 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
935 // Own (=internal) URL
939 // Three different ways to debug...
940 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
941 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
942 //* DEBUG: */ die($URL);
944 // Simple probe for bots/spiders from search engines
945 if ((isSpider()) && ($allowSpider === true)) {
946 // Secure the URL against bad things such als HTML insertions and so on...
947 $URL = secureString($URL);
949 // Set content-type here to fix a missing array element
950 setContentType('text/html');
952 // Output new location link as anchor
953 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
954 } elseif (!headers_sent()) {
955 // Clear own output buffer
956 $GLOBALS['output'] = '';
958 // Load URL when headers are not sent
959 sendHeader('Location: '.str_replace('&', '&', $URL));
961 // Output error message
962 loadInclude('inc/header.php');
963 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
964 loadInclude('inc/footer.php');
967 // Shut the mailer down here
971 // Wrapper for redirectToUrl but URL comes from a configuration entry
972 function redirectToConfiguredUrl ($configEntry) {
974 $URL = getConfig($configEntry);
979 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
986 // Compiles the given HTML/mail code
987 function compileCode ($code, $simple = false, $constants = true, $full = true) {
988 // Is the code a string?
989 if (!is_string($code)) {
990 // Silently return it
995 $startCompile = microtime(true);
998 $code = compileRawCode($code, $simple, $constants, $full);
1001 $compiled = microtime(true);
1004 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1006 // Return compiled code
1010 // Compiles the code (use compileCode() only for HTML because of the comments)
1011 // @TODO $simple is deprecated
1012 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1013 // Is the code a string?
1014 if (!is_string($code)) {
1015 // Silently return it
1019 // Init replacement-array with smaller set of security characters
1020 $secChars = $GLOBALS['url_chars'];
1022 // Select full set of chars to replace when we e.g. want to compile URLs
1023 if ($full === true) $secChars = $GLOBALS['security_chars'];
1025 // Compile more through a filter
1026 $code = runFilterChain('compile_code', $code);
1028 // Compile constants
1029 if ($constants === true) {
1030 // BEFORE 0.2.1 : Language and data constants
1031 // WITH 0.2.1+ : Only language constants
1032 $code = str_replace('{--', "\" . getMessage('", str_replace('--}', "') . \"", $code));
1034 // BEFORE 0.2.1 : Not used
1035 // WITH 0.2.1+ : Data constants
1036 $code = str_replace('{!', "\" . constant('", str_replace('!}', "') . \"", $code));
1039 // Compile QUOT and other non-HTML codes
1040 foreach ($secChars['to'] as $k => $to) {
1041 // Do the reversed thing as in inc/libs/security_functions.php
1042 $code = str_replace($to, $secChars['from'][$k], $code);
1045 // Find $content[bla][blub] entries
1046 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1047 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1049 // Are some matches found?
1050 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1051 // Replace all matches
1052 $matchesFound = array();
1053 foreach ($matches[0] as $key => $match) {
1054 // Fuzzy look has failed by default
1055 $fuzzyFound = false;
1057 // Fuzzy look on match if already found
1058 foreach ($matchesFound as $found => $set) {
1060 $test = substr($found, 0, strlen($match));
1062 // Does this entry exist?
1063 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
1064 if ($test == $match) {
1066 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
1073 if ($fuzzyFound === true) continue;
1075 // Take all string elements
1076 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1077 // Replace it in the code
1078 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
1079 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1080 $code = str_replace($match, '".' . $newMatch . '."', $code);
1081 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1082 $matchesFound[$match] = 1;
1083 } elseif (!isset($matchesFound[$match])) {
1084 // Not yet replaced!
1085 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
1086 $code = str_replace($match, '".' . $match . '."', $code);
1087 $matchesFound[$match] = 1;
1096 /************************************************************************
1098 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1099 * $a_sort sortiert: *
1101 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1102 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1103 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1104 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1105 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1107 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1108 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1109 * Sie, dass es doch nicht so schwer ist! :-) *
1111 ************************************************************************/
1112 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1114 while ($primary_key < count($a_sort)) {
1115 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1116 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1118 if ($nums === false) {
1119 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1120 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1121 } elseif ($key != $key2) {
1122 // Sort numbers (E.g.: 9 < 10)
1123 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1124 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1128 // We have found two different values, so let's sort whole array
1129 foreach ($dummy as $sort_key => $sort_val) {
1130 $t = $dummy[$sort_key][$key];
1131 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1132 $dummy[$sort_key][$key2] = $t;
1143 // Write back sorted array
1148 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1151 if ($type == 'yn') {
1152 // This is a yes/no selection only!
1153 if ($id > 0) $prefix .= "[" . $id."]";
1154 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1156 // Begin with regular selection box here
1157 if (!empty($prefix)) $prefix .= "_";
1159 if ($id > 0) $type2 .= "[" . $id."]";
1160 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1165 for ($idx = 1; $idx < 32; $idx++) {
1166 $OUT .= "<option value=\"" . $idx."\"";
1167 if ($default == $idx) $OUT .= ' selected="selected"';
1168 $OUT .= ">" . $idx."</option>\n";
1172 case 'month': // Month
1173 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1174 $OUT .= "<option value=\"" . $month."\"";
1175 if ($default == $month) $OUT .= ' selected="selected"';
1176 $OUT .= ">" . $descr."</option>\n";
1180 case 'year': // Year
1182 $year = date('Y', time());
1184 // Use configured min age or fixed?
1185 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1187 $startYear = $year - getConfig('min_age');
1190 $startYear = $year - 16;
1193 // Calculate earliest year (100 years old people can still enter Internet???)
1194 $minYear = $year - 100;
1196 // Check if the default value is larger than minimum and bigger than actual year
1197 if (($default > $minYear) && ($default >= $year)) {
1198 for ($idx = $year; $idx < ($year + 11); $idx++) {
1199 $OUT .= "<option value=\"" . $idx."\"";
1200 if ($default == $idx) $OUT .= ' selected="selected"';
1201 $OUT .= ">" . $idx."</option>\n";
1203 } elseif ($default == -1) {
1204 // Current year minus 1
1205 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1207 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1210 // Get current year and subtract the configured minimum age
1211 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1212 // Calculate earliest year depending on extension version
1213 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1214 // Use configured minimum age
1215 $year = date('Y', time()) - getConfig('min_age');
1217 // Use fixed 16 years age
1218 $year = date('Y', time()) - 16;
1221 // Construct year selection list
1222 for ($idx = $minYear; $idx <= $year; $idx++) {
1223 $OUT .= "<option value=\"" . $idx."\"";
1224 if ($default == $idx) $OUT .= ' selected="selected"';
1225 $OUT .= ">" . $idx."</option>\n";
1232 for ($idx = '0'; $idx < 60; $idx+=5) {
1233 if (strlen($idx) == 1) $idx = '0' . $idx;
1234 $OUT .= "<option value=\"" . $idx."\"";
1235 if ($default == $idx) $OUT .= ' selected="selected"';
1236 $OUT .= ">" . $idx."</option>\n";
1241 for ($idx = '0'; $idx < 24; $idx++) {
1242 if (strlen($idx) == 1) $idx = '0' . $idx;
1243 $OUT .= "<option value=\"" . $idx."\"";
1244 if ($default == $idx) $OUT .= ' selected="selected"';
1245 $OUT .= ">" . $idx."</option>\n";
1250 $OUT .= "<option value=\"Y\"";
1251 if ($default == 'Y') $OUT .= ' selected="selected"';
1252 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1253 if ($default != 'Y') $OUT .= ' selected="selected"';
1254 $OUT .= ">{--NO--}</option>\n";
1257 $OUT .= " </select>\n";
1262 // Deprecated : $length
1265 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1266 // Build server string
1267 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
1270 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1271 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1272 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1273 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1274 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1276 // Build string from misc data
1277 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1279 // Add more additional data
1280 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1282 // Add referal id, language, theme and userid
1283 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1284 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1285 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1286 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1288 // Calculate number for generating the code
1289 $a = $code + getConfig('_ADD') - 1;
1291 if (isConfigEntrySet('master_salt')) {
1292 // Generate hash with master salt from modula of number with the prime number and other data
1293 $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'));
1295 // Create number from hash
1296 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1298 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1299 $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')));
1301 // Create number from hash
1302 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1305 // At least 10 numbers shall be secure enought!
1306 $len = getConfig('code_length');
1307 if ($len == '0') $len = $length;
1308 if ($len == '0') $len = 10;
1310 // Cut off requested counts of number
1311 $return = substr(str_replace('.', '', $rcode), 0, $len);
1313 // Done building code
1317 // Does only allow numbers
1318 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
1319 // Filter all numbers out
1320 $ret = preg_replace('/[^0123456789]/', '', $num);
1323 if ($castValue === true) $ret = (double)$ret;
1325 // Has the whole value changed?
1326 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
1328 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1335 // Insert the code in $img_code into jpeg or PNG image
1336 function generateImageOrCode ($img_code, $headerSent = true) {
1337 // Is the code size oversized or shouldn't we display it?
1338 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1339 // Stop execution of function here because of over-sized code length
1340 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1341 } elseif ($headerSent === false) {
1342 // Return an HTML code here
1343 return "<img src=\"{%url=img.php?code=" . $img_code."%}\" alt=\"Image\" />\n";
1347 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1350 getConfig('img_type')
1354 if (isFileReadable($img)) {
1355 // Switch image type
1356 switch (getConfig('img_type'))
1359 // Okay, load image and hide all errors
1360 $image = imagecreatefromjpeg($img);
1364 // Okay, load image and hide all errors
1365 $image = imagecreatefrompng($img);
1369 // Exit function here
1370 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1374 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1375 $text_color = imagecolorallocate($image, 0, 0, 0);
1377 // Insert code into image
1378 imagestring($image, 5, 14, 2, $img_code, $text_color);
1380 // Return to browser
1381 sendHeader('Content-Type: image/' . getConfig('img_type'));
1383 // Output image with matching image factory
1384 switch (getConfig('img_type')) {
1385 case 'jpg': imagejpeg($image); break;
1386 case 'png': imagepng($image); break;
1389 // Remove image from memory
1390 imagedestroy($image);
1392 // Create selection box or array of splitted timestamp
1393 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1394 // Do not continue if ONE_DAY is absend
1395 if (!isConfigEntrySet('ONE_DAY')) {
1396 // And return the timestamp itself or empty array
1397 if ($return_array === true) {
1404 // Calculate 2-seconds timestamp
1405 $stamp = round($timestamp);
1406 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1408 // Do we have a leap year?
1410 $TEST = date('Y', time()) / 4;
1411 $M1 = date('m', time());
1412 $M2 = date('m', (time() + $timestamp));
1414 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1415 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1417 // First of all years...
1418 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1419 //* DEBUG: */ print("Y={$Y}<br />");
1421 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1422 //* DEBUG: */ print("M={$M}<br />");
1424 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1425 //* DEBUG: */ print("W={$W}<br />");
1427 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1428 //* DEBUG: */ print("D={$D}<br />");
1430 $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));
1431 //* DEBUG: */ print("h={$h}<br />");
1433 $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));
1434 //* DEBUG: */ print("m={$m}<br />");
1435 // And at last seconds...
1436 $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));
1437 //* DEBUG: */ print("s={$s}<br />");
1439 // Is seconds zero and time is < 60 seconds?
1440 if (($s == '0') && ($timestamp < 60)) {
1442 $s = round($timestamp);
1446 // Now we convert them in seconds...
1448 if ($return_array) {
1449 // Just put all data in an array for later use
1461 $OUT = "<div align=\"" . $align."\">\n";
1462 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"timebox_table dashed\">\n";
1465 if (isInString('Y', $display) || (empty($display))) {
1466 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1469 if (isInString('M', $display) || (empty($display))) {
1470 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1473 if (isInString('W', $display) || (empty($display))) {
1474 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1477 if (isInString('D', $display) || (empty($display))) {
1478 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1481 if (isInString('h', $display) || (empty($display))) {
1482 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1485 if (isInString('m', $display) || (empty($display))) {
1486 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1489 if (isInString('s', $display) || (empty($display))) {
1490 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1496 if (isInString('Y', $display) || (empty($display))) {
1497 // Generate year selection
1498 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ye\" size=\"1\">\n";
1499 for ($idx = '0'; $idx <= 10; $idx++) {
1500 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1501 if ($idx == $Y) $OUT .= ' selected="selected"';
1502 $OUT .= ">" . $idx."</option>\n";
1504 $OUT .= " </select></td>\n";
1506 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1509 if (isInString('M', $display) || (empty($display))) {
1510 // Generate month selection
1511 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mo\" size=\"1\">\n";
1512 for ($idx = '0'; $idx <= 11; $idx++)
1514 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1515 if ($idx == $M) $OUT .= ' selected="selected"';
1516 $OUT .= ">" . $idx."</option>\n";
1518 $OUT .= " </select></td>\n";
1520 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1523 if (isInString('W', $display) || (empty($display))) {
1524 // Generate week selection
1525 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_we\" size=\"1\">\n";
1526 for ($idx = '0'; $idx <= 4; $idx++) {
1527 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1528 if ($idx == $W) $OUT .= ' selected="selected"';
1529 $OUT .= ">" . $idx."</option>\n";
1531 $OUT .= " </select></td>\n";
1533 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1536 if (isInString('D', $display) || (empty($display))) {
1537 // Generate day selection
1538 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_da\" size=\"1\">\n";
1539 for ($idx = '0'; $idx <= 31; $idx++) {
1540 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1541 if ($idx == $D) $OUT .= ' selected="selected"';
1542 $OUT .= ">" . $idx."</option>\n";
1544 $OUT .= " </select></td>\n";
1546 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1549 if (isInString('h', $display) || (empty($display))) {
1550 // Generate hour selection
1551 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ho\" size=\"1\">\n";
1552 for ($idx = '0'; $idx <= 23; $idx++) {
1553 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1554 if ($idx == $h) $OUT .= ' selected="selected"';
1555 $OUT .= ">" . $idx."</option>\n";
1557 $OUT .= " </select></td>\n";
1559 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1562 if (isInString('m', $display) || (empty($display))) {
1563 // Generate minute selection
1564 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mi\" size=\"1\">\n";
1565 for ($idx = '0'; $idx <= 59; $idx++) {
1566 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1567 if ($idx == $m) $OUT .= ' selected="selected"';
1568 $OUT .= ">" . $idx."</option>\n";
1570 $OUT .= " </select></td>\n";
1572 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1575 if (isInString('s', $display) || (empty($display))) {
1576 // Generate second selection
1577 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_se\" size=\"1\">\n";
1578 for ($idx = '0'; $idx <= 59; $idx++) {
1579 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1580 if ($idx == $s) $OUT .= ' selected="selected"';
1581 $OUT .= ">" . $idx."</option>\n";
1583 $OUT .= " </select></td>\n";
1585 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1588 $OUT .= "</table>\n";
1590 // Return generated HTML code
1596 function createTimestampFromSelections ($prefix, $postData) {
1597 // Initial return value
1600 // Do we have a leap year?
1602 $TEST = date('Y', time()) / 4;
1603 $M1 = date('m', time());
1604 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1605 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
1606 // First add years...
1607 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1609 $ret += $postData[$prefix . '_mo'] * 2628000;
1611 $ret += $postData[$prefix . '_we'] * 604800;
1613 $ret += $postData[$prefix . '_da'] * 86400;
1615 $ret += $postData[$prefix . '_ho'] * 3600;
1617 $ret += $postData[$prefix . '_mi'] * 60;
1618 // And at last seconds...
1619 $ret += $postData[$prefix . '_se'];
1620 // Return calculated value
1624 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1625 function createFancyTime ($stamp) {
1626 // Get data array with years/months/weeks/days/...
1627 $data = createTimeSelections($stamp, '', '', '', true);
1629 foreach($data as $k => $v) {
1631 // Value is greater than 0 "eval" data to return string
1632 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1637 // Do we have something there?
1638 if (strlen($ret) > 0) {
1639 // Remove leading commata and space
1640 $ret = substr($ret, 2);
1643 $ret = "0 {--_SECONDS--}";
1646 // Return fancy time string
1650 // Generates a navigation row for listing emails
1651 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1653 if ($show_form === false) {
1658 for ($page = 1; $page <= $PAGES; $page++) {
1659 // Is the page currently selected or shall we generate a link to it?
1660 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1661 // Is currently selected, so only highlight it
1662 $NAV .= '<strong>-';
1664 // Open anchor tag and add base URL
1665 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1667 // Add userid when we shall show all mails from a single member
1668 if ((isGetRequestParameterSet('userid')) && (bigintval(getRequestParameter('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestParameter('userid'));
1670 // Close open anchor tag
1674 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1675 // Is currently selected, so only highlight it
1676 $NAV .= '-</strong>';
1682 // Add seperator if we have not yet reached total pages
1683 if ($page < $PAGES) $NAV .= ' | ';
1686 // Define constants only once
1687 $content['nav'] = $NAV;
1688 $content['span'] = $colspan;
1689 $content['top'] = $TOP;
1691 // Load navigation template
1692 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1694 if ($return === true) {
1695 // Return generated HTML-Code
1703 // Extract host from script name
1704 function extractHostnameFromUrl (&$script) {
1705 // Use default SERVER_URL by default... ;) So?
1706 $url = getConfig('SERVER_URL');
1708 // Is this URL valid?
1709 if (substr($script, 0, 7) == 'http://') {
1710 // Use the hostname from script URL as new hostname
1711 $url = substr($script, 7);
1712 $extract = explode('/', $url);
1714 // Done extracting the URL :)
1717 // Extract host name
1718 $host = str_replace('http://', '', $url);
1719 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1721 // Generate relative URL
1722 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1723 if (substr(strtolower($script), 0, 7) == 'http://') {
1724 // But only if http:// is in front!
1725 $script = substr($script, (strlen($url) + 7));
1726 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1728 $script = substr($script, (strlen($url) + 8));
1731 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1732 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1738 // Send a GET request
1739 function sendGetRequest ($script, $data = array()) {
1740 // Extract host name from script
1741 $host = extractHostnameFromUrl($script);
1744 $body = http_build_query($data, '', '&');
1746 // Do we have a question-mark in the script?
1747 if (strpos($script, '?') === false) {
1748 // No, so first char must be question mark
1749 $body = '?' . $body;
1752 $body = '&' . $body;
1758 // Remove trailed & to make it more conform
1759 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
1761 // Generate GET request header
1762 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1763 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1764 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1765 if (isConfigEntrySet('FULL_VERSION')) {
1766 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1768 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1770 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1771 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1772 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1773 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1774 $request .= 'Content-Length: 0' . getConfig('HTTP_EOL');
1775 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1776 $request .= getConfig('HTTP_EOL');
1778 // Send the raw request
1779 $response = sendRawRequest($host, $request);
1781 // Return the result to the caller function
1785 // Send a POST request
1786 function sendPostRequest ($script, $postData) {
1787 // Is postData an array?
1788 if (!is_array($postData)) {
1790 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1791 return array('', '', '');
1794 // Extract host name from script
1795 $host = extractHostnameFromUrl($script);
1797 // Construct request body
1798 $body = http_build_query($postData, '', '&');
1800 // Generate POST request header
1801 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1802 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1803 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1804 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1805 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1806 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1807 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1808 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1809 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
1810 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1811 $request .= getConfig('HTTP_EOL');
1816 // Send the raw request
1817 $response = sendRawRequest($host, $request);
1819 // Return the result to the caller function
1823 // Sends a raw request to another host
1824 function sendRawRequest ($host, $request) {
1825 // Init errno and errdesc with 'all fine' values
1826 $errno = '0'; $errdesc = '';
1829 $response = array('', '', '');
1831 // Default is not to use proxy
1834 // Are proxy settins set?
1835 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1841 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1842 if ($useProxy === true) {
1843 // Connect to host through proxy connection
1844 $fp = fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1846 // Connect to host directly
1847 $fp = fsockopen($host, 80, $errno, $errdesc, 30);
1851 if (!is_resource($fp)) {
1853 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
1855 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
1856 // Cannot set non-blocking mode or timeout
1857 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
1862 if ($useProxy === true) {
1863 // Generate CONNECT request header
1864 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.1' . getConfig('HTTP_EOL');
1865 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1867 // Use login data to proxy? (username at least!)
1868 if (getConfig('proxy_username') != '') {
1870 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1871 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1874 // Add last new-line
1875 $proxyTunnel .= getConfig('HTTP_EOL');
1876 //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1879 fwrite($fp, $proxyTunnel);
1883 // No response received
1887 // Read the first line
1888 $resp = trim(fgets($fp, 10240));
1889 $respArray = explode(' ', $resp);
1890 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1891 // Invalid response!
1897 fwrite($fp, $request);
1900 $start = microtime(true);
1903 while (!feof($fp)) {
1904 // Get info from stream
1905 $info = stream_get_meta_data($fp);
1907 // Is it timed out? 15 seconds is a really patient...
1908 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1910 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1916 // Get line from stream
1917 $line = fgets($fp, 128);
1919 // Ignore empty lines because of non-blocking mode
1921 // uslepp a little to avoid 100% CPU load
1928 // Add it to response
1929 $response[] = trim($line);
1935 // Time request if debug-mode is enabled
1936 if (isDebugModeEnabled()) {
1937 // Add debug message...
1938 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds.');
1941 // Skip first empty lines
1943 foreach ($resp as $idx => $line) {
1945 $line = trim($line);
1947 // Is this line empty?
1950 array_shift($response);
1952 // Abort on first non-empty line
1957 //* DEBUG: */ print('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1958 //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1960 // Proxy agent found or something went wrong?
1961 if (!isset($response[0])) {
1962 // No response, maybe timeout
1963 $response = array('', '', '');
1964 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1965 // Proxy header detected, so remove two lines
1966 array_shift($response);
1967 array_shift($response);
1970 // Was the request successfull?
1971 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1972 // Not found / access forbidden
1973 $response = array('', '', '');
1980 // Taken from www.php.net isInStringIgnoreCase() user comments
1981 function isEmailValid ($email) {
1982 // Check first part of email address
1983 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1986 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1989 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1991 // Return check result
1992 return preg_match($regex, $email);
1995 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1996 function isUrlValid ($URL, $compile=true) {
1997 // Trim URL a little
1998 $URL = trim(urldecode($URL));
1999 //* DEBUG: */ outputHtml($URL.'<br />');
2001 // Compile some chars out...
2002 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
2003 //* DEBUG: */ outputHtml($URL.'<br />');
2005 // Check for the extension filter
2006 if (isExtensionActive('filter')) {
2007 // Use the extension's filter set
2008 return FILTER_VALIDATE_URL($URL, false);
2011 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2012 // https:// in front of the URLs
2013 return isUrlValidSimple($URL);
2016 // Generate a list of administrative links to a given userid
2017 function generateMemberAdminActionLinks ($userid, $status = '') {
2018 // Make sure userid is a number
2019 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
2021 // Define all main targets
2022 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2024 // Begin of navigation links
2027 foreach ($targetArray as $tar) {
2028 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
2029 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
2030 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2031 // Locked accounts shall be unlocked
2032 $OUT .= 'UNLOCK_USER';
2034 // All other status is fine
2035 $OUT .= strtoupper($tar);
2037 $OUT .= '_TITLE--}">{--ADMIN_';
2038 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2039 // Locked accounts shall be unlocked
2040 $OUT .= 'UNLOCK_USER';
2042 // All other status is fine
2043 $OUT .= strtoupper($tar);
2045 $OUT .= '--}</a></span> | ';
2048 // Finish navigation link
2049 $OUT = substr($OUT, 0, -7) . ']';
2055 // Generate an email link
2056 function generateEmailLink ($email, $table = 'admins') {
2057 // Default email link (INSECURE! Spammer can read this by harvester programs)
2058 $EMAIL = 'mailto:' . $email;
2060 // Check for several extensions
2061 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2062 // Create email link for contacting admin in guest area
2063 $EMAIL = generateAdminEmailLink($email);
2064 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2065 // Create email link for contacting a member within admin area (or later in other areas, too?)
2066 $EMAIL = generateUserEmailLink($email, 'admin');
2067 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2068 // Create email link to contact sponsor within admin area (or like the link above?)
2069 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2072 // Shall I close the link when there is no admin?
2073 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2075 // Return email link
2079 // Generate a hash for extra-security for all passwords
2080 function generateHash ($plainText, $salt = '', $hash = true) {
2082 //* DEBUG: */ outputHtml('plainText=' . $plainText . ',salt=' . $salt . ',hash='.intval($hash).'<br />');
2084 // Is the required extension 'sql_patches' there and a salt is not given?
2085 // 0123 4 43 3 4 432 2 3 32 2 3 3210
2086 if ((((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')))) {
2087 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2088 if ($hash === true) {
2089 // Is plain password
2090 return md5($plainText);
2092 // Is already a hash
2097 // Do we miss an arry element here?
2098 if (!isConfigEntrySet('file_hash')) {
2100 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2103 // When the salt is empty build a new one, else use the first x configured characters as the salt
2105 // Build server string for more entropy
2106 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2109 $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');
2112 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2114 // Calculate number for generating the code
2115 $a = time() + getConfig('_ADD') - 1;
2117 // Generate SHA1 sum from modula of number and the prime number
2118 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2119 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2120 $sha1 = scrambleString($sha1);
2121 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2122 //* DEBUG: */ $sha1b = descrambleString($sha1);
2123 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2125 // Generate the password salt string
2126 $salt = substr($sha1, 0, getConfig('salt_length'));
2127 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2130 //* DEBUG: */ outputHtml('salt=' . $salt . '<br />');
2131 $salt = substr($salt, 0, getConfig('salt_length'));
2132 //* DEBUG: */ outputHtml('salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />');
2134 // Sanity check on salt
2135 if (strlen($salt) != getConfig('salt_length')) {
2137 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2141 // Generate final hash (for debug output)
2142 $finalHash = $salt . sha1($salt . $plainText);
2145 //* DEBUG: */ outputHtml('finalHash=' . $finalHash);
2151 // Scramble a string
2152 function scrambleString($str) {
2156 // Final check, in case of failture it will return unscrambled string
2157 if (strlen($str) > 40) {
2158 // The string is to long
2160 } elseif (strlen($str) == 40) {
2162 $scrambleNums = explode(':', getConfig('pass_scramble'));
2164 // Generate new numbers
2165 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2168 // Compare both lengths and abort if different
2169 if (strlen($str) != count($scrambleNums)) return $str;
2171 // Scramble string here
2172 //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2173 for ($idx = '0'; $idx < strlen($str); $idx++) {
2174 // Get char on scrambled position
2175 $char = substr($str, $scrambleNums[$idx], 1);
2177 // Add it to final output string
2178 $scrambled .= $char;
2181 // Return scrambled string
2182 //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2186 // De-scramble a string scrambled by scrambleString()
2187 function descrambleString($str) {
2188 // Scramble only 40 chars long strings
2189 if (strlen($str) != 40) return $str;
2191 // Load numbers from config
2192 $scrambleNums = explode(':', getConfig('pass_scramble'));
2195 if (count($scrambleNums) != 40) return $str;
2197 // Begin descrambling
2198 $orig = str_repeat(' ', 40);
2199 //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2200 for ($idx = '0'; $idx < 40; $idx++) {
2201 $char = substr($str, $idx, 1);
2202 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2205 // Return scrambled string
2206 //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2210 // Generated a "string" for scrambling
2211 function genScrambleString ($len) {
2212 // Prepare array for the numbers
2213 $scrambleNumbers = array();
2215 // First we need to setup randomized numbers from 0 to 31
2216 for ($idx = '0'; $idx < $len; $idx++) {
2218 $rand = mt_rand(0, ($len -1));
2220 // Check for it by creating more numbers
2221 while (array_key_exists($rand, $scrambleNumbers)) {
2222 $rand = mt_rand(0, ($len -1));
2226 $scrambleNumbers[$rand] = $rand;
2229 // So let's create the string for storing it in database
2230 $scrambleString = implode(':', $scrambleNumbers);
2231 return $scrambleString;
2234 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2235 function encodeHashForCookie ($passHash) {
2236 // Return vanilla password hash
2239 // Is a secret key and master salt already initialized?
2240 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
2241 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2242 // Only calculate when the secret key is generated
2243 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getConfig('secret_key')));
2244 if ((strlen($passHash) != 49) || (strlen(getConfig('secret_key')) != 40)) {
2245 // Both keys must have same length so return unencrypted
2246 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getConfig('secret_key')) . '!=40');
2250 $newHash = ''; $start = 9;
2251 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
2252 for ($idx = 0; $idx < 20; $idx++) {
2253 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getConfig('secret_key'))), 2));
2254 $part2 = hexdec(substr(getConfig('secret_key'), $start, 2));
2255 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
2256 $mod = dechex($idx);
2257 if ($part1 > $part2) {
2258 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2259 } elseif ($part2 > $part1) {
2260 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2262 $mod = substr($mod, 0, 2);
2263 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
2264 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
2265 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
2270 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
2271 $ret = generateHash($newHash, getConfig('master_salt'));
2275 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
2279 // Fix "deleted" cookies
2280 function fixDeletedCookies ($cookies) {
2281 // Is this an array with entries?
2282 if ((is_array($cookies)) && (count($cookies) > 0)) {
2283 // Then check all cookies if they are marked as deleted!
2284 foreach ($cookies as $cookieName) {
2285 // Is the cookie set to "deleted"?
2286 if (getSession($cookieName) == 'deleted') {
2287 setSession($cookieName, '');
2293 // Output error messages in a fasioned way and die...
2294 function app_die ($F, $L, $message) {
2295 // Check if Script is already dieing and not let it kill itself another 1000 times
2296 if (!isset($GLOBALS['app_died'])) {
2297 // Make sure, that the script realy realy diese here and now
2298 $GLOBALS['app_died'] = true;
2300 // Set content type as text/html
2301 setContentType('text/html');
2304 loadIncludeOnce('inc/header.php');
2306 // Rewrite message for output
2307 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2309 // Better log this message away
2310 if ($F != 'debug_report_bug') logDebugMessage($F, $L, $message);
2312 // Load the message template
2313 loadTemplate('app_die_message', false, $message);
2316 loadIncludeOnce('inc/footer.php');
2318 // Script tried to kill itself twice
2319 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2323 // Display parsing time and number of SQL queries in footer
2324 function displayParsingTime() {
2325 // Is the timer started?
2326 if (!isset($GLOBALS['startTime'])) {
2332 $endTime = microtime(true);
2334 // "Explode" both times
2335 $start = explode(' ', $GLOBALS['startTime']);
2336 $end = explode(' ', $endTime);
2337 $runTime = $end[0] - $start[0];
2338 if ($runTime < 0) $runTime = '0';
2342 'runtime' => translateComma($runTime),
2343 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2346 // Load the template
2347 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
2350 // Check wether a boolean constant is set
2351 // Taken from user comments in PHP documentation for function constant()
2352 function isBooleanConstantAndTrue ($constName) { // : Boolean
2353 // Failed by default
2357 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2359 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-CACHE!<br />");
2360 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2363 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-RESOLVE!<br />");
2364 if (defined($constName)) {
2366 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-FOUND!<br />");
2367 $res = (constant($constName) === true);
2371 $GLOBALS['cache_array']['const'][$constName] = $res;
2373 //* DEBUG: */ var_dump($res);
2379 // Checks if a given apache module is loaded
2380 function isApacheModuleLoaded ($apacheModule) {
2381 // Check it and return result
2382 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2385 // Get current theme name
2386 function getCurrentTheme () {
2387 // The default theme is 'default'... ;-)
2390 // Do we have ext-theme installed and active?
2391 if (isExtensionActive('theme')) {
2392 // Call inner method
2393 $ret = getActualTheme();
2396 // Return theme value
2400 // Generates an error code from given account status
2401 function generateErrorCodeFromUserStatus ($status='') {
2402 // If no status is provided, use the default, cached
2403 if ((empty($status)) && (isMember())) {
2405 $status = getUserData('status');
2408 // Default error code if unknown account status
2409 $errorCode = getCode('UNKNOWN_STATUS');
2411 // Generate constant name
2412 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2414 // Is the constant there?
2415 if (isCodeSet($codeName)) {
2417 $errorCode = getCode($codeName);
2420 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2423 // Return error code
2427 // Back-ported from the new ship-simu engine. :-)
2428 function debug_get_printable_backtrace () {
2430 $backtrace = "<ol>\n";
2432 // Get and prepare backtrace for output
2433 $backtraceArray = debug_backtrace();
2434 foreach ($backtraceArray as $key => $trace) {
2435 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2436 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2437 if (!isset($trace['args'])) $trace['args'] = array();
2438 $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";
2442 $backtrace .= "</ol>\n";
2444 // Return the backtrace
2448 // A mail-able backtrace
2449 function debug_get_mailable_backtrace () {
2453 // Get and prepare backtrace for output
2454 $backtraceArray = debug_backtrace();
2455 foreach ($backtraceArray as $key => $trace) {
2456 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2457 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2458 if (!isset($trace['args'])) $trace['args'] = array();
2459 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2462 // Return the backtrace
2466 // Output a debug backtrace to the user
2467 function debug_report_bug ($message = '', $sendEmail = true) {
2468 // Is this already called?
2469 if (isset($GLOBALS[__FUNCTION__])) {
2471 print 'Message:'.$message.'<br />Backtrace:<pre>';
2472 debug_print_backtrace();
2476 // Set this function as called
2477 $GLOBALS[__FUNCTION__] = true;
2482 // Is the optional message set?
2483 if (!empty($message)) {
2485 $debug = sprintf("Note: %s<br />\n",
2489 // @TODO Add a little more infos here
2490 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2494 $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>";
2495 $debug .= debug_get_printable_backtrace();
2496 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2497 $debug .= "Thank you for finding bugs.";
2499 // Send an email? (e.g. not wanted for evaluation errors)
2500 if (($sendEmail === true) && (!isInstallationPhase())) {
2503 'message' => trim($message),
2504 'backtrace' => trim(debug_get_mailable_backtrace())
2507 // Send email to webmaster
2508 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2512 app_die(__FUNCTION__, __LINE__, $debug);
2515 // Generates a ***weak*** seed
2516 function generateSeed () {
2517 return microtime(true) * 100000;
2520 // Converts a message code to a human-readable message
2521 function getMessageFromErrorCode ($code) {
2525 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2526 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2527 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2528 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2529 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2530 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2531 case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2532 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2533 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2534 case getCode('ACCOUNT_LOCKED') : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2535 case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2536 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2537 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2538 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2539 case getCode('MODULE_MEM_ONLY') : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestParameter('mod')); break;
2540 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2541 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2542 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2543 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestParameter('blist'), 0); break;
2544 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2545 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2546 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2547 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2548 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2549 case getCode('MORE_RECEIVERS3') : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
2550 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2551 case getCode('NO_MAIL_TYPE') : $message = getMessage('MEMBER_NO_MAIL_TYPE_SELECTED'); break;
2552 case getCode('UNKNOWN_ERROR') : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
2553 case getCode('UNKNOWN_STATUS') : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
2555 case getCode('ERROR_MAILID'):
2556 if (isExtensionActive('mailid', true)) {
2557 $message = getMessage('ERROR_CONFIRMING_MAIL');
2559 $message = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'mailid');
2563 case getCode('EXTENSION_PROBLEM'):
2564 if (isGetRequestParameterSet('ext')) {
2565 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
2567 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2571 case getCode('URL_TLOCK'):
2572 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2573 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2574 array(bigintval(getRequestParameter('id'))), __FILE__, __LINE__);
2576 // Load timestamp from last order
2577 list($timestamp) = SQL_FETCHROW($result);
2580 SQL_FREERESULT($result);
2582 // Translate it for templates
2583 $timestamp = generateDateTime($timestamp, 1);
2585 // Calculate hours...
2586 $STD = round(getConfig('url_tlock') / 60 / 60);
2589 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2592 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2594 // Finally contruct the message
2595 // @TODO Rewrite this old lost code to a template
2596 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2597 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2598 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2602 // Missing/invalid code
2603 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2606 logDebugMessage(__FUNCTION__, __LINE__, $message);
2610 // Return the message
2614 // Compile characters which are allowed in URLs
2615 function compileUriCode ($code, $simple = true) {
2616 // Compile constants
2617 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2619 // Compile QUOT and other non-HTML codes
2620 $code = str_replace('{DOT}', '.',
2621 str_replace('{SLASH}', '/',
2622 str_replace('{QUOT}', "'",
2623 str_replace('{DOLLAR}', '$',
2624 str_replace('{OPEN_ANCHOR}', '(',
2625 str_replace('{CLOSE_ANCHOR}', ')',
2626 str_replace('{OPEN_SQR}', '[',
2627 str_replace('{CLOSE_SQR}', ']',
2628 str_replace('{PER}', '%',
2632 // Return compiled code
2636 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2637 function isUrlValidSimple ($url) {
2639 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2641 // Allows http and https
2642 $http = "(http|https)+(:\/\/)";
2644 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2645 // Test double-domains (e.g. .de.vu)
2646 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2648 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2650 $dir = "((/)+([-_\.[:alnum:]])+)*";
2652 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2653 // ... and the string after and including question character
2654 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2655 // Pattern for URLs like http://url/dir/doc.html?var=value
2656 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2657 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2658 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2659 // Pattern for URLs like http://url/dir/?var=value
2660 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2661 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2662 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2663 // Pattern for URLs like http://url/dir/page.ext
2664 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2665 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2666 $pattern['ipdp'] = $http . $ip . $dir . $page;
2667 // Pattern for URLs like http://url/dir
2668 $pattern['d1d'] = $http . $domain1 . $dir;
2669 $pattern['d2d'] = $http . $domain2 . $dir;
2670 $pattern['ipd'] = $http . $ip . $dir;
2671 // Pattern for URLs like http://url/?var=value
2672 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2673 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2674 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2675 // Pattern for URLs like http://url?var=value
2676 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2677 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2678 $pattern['ipg12'] = $http . $ip . $getstring1;
2679 // Test all patterns
2681 foreach ($pattern as $key => $pat) {
2683 if (isDebugRegExpressionEnabled()) {
2684 // @TODO Are these convertions still required?
2685 $pat = str_replace('.', "\.", $pat);
2686 $pat = str_replace('@', "\@", $pat);
2687 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2690 // Check if expression matches
2691 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2694 if ($reg === true) break;
2697 // Return true/false
2701 // Wtites data to a config.php-style file
2702 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2703 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2704 // Initialize some variables
2710 // Is the file there and read-/write-able?
2711 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2712 $search = 'CFG: ' . $comment;
2713 $tmp = $FQFN . '.tmp';
2715 // Open the source file
2716 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2718 // Is the resource valid?
2719 if (is_resource($fp)) {
2720 // Open temporary file
2721 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2723 // Is the resource again valid?
2724 if (is_resource($fp_tmp)) {
2725 // Mark temporary file as readable
2726 $GLOBALS['file_readable'][$tmp] = true;
2729 while (!feof($fp)) {
2730 // Read from source file
2731 $line = fgets ($fp, 1024);
2733 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2736 if ($next === $seek) {
2738 $line = $prefix . $DATA . $suffix . "\n";
2744 // Write to temp file
2745 fwrite($fp_tmp, $line);
2751 // Finished writing tmp file
2755 // Close source file
2758 if (($done === true) && ($found === true)) {
2759 // Copy back tmp file and delete tmp :-)
2760 copyFileVerified($tmp, $FQFN, 0644);
2761 return removeFile($tmp);
2762 } elseif ($found === false) {
2763 outputHtml('<strong>CHANGE:</strong> 404!');
2765 outputHtml('<strong>TMP:</strong> UNDONE!');
2769 // File not found, not readable or writeable
2770 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2773 // An error was detected!
2776 // Send notification to admin
2777 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2778 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2780 sendAdminsEmails($subject, $templateName, $content, $userid);
2782 // Send out out-dated way
2783 $message = loadEmailTemplate($templateName, $content, $userid);
2784 sendAdminEmails($subject, $message);
2788 // Debug message logger
2789 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2790 // Is debug mode enabled?
2791 if ((isDebugModeEnabled()) || ($force === true)) {
2793 $message = str_replace("\r", '', str_replace("\n", '', $message));
2795 // Log this message away, we better don't call app_die() here to prevent an endless loop
2796 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2797 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2802 // Handle extra values
2803 function handleExtraValues ($filterFunction, $value, $extraValue) {
2804 // Default is the value itself
2807 // Do we have a special filter function?
2808 if (!empty($filterFunction)) {
2809 // Does the filter function exist?
2810 if (function_exists($filterFunction)) {
2811 // Do we have extra parameters here?
2812 if (!empty($extraValue)) {
2813 // Put both parameters in one new array by default
2814 $args = array($value, $extraValue);
2816 // If we have an array simply use it and pre-extend it with our value
2817 if (is_array($extraValue)) {
2818 // Make the new args array
2819 $args = merge_array(array($value), $extraValue);
2822 // Call the multi-parameter call-back
2823 $ret = call_user_func_array($filterFunction, $args);
2825 // One parameter call
2826 $ret = call_user_func($filterFunction, $value);
2835 // Converts timestamp selections into a timestamp
2836 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2837 // Init test variable
2841 // Get last three chars
2842 $test = substr($id, -3);
2844 // Improved way of checking! :-)
2845 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2846 // Found a multi-selection for timings?
2847 $test = substr($id, 0, -3);
2848 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)) {
2849 // Generate timestamp
2850 $postData[$test] = createTimestampFromSelections($test, $postData);
2851 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2852 $GLOBALS['skip_config'][$test] = true;
2854 // Remove data from array
2855 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2856 unset($postData[$test . '_' . $rem]);
2867 // Reverts the german decimal comma into Computer decimal dot
2868 function convertCommaToDot ($str) {
2869 // Default float is not a float... ;-)
2872 // Which language is selected?
2873 switch (getLanguage()) {
2874 case 'de': // German language
2875 // Remove german thousand dots first
2876 $str = str_replace('.', '', $str);
2878 // Replace german commata with decimal dot and cast it
2879 $float = (float)str_replace(',', '.', $str);
2882 default: // US and so on
2883 // Remove thousand dots first and cast
2884 $float = (float)str_replace(',', '', $str);
2892 // Handle menu-depending failed logins and return the rendered content
2893 function handleLoginFailures ($accessLevel) {
2894 // Default output is empty ;-)
2897 // Is the session data set?
2898 if ((isSessionVariableSet('mxchange_' . $accessLevel . '_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel . '_last_failure'))) {
2899 // Ignore zero values
2900 if (getSession('mxchange_' . $accessLevel . '_failures') > 0) {
2901 // Non-guest has login failures found, get both data and prepare it for template
2902 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "accessLevel={$accessLevel}<br />");
2904 'login_failures' => getSession('mxchange_' . $accessLevel . '_failures'),
2905 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel . '_last_failure'), 2)
2909 $OUT = loadTemplate('login_failures', true, $content);
2912 // Reset session data
2913 setSession('mxchange_' . $accessLevel . '_failures', '');
2914 setSession('mxchange_' . $accessLevel . '_last_failure', '');
2917 // Return rendered content
2922 function rebuildCache ($cache, $inc = '', $force = false) {
2924 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
2926 // Shall I remove the cache file?
2927 if (isCacheInstanceValid()) {
2929 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2931 $GLOBALS['cache_instance']->removeCacheFile($force);
2934 // Include file given?
2937 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
2939 // Is the include there?
2940 if (isIncludeReadable($inc)) {
2941 // And rebuild it from scratch
2942 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
2945 // Include not found!
2946 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2952 // Determines the real remote address
2953 function determineRealRemoteAddress () {
2954 // Is a proxy in use?
2955 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2957 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
2958 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
2959 // Yet, another proxy
2960 $address = $_SERVER['HTTP_CLIENT_IP'];
2962 // The regular address when no proxy was used
2963 $address = $_SERVER['REMOTE_ADDR'];
2966 // This strips out the real address from proxy output
2967 if (strstr($address, ',')) {
2968 $addressArray = explode(',', $address);
2969 $address = $addressArray[0];
2972 // Return the result
2976 // Adds a bonus mail to the queue
2977 // This is a high-level function!
2978 function addNewBonusMail ($data, $mode = '', $output=true) {
2979 // Use mode from data if not set and availble ;-)
2980 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2982 // Generate receiver list
2983 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
2986 if (!empty($receiver)) {
2987 // Add bonus mail to queue
2988 addBonusMailToQueue(
3000 // Mail inserted into bonus pool
3001 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3002 } elseif ($output) {
3003 // More entered than can be reached!
3004 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3007 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3011 // Determines referal id and sets it
3012 function determineReferalId () {
3013 // Skip this in non-html-mode and outside ref.php
3014 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3016 // Check if refid is set
3017 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3019 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3020 // The variable user comes from the click-counter script click.php and we only accept this here
3021 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
3022 } elseif (isPostRequestParameterSet('refid')) {
3023 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3024 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
3025 } elseif (isGetRequestParameterSet('refid')) {
3026 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3027 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
3028 } elseif (isGetRequestParameterSet('ref')) {
3029 // Set refid=ref (the referal link uses such variable)
3030 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
3031 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3032 // Set session refid als global
3033 $GLOBALS['refid'] = bigintval(getSession('refid'));
3034 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3035 // Select a random user which has confirmed enougth mails
3036 $GLOBALS['refid'] = determineRandomReferalId();
3037 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3038 // Set default refid as refid in URL
3039 $GLOBALS['refid'] = getConfig('def_refid');
3041 // No default id when sql_patches is not installed or none set
3042 $GLOBALS['refid'] = '0';
3045 // Set cookie when default refid > 0
3046 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3047 // Default is not found
3050 // Do we have nickname or userid set?
3051 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3052 // Nickname in URL, so load the id
3053 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3054 } elseif ($GLOBALS['refid'] > 0) {
3055 // Direct userid entered
3056 $found = fetchUserData($GLOBALS['refid']);
3059 // Is the record valid?
3060 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3061 // No, then reset referal id
3062 $GLOBALS['refid'] = getConfig('def_refid');
3066 setSession('refid', $GLOBALS['refid']);
3069 // Return determined refid
3070 return $GLOBALS['refid'];
3073 // Enables the reset mode and runs it
3074 function doReset () {
3075 // Enable the reset mode
3076 $GLOBALS['reset_enabled'] = true;
3079 runFilterChain('reset');
3082 // Our shutdown-function
3083 function shutdown () {
3084 // Call the filter chain 'shutdown'
3085 runFilterChain('shutdown', null);
3087 // Check if not in installation phase and the link is up
3088 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
3090 SQL_CLOSE(__FILE__, __LINE__);
3091 } elseif (!isInstallationPhase()) {
3093 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3096 // Stop executing here
3101 function initMemberId () {
3102 $GLOBALS['member_id'] = '0';
3105 // Setter for member id
3106 function setMemberId ($memberid) {
3107 // We should not set member id to zero
3108 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3111 $GLOBALS['member_id'] = bigintval($memberid);
3114 // Getter for member id or returns zero
3115 function getMemberId () {
3116 // Default member id
3119 // Is the member id set?
3120 if (isMemberIdSet()) {
3122 $memberid = $GLOBALS['member_id'];
3129 // Checks ether the member id is set
3130 function isMemberIdSet () {
3131 return (isset($GLOBALS['member_id']));
3134 // Handle message codes from URL
3135 function handleCodeMessage () {
3136 if (isGetRequestParameterSet('code')) {
3137 // Default extension is 'unknown'
3140 // Is extension given?
3141 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
3143 // Convert the 'code' parameter from URL to a human-readable message
3144 $message = getMessageFromErrorCode(getRequestParameter('code'));
3146 // Load message template
3147 loadTemplate('message', false, $message);
3151 // Setter for extra title
3152 function setExtraTitle ($extraTitle) {
3153 $GLOBALS['extra_title'] = $extraTitle;
3156 // Getter for extra title
3157 function getExtraTitle () {
3158 // Is the extra title set?
3159 if (!isExtraTitleSet()) {
3160 // No, then abort here
3161 debug_report_bug('extra_title is not set!');
3165 return $GLOBALS['extra_title'];
3168 // Checks if the extra title is set
3169 function isExtraTitleSet () {
3170 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3173 // Generates a 'extension foo inactive' message
3174 function generateExtensionInactiveMessage ($ext_name) {
3175 // Is the extension empty?
3176 if (empty($ext_name)) {
3177 // This should not happen
3178 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3182 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3184 // Is an admin logged in?
3186 // Then output admin message
3187 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3190 // Return prepared message
3194 // Generates a 'extension foo not installed' message
3195 function generateExtensionNotInstalledMessage ($ext_name) {
3196 // Is the extension empty?
3197 if (empty($ext_name)) {
3198 // This should not happen
3199 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3203 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3205 // Is an admin logged in?
3207 // Then output admin message
3208 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3211 // Return prepared message
3215 // Generates a message depending on if the extension is not installed or not
3217 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3221 // Is the extension not installed or just deactivated?
3222 switch (isExtensionInstalled($ext_name)) {
3223 case true; // Deactivated!
3224 $message = generateExtensionInactiveMessage($ext_name);
3227 case false; // Not installed!
3228 $message = generateExtensionNotInstalledMessage($ext_name);
3231 default: // Should not happen!
3232 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3233 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3237 // Return the message
3241 // Reads a directory recursively by default and searches for files not matching
3242 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3243 // a whole directory.
3244 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3245 // Add default entries we should exclude
3246 $excludeArray[] = '.';
3247 $excludeArray[] = '..';
3248 $excludeArray[] = '.svn';
3249 $excludeArray[] = '.htaccess';
3251 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3256 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3259 while ($baseFile = readdir($dirPointer)) {
3260 // Exclude '.', '..' and entries in $excludeArray automatically
3261 if (in_array($baseFile, $excludeArray, true)) {
3263 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3267 // Construct include filename and FQFN
3268 $fileName = $baseDir . $baseFile;
3269 $FQFN = getConfig('PATH') . $fileName;
3271 // Remove double slashes
3272 $FQFN = str_replace('//', '/', $FQFN);
3274 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3275 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3276 // These Lines are only for debugging!!
3277 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3278 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3279 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3285 // Skip also files with non-matching prefix genericly
3286 if (($recursive === true) && (isDirectory($FQFN))) {
3287 // Is a redirectory so read it as well
3288 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3290 // And skip further processing
3292 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3294 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3296 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3297 // Skip wrong suffix as well
3298 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3300 } elseif (!isFileReadable($FQFN)) {
3301 // Not readable so skip it
3302 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3306 // Is the file a PHP script or other?
3307 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3308 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3309 // Is this a valid include file?
3310 if ($extension == '.php') {
3311 // Remove both for extension name
3312 $extName = substr($baseFile, strlen($prefix), -4);
3314 // Is the extension valid and active?
3315 if (isExtensionNameValid($extName)) {
3316 // Then add this file
3317 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3318 $files[] = $fileName;
3320 // Add non-extension files as well
3321 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3322 if ($addBaseDir === true) {
3323 $files[] = $fileName;
3325 $files[] = $baseFile;
3329 // We found .php file but should not search for them, why?
3330 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3332 } elseif (substr($baseFile, -4, 4) == $extension) {
3333 // Other, generic file found
3334 $files[] = $fileName;
3339 closedir($dirPointer);
3344 // Return array with include files
3345 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3349 // Maps a module name into a database table name
3350 function mapModuleToTable ($moduleName) {
3351 // Map only these, still lame code...
3352 switch ($moduleName) {
3353 // 'index' is the guest's menu
3354 case 'index': $moduleName = 'guest'; break;
3355 // ... and 'login' the member's menu
3356 case 'login': $moduleName = 'member'; break;
3357 // Anything else will not be mapped, silently.
3364 // Add SQL debug data to array for later output
3365 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3366 // Already executed?
3367 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3368 // Then abort here, we don't need to profile a query twice
3372 // Remeber this as profiled (or not, but we don't care here)
3373 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3375 // Do we have cache?
3376 if (!isset($GLOBALS['debug_sql_available'])) {
3377 // Check it and cache it in $GLOBALS
3378 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3381 // Don't execute anything here if we don't need or ext-other is missing
3382 if ($GLOBALS['debug_sql_available'] === false) {
3388 'num_rows' => SQL_NUMROWS($result),
3389 'affected' => SQL_AFFECTEDROWS(),
3390 'sql_str' => $sqlString,
3391 'timing' => $timing,
3392 'file' => basename($F),
3397 $GLOBALS['debug_sqls'][] = $record;
3400 // Initializes the cache instance
3401 function initCacheInstance () {
3402 // Load include for CacheSystem class
3403 loadIncludeOnce('inc/classes/cachesystem.class.php');
3405 // Initialize cache system only when it's needed
3406 $GLOBALS['cache_instance'] = new CacheSystem();
3407 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3408 // Failed to initialize cache sustem
3409 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3413 // Getter for message from array or raw message
3414 function getMessageFromIndexedArray ($message, $pos, $array) {
3415 // Check if the requested message was found in array
3416 if (isset($array[$pos])) {
3417 // ... if yes then use it!
3418 $ret = $array[$pos];
3420 // ... else use default message
3428 // Print code with line numbers
3429 function linenumberCode ($code) {
3430 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3431 $count_lines = count($codeE);
3433 $r = 'Line | Code:<br />';
3434 foreach($codeE as $line => $c) {
3435 $r .= '<div class="line"><span class="linenum">';
3436 if ($count_lines == 1) {
3439 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3444 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3447 return '<div class="code">' . $r . '</div>';
3450 // Convert ';' to ', ' for e.g. receiver list
3451 function convertReceivers ($old) {
3452 return str_replace(';', ', ', $old);
3455 // Determines the right page title
3456 function determinePageTitle () {
3457 // Config and database connection valid?
3458 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3462 // Title decoration enabled?
3463 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3465 // Do we have some extra title?
3466 if (isExtraTitleSet()) {
3468 $TITLE .= getExtraTitle() . ' by ';
3472 $TITLE .= getConfig('MAIN_TITLE');
3474 // Add title of module? (middle decoration will also be added!)
3475 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3476 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3479 // Add title from what file
3481 if (getModule() == 'login') $mode = 'member';
3482 elseif (getModule() == 'index') $mode = 'guest';
3483 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3485 // Add title decorations? (right)
3486 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3488 // Remember title in constant for the template
3489 $pageTitle = $TITLE;
3490 } elseif ((isInstalled()) && (isAdminRegistered())) {
3491 // Installed, admin registered but no ext-sql_patches
3492 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3493 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3494 // Installed but no admin registered
3495 $pageTitle = getMessage('SETUP_OF_MXCHANGE');
3496 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3497 // Installation mode
3498 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3500 // Configuration not found!
3501 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3503 // Do not add the fatal message in installation mode
3504 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3508 return decodeEntities($pageTitle);
3511 // Checks wethere there is a cache file there. This function is cached.
3512 function isTemplateCached ($template) {
3513 // Do we have cached this result?
3514 if (!isset($GLOBALS['template_cache'][$template])) {
3516 $FQFN = generateCacheFqfn($template);
3519 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3523 return $GLOBALS['template_cache'][$template];
3526 // Flushes non-flushed template cache to disk
3527 function flushTemplateCache ($template, $eval) {
3528 // Is this cache flushed?
3529 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3531 $FQFN = generateCacheFqfn($template);
3533 // Replace username with a call
3534 $eval = str_replace('$username', '".getUsername()."', $eval);
3537 writeToFile($FQFN, $eval, true);
3541 // Reads a template cache
3542 function readTemplateCache ($template) {
3544 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3546 $FQFN = generateCacheFqfn($template);
3549 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3553 return $GLOBALS['template_eval'][$template];
3556 // Escapes quotes (default is only double-quotes)
3557 function escapeQuotes ($str, $single = false) {
3558 // Should we escape all?
3559 if ($single === true) {
3560 // Escape all (including null)
3561 $str = addslashes($str);
3563 // Escape only double-quotes but prevent double-quoting
3564 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3567 // Return the escaped string
3571 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3572 function escapeJavaScriptQuotes ($str) {
3573 // Replace all double-quotes and secure back-ticks
3574 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3580 // Send out mails depending on the 'mod/modes' combination
3581 // @TODO Lame description for this function
3582 function sendModeMails ($mod, $modes) {
3584 if (fetchUserData(getMemberId())) {
3585 // Extract salt from cookie
3586 $salt = substr(getSession('u_hash'), 0, -40);
3588 // Now let's compare passwords
3589 $hash = encodeHashForCookie(getUserData('password'));
3591 // Does the hash match or should we change it?
3592 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
3594 $content = getUserDataArray();
3597 $content['gender'] = translateGender($content['gender']);
3599 // Clear/init the content variable
3600 $content['message'] = '';
3603 // @TODO Move this in a filter
3606 foreach ($modes as $mode) {
3608 case 'normal': break; // Do not add any special lines
3609 case 'email': // Email was changed!
3610 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestParameter('old_email')."\n";
3613 case 'pass': // Password was changed
3614 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3618 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3619 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3624 if (isExtensionActive('country')) {
3625 // Replace code with description
3626 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
3629 // Merge content with data from POST
3630 $content = merge_array($content, postRequestArray());
3633 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3635 if (getConfig('admin_notify') == 'Y') {
3636 // The admin needs to be notified about a profile change
3637 $message_admin = 'admin_mydata_notify';
3638 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3641 $message_admin = '';
3645 // Set subject lines
3646 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3648 // Output success message
3649 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3652 default: // Unsupported module!
3653 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3654 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
3658 // Passwords mismatch
3659 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
3662 // Could not load profile
3663 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
3666 // Send email to user if required
3667 if ((!empty($sub_mem)) && (!empty($message))) {
3669 sendEmail($content['email'], $sub_mem, $message);
3672 // Send only if no other error has occured
3673 if (empty($content)) {
3674 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3676 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3677 } elseif (getConfig('admin_notify') == 'Y') {
3678 // Cannot send mails to admin!
3679 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3682 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3687 loadTemplate('admin_settings_saved', false, $content);
3690 // Generates a 'selection box' from given array
3691 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent='') {
3693 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3694 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3696 // Walk through all options
3697 foreach ($options as $option) {
3698 // Add the <option> entry
3699 if (empty($optionContent)) {
3700 // ... from template
3701 $OUT .= loadTemplate('select_' . $name . '_option', true, $option);
3704 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3708 // Finish selection box
3709 $OUT .= '</select>';
3713 'selection_box' => $OUT,
3714 'module' => getModule(),
3718 // Load template and return it
3719 return loadTemplate('select_' . $name . '_box', true, $content);
3722 // Get a module from filename and access level
3723 function getModuleFromFileName ($file, $accessLevel) {
3724 // Default is 'invalid';
3725 $modCheck = 'invalid';
3727 // @TODO This is still very static, rewrite it somehow
3728 switch ($accessLevel) {
3730 $modCheck = 'admin';
3736 $modCheck = getModule();
3739 default: // Unsupported file name / access level
3740 debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3748 // Encodes an URL for adding session id, etc.
3749 function encodeUrl ($url, $outputMode = '0') {
3750 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
3751 if ((strpos($url, session_name()) !== false) || (getOutputMode() == -3)) return $url;
3753 // Do we have a valid session?
3754 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3756 // Determine right seperator
3757 $seperator = '&';
3758 if (strpos($url, '?') === false) {
3761 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3767 if (session_id() != '') {
3768 $url .= $seperator . session_name() . '=' . session_id();
3773 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3775 $url = '{?URL?}/' . $url;
3782 // Simple check for spider
3783 function isSpider () {
3785 $userAgent = strtolower(detectUserAgent(true));
3787 // It should not be empty, if so it is better a spider/bot
3788 if (empty($userAgent)) return true;
3791 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
3794 // Prepares the header for HTML output
3795 function loadHtmlHeader () {
3797 // 1.) pre_page_header (mainly loads the page_header template and includes
3798 // meta description)
3799 runFilterChain('pre_page_header');
3801 // Here can be something be added, but normally one of the two filters
3802 // around this line should do the job for you.
3804 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
3805 // to close the head-tag)
3806 // Include more header data here
3807 runFilterChain('post_page_header');
3810 // Adds page header and footer to output array element
3811 function addPageHeaderFooter () {
3815 // Add them all together. This is maybe to simple
3816 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
3817 // Add page part if set
3818 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
3821 // Transfer $OUT to 'output'
3822 $GLOBALS['output'] = $OUT;
3825 // Generates meta description for current module and 'what' value
3826 function generateMetaDescriptionCode () {
3827 // Only include from guest area
3828 if (getModule() == 'index') {
3829 // Construct dynamic description
3830 $DESCR = '{?MAIN_TITLE?} '.trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
3832 // Output it directly
3833 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
3837 unset($GLOBALS['ref_level']);
3840 // Generates an FQFN for template cache from the given template name
3841 function generateCacheFqfn ($template) {
3843 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
3844 // Generate the FQFN
3845 $GLOBALS['template_cache_fqfn'][$template] = sprintf("%s_compiled/html/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3849 return $GLOBALS['template_cache_fqfn'][$template];
3852 // Function to search for the last modified file
3853 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
3855 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
3856 // Does it match what we are looking for? (We skip a lot files already!)
3857 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
3858 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
3860 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
3861 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
3863 // Walk through all entries
3864 foreach ($ds as $d) {
3865 // Generate proper FQFN
3866 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir . '/' . $d);
3868 // Is it a file and readable?
3869 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
3870 if (isFileReadable($FQFN)) {
3871 // $FQFN is a readable file so extract the requested data from it
3872 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
3873 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
3875 // Is the file more recent?
3876 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
3877 // This file is newer as the file before
3878 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
3879 $last_changed['path_name'] = $FQFN;
3880 $last_changed[$lookFor] = $check;
3884 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
3889 //////////////////////////////////////////////////
3890 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3891 //////////////////////////////////////////////////
3893 if (!function_exists('html_entity_decode')) {
3894 // Taken from documentation on www.php.net
3895 function html_entity_decode ($string) {
3896 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3897 $trans_tbl = array_flip($trans_tbl);
3898 return strtr($string, $trans_tbl);
3902 if (!function_exists('http_build_query')) {
3903 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
3904 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
3906 foreach ((array)$data as $k => $v) {
3907 if (is_int($k) && $prefix != null) {
3908 $k = urlencode($prefix . $k);
3911 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
3913 if (is_array($v) || is_object($v)) {
3914 array_push($ret, http_build_query($v, '', $sep, $k));
3916 array_push($ret, $k.'='.urlencode($v));
3920 if (empty($sep)) $sep = ini_get('arg_separator.output');
3922 return implode($sep, $ret);