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'])) {
49 $GLOBALS['output'] = '';
53 $username = getMessage('USERNAME_UNKNOWN');
54 if (isset($GLOBALS['username'])) $username = getUsername();
56 // Do we have HTML-Code here?
57 if (!empty($htmlCode)) {
58 // Yes, so we handle it as you have configured
59 switch (getConfig('OUTPUT_MODE')) {
61 // That's why you don't need any \n at the end of your HTML code... :-)
62 if (getPhpCaching() == 'on') {
63 // Output into PHP's internal buffer
64 outputRawCode($htmlCode);
66 // That's why you don't need any \n at the end of your HTML code... :-)
67 if ($newLine === true) print("\n");
69 // Render mode for old or lame servers...
70 $GLOBALS['output'] .= $htmlCode;
72 // That's why you don't need any \n at the end of your HTML code... :-)
73 if ($newLine === true) $GLOBALS['output'] .= "\n";
78 // If we are switching from render to direct output rendered code
79 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
81 // The same as above... ^
82 outputRawCode($htmlCode);
83 if ($newLine === true) print("\n");
87 // Huh, something goes wrong or maybe you have edited config.php ???
88 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
91 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
92 // Output cached HTML code
93 $GLOBALS['output'] = ob_get_contents();
95 // Clear output buffer for later output if output is found
96 if (!empty($GLOBALS['output'])) {
100 // Extension 'rewrite' installed?
101 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
102 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
105 // Send all HTTP headers
108 // Compile and run finished rendered HTML code
109 compileFinalOutput();
111 // Output code here, DO NOT REMOVE! ;-)
112 outputRawCode($GLOBALS['output']);
113 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
114 // Rewrite links when rewrite extension is active
115 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
116 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
119 // Send all HTTP headers
122 // Compile and run finished rendered HTML code
123 compileFinalOutput();
125 // Output code here, DO NOT REMOVE! ;-)
126 outputRawCode($GLOBALS['output']);
128 // And flush all headers
133 // Sends out all headers required for HTTP/1.1 reply
134 function sendHttpHeaders () {
136 $now = gmdate('D, d M Y H:i:s') . ' GMT';
139 sendHeader('HTTP/1.1 200 OK');
141 // General headers for no caching
142 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
143 sendHeader('Last-Modified: ' . $now);
144 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
145 sendHeader('Pragma: no-cache'); // HTTP/1.0
146 sendHeader('Connection: Close');
147 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
148 sendHeader('Content-Language: ' . getLanguage());
151 // Compiles the final output
152 function compileFinalOutput () {
156 // Add page header and footer
157 addPageHeaderFooter();
160 while (((strpos($GLOBALS['output'], '{--') !== false) || (strpos($GLOBALS['output'], '{DQUOTE}') !== false) || (strpos($GLOBALS['output'], '{!') !== false) || (strpos($GLOBALS['output'], '{?') !== false) || (strpos($GLOBALS['output'], '{%') !== false)) && ($cnt < 3)) {
161 // Init common variables
166 //* DEBUG: */ print '<pre>'.htmlentities($GLOBALS['output']).'</pre>';
167 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($GLOBALS['output']))) . '";';
168 //* DEBUG: */ die('<pre>'.htmlentities($eval).'</pre>');
170 //* DEBUG: */ die('<pre>'.htmlentities($newContent).'</pre>');
172 // Was that eval okay?
173 if (empty($newContent)) {
174 // Something went wrong!
175 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
179 $GLOBALS['output'] = $newContent;
186 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
187 // Compress it for HTTP gzip
188 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
191 sendHeader('Content-Encoding: gzip');
192 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
193 // Compress it for HTTP deflate
194 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
197 sendHeader('Content-Encoding: deflate');
201 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
207 // Output the raw HTML code
208 function outputRawCode ($htmlCode) {
209 // Output stripped HTML code to avoid broken JavaScript code, etc.
210 print(str_replace('{BACK}', "\\", $htmlCode));
212 // Flush the output if only getPhpCaching() is not 'on'
213 if (getPhpCaching() != 'on') {
219 // Init fatal message array
220 function initFatalMessages () {
221 $GLOBALS['fatal_messages'] = array();
224 // Getter for whole fatal error messages
225 function getFatalArray () {
226 return $GLOBALS['fatal_messages'];
229 // Add a fatal error message to the queue array
230 function addFatalMessage ($F, $L, $message, $extra = '') {
231 if (is_array($extra)) {
232 // Multiple extras for a message with masks
233 $message = call_user_func_array('sprintf', $extra);
234 } elseif (!empty($extra)) {
235 // $message is text with a mask plus extras to insert into the text
236 $message = sprintf($message, $extra);
239 // Add message to $GLOBALS['fatal_messages']
240 $GLOBALS['fatal_messages'][] = $message;
242 // Log fatal messages away
243 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
246 // Getter for total fatal message count
247 function getTotalFatalErrors () {
251 // Do we have at least the first entry?
252 if (!empty($GLOBALS['fatal_messages'][0])) {
254 $count = count($GLOBALS['fatal_messages']);
261 // Load a template file and return it's content (only it's name; do not use ' or ")
262 function loadTemplate ($template, $return = false, $content = array()) {
263 // @TODO Remove this sanity-check if all is fine
264 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
266 // @TODO Try to rewrite all $DATA to $content
270 if (isTemplateCached($template)) {
271 // Evaluate the cache
272 eval(readTemplateCache($template));
273 } elseif (!isset($GLOBALS['template_eval'][$template])) {
274 // Add more variables which you want to use in your template files
275 $username = getUsername();
277 // Make all template names lowercase
278 $template = strtolower($template);
282 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
285 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
286 $extraPath = detectExtraTemplatePath($template);;
288 ////////////////////////
289 // Generate file name //
290 ////////////////////////
291 $FQFN = $basePath . $extraPath . $template . '.tpl';
293 // Does the special template exists?
294 if (!isFileReadable($FQFN)) {
295 // Reset to default template
296 $FQFN = $basePath . $template . '.tpl';
299 // Now does the final template exists?
300 if (isFileReadable($FQFN)) {
301 // Count the template load
302 incrementConfigEntry('num_templates');
304 // The local file does exists so we load it. :)
305 $GLOBALS['tpl_content'] = readFromFile($FQFN);
307 // Do we have to compile the code?
309 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)) {
310 // Normal HTML output?
311 if (getOutputMode() == '0') {
312 // Add surrounding HTML comments to help finding bugs faster
313 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
315 // Prepare eval() command
316 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
317 } elseif (substr($template, 0, 3) == 'js_') {
318 // JavaScripts don't like entities and timings
319 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
321 // Prepare eval() command, other output doesn't like entities, maybe
322 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
325 // Add surrounding HTML comments to help finding bugs faster
326 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
327 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
330 // Cache the eval() command here
331 $GLOBALS['template_eval'][$template] = $eval;
334 eval($GLOBALS['template_eval'][$template]);
335 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
336 // Only admins shall see this warning or when installation mode is active
337 $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
338 (' . $template . ')<br />
340 {--TEMPLATE_CONTENT--}
341 <pre>' . print_r($content, true) . '</pre>
343 <pre>' . print_r($DATA, true) . '</pre>
347 $GLOBALS['template_eval'][$template] = '404';
351 eval($GLOBALS['template_eval'][$template]);
354 // Do we have some content to output or return?
356 // Not empty so let's put it out! ;)
357 if ($return === true) {
358 // Return the HTML code
364 } elseif (isDebugModeEnabled()) {
365 // Warning, empty output!
366 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
370 // Detects the extra template path from given template name
371 function detectExtraTemplatePath ($template) {
376 if (!isset($GLOBALS['extra_path'][$template])) {
377 // Check for admin/guest/member/etc. templates
378 if (substr($template, 0, 6) == 'admin_') {
379 // Admin template found
380 $extraPath = 'admin/';
381 } elseif (substr($template, 0, 6) == 'guest_') {
382 // Guest template found
383 $extraPath = 'guest/';
384 } elseif (substr($template, 0, 7) == 'member_') {
385 // Member template found
386 $extraPath = 'member/';
387 } elseif (substr($template, 0, 7) == 'select_') {
388 // Selection template found
389 $extraPath = 'select/';
390 } elseif (substr($template, 0, 8) == 'install_') {
391 // Installation template found
392 $extraPath = 'install/';
393 } elseif (substr($template, 0, 4) == 'ext_') {
394 // Extension template found
396 } elseif (substr($template, 0, 3) == 'la_') {
397 // 'Logical-area' template found
399 } elseif (substr($template, 0, 3) == 'js_') {
400 // JavaScript template found
402 } elseif (substr($template, 0, 5) == 'menu_') {
403 // Menu template found
404 $extraPath = 'menu/';
406 // Test for extension
407 $test = substr($template, 0, strpos($template, '_'));
409 // Probe for valid extension name
410 if (isExtensionNameValid($test)) {
411 // Set extra path to extension's name
412 $extraPath = $test . '/';
417 $GLOBALS['extra_path'][$template] = $extraPath;
421 return $GLOBALS['extra_path'][$template];
424 // Loads an email template and compiles it
425 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
428 // Make sure all template names are lowercase!
429 $template = strtolower($template);
431 // Default 'nickname' if extension is not installed
434 // Neutral email address is default
435 $email = getConfig('WEBMASTER');
437 // Is content an array?
438 if (is_array($content)) {
439 // Add expiration to array
440 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
441 // Will never expire!
442 $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
443 } elseif (isConfigEntrySet('auto_purge')) {
444 // Create nice date string
445 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
448 $content['expiration'] = getMessage('MAIL_NO_CONFIG_AUTO_PURGE');
453 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content).'<br />');
454 if (($userid > 0) && (is_array($content))) {
455 // If nickname extension is installed, fetch nickname as well
456 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
457 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
459 fetchUserData($userid, 'nickname');
461 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
463 fetchUserData($userid);
466 // Merge data if valid
467 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
468 if (isUserDataValid()) {
469 $content = merge_array($content, getUserDataArray());
471 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
474 // Translate M to male or F to female if present
475 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
477 // Overwrite email from data if present
478 if (isset($content['email'])) $email = $content['email'];
480 // Store email for some functions in global $DATA array
481 // @TODO Do only use $content, not $DATA or raw variables
482 $DATA['email'] = $email;
485 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
488 $extraPath = detectExtraTemplatePath($template);
490 // Generate full FQFN
491 $FQFN = $basePath . $extraPath . $template . '.tpl';
493 // Does the special template exists?
494 if (!isFileReadable($FQFN)) {
495 // Reset to default template
496 $FQFN = $basePath . $template . '.tpl';
499 // Now does the final template exists?
501 if (isFileReadable($FQFN)) {
502 // The local file does exists so we load it. :)
503 $GLOBALS['tpl_content'] = readFromFile($FQFN);
506 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
507 eval($GLOBALS['tpl_content']);
508 } elseif (!empty($template)) {
509 // Template file not found!
510 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
511 {--TEMPLATE_CONTENT--}
512 <pre>' . print_r($content, true) . '</pre>
514 <pre>' . print_r($DATA, true) . '</pre>
517 // Debug mode not active? Then remove the HTML tags
518 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
520 // No template name supplied!
521 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
524 // Is there some content?
525 if (empty($newContent)) {
527 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
529 // Add last error if the required function exists
530 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
533 // Remove content and data
541 // Send mail out to an email address
542 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
543 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail},SUBJECT={$subject}<br />");
545 // Compile subject line (for POINTS constant etc.)
546 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
549 if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
550 // Value detected, is the message extension installed?
551 // @TODO Extension 'msg' does not exist
552 if (isExtensionActive('msg')) {
553 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
556 // Does the user exist?
557 if (fetchUserData($toEmail)) {
559 $toEmail = getUserData('email');
562 $toEmail = getConfig('WEBMASTER');
565 } elseif ($toEmail == '0') {
567 $toEmail = getConfig('WEBMASTER');
569 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
571 // Check for PHPMailer or debug-mode
572 if (!checkPhpMailerUsage()) {
573 // Not in PHPMailer-Mode
574 if (empty($mailHeader)) {
575 // Load email header template
576 $mailHeader = loadEmailTemplate('header');
579 $mailHeader .= loadEmailTemplate('header');
581 } elseif (isDebugModeEnabled()) {
582 if (empty($mailHeader)) {
583 // Load email header template
584 $mailHeader = loadEmailTemplate('header');
587 $mailHeader .= loadEmailTemplate('header');
592 eval('$toEmail = "' . compileRawCode(escapeQuotes($toEmail)) . '";');
595 eval('$message = "' . str_replace('$', '$', compileRawCode(escapeQuotes($message))) . '";');
597 // Fix HTML parameter (default is no!)
598 if (empty($isHtml)) $isHtml = 'N';
599 if (isDebugModeEnabled()) {
600 // In debug mode we want to display the mail instead of sending it away so we can debug this part
602 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
603 To : ' . htmlentities(utf8_decode($toEmail)) . '
604 Subject : ' . htmlentities(utf8_decode($subject)) . '
605 Message : ' . htmlentities(utf8_decode($message)) . '
607 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
608 // Send mail as HTML away
609 return sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
610 } elseif (!empty($toEmail)) {
612 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
613 } elseif ($isHtml != 'Y') {
615 return sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
619 // Check to use wether legacy mail() command or PHPMailer class
620 // @TODO Rewrite this to an extension 'smtp'
622 function checkPhpMailerUsage() {
623 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
626 // Send out a raw email with PHPMailer class or legacy mail() command
627 function sendRawEmail ($toEmail, $subject, $message, $from) {
628 // Just compile all again, to put out all configs, etc.
629 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
630 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
631 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
632 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
634 // Shall we use PHPMailer class or legacy mode?
635 if (checkPhpMailerUsage()) {
636 // Use PHPMailer class with SMTP enabled
637 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
638 loadIncludeOnce('inc/phpmailer/class.smtp.php');
641 $mail = new PHPMailer();
643 // Set charset to UTF-8
644 $mail->CharSet = 'UTF-8';
646 // Path for PHPMailer
647 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
650 $mail->SMTPAuth = true;
651 $mail->Host = getConfig('SMTP_HOSTNAME');
653 $mail->Username = getConfig('SMTP_USER');
654 $mail->Password = getConfig('SMTP_PASSWORD');
656 $mail->From = getConfig('WEBMASTER');
660 $mail->FromName = getConfig('MAIN_TITLE');
661 $mail->Subject = $subject;
662 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
663 $mail->Body = $message;
664 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
665 $mail->WordWrap = 70;
668 $mail->Body = decodeEntities($message);
670 $mail->AddAddress($toEmail, '');
671 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
672 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
673 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
676 // Has an error occured?
677 if (!empty($mail->ErrorInfo)) {
679 logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
688 // Use legacy mail() command
689 return mail($toEmail, $subject, decodeEntities($message), $from);
693 // Generate a password in a specified length or use default password length
694 function generatePassword ($length = '0') {
695 // Auto-fix invalid length of zero
696 if ($length == '0') $length = getConfig('pass_len');
698 // Initialize array with all allowed chars
699 $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,-,+,_,/,.');
701 // Start creating password
703 for ($i = '0'; $i < $length; $i++) {
704 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
707 // When the size is below 40 we can also add additional security by scrambling
708 // it. Otherwise we may corrupt hashes
709 if (strlen($PASS) <= 40) {
710 // Also scramble the password
711 $PASS = scrambleString($PASS);
714 // Return the password
718 // Generates a human-readable timestamp from the Uni* stamp
719 function generateDateTime ($time, $mode = '0') {
720 // Filter out numbers
721 $time = bigintval($time);
723 // If the stamp is zero it mostly didn't "happen"
726 return getMessage('NEVER_HAPPENED');
729 switch (getLanguage()) {
730 case 'de': // German date / time format
732 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
733 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
734 case '2': $ret = date('d.m.Y|H:i', $time); break;
735 case '3': $ret = date('d.m.Y', $time); break;
737 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
742 default: // Default is the US date / time format!
744 case '0': $ret = date('r', $time); break;
745 case '1': $ret = date('Y-m-d - g:i A', $time); break;
746 case '2': $ret = date('y-m-d|H:i', $time); break;
747 case '3': $ret = date('y-m-d', $time); break;
749 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
758 // Translates Y/N to yes/no
759 function translateYesNo ($yn) {
761 $translated = '??? (' . $yn . ')';
763 case 'Y': $translated = getMessage('YES'); break;
764 case 'N': $translated = getMessage('NO'); break;
767 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
775 // Translates the "pool type" into human-readable
776 function translatePoolType ($type) {
777 // Default?type is unknown
778 $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
781 $constName = sprintf("POOL_TYPE_%s", $type);
784 if (isMessageIdValid($constName)) {
786 $translated = getMessage($constName);
789 // Return "translation"
793 // Translates the american decimal dot into a german comma
794 function translateComma ($dotted, $cut = true, $max = '0') {
795 // First, cast all to double, due to PHP changes
796 $dotted = (double) $dotted;
798 // Default is 3 you can change this in admin area "Misc -> Misc Options"
799 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
801 // Use from config is default
802 $maxComma = getConfig('max_comma');
804 // Use from parameter?
805 if ($max > 0) $maxComma = $max;
808 if (($cut === true) && ($max == '0')) {
809 // Test for commata if in cut-mode
810 $com = explode('.', $dotted);
811 if (count($com) < 2) {
812 // Don't display commatas even if there are none... ;-)
818 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
821 switch (getLanguage()) {
822 case 'de': // German language
823 $dotted = number_format($dotted, $maxComma, ',', '.');
826 default: // All others
827 $dotted = number_format($dotted, $maxComma, '.', ',');
831 // Return translated value
835 // Translate Uni*-like gender to human-readable
836 function translateGender ($gender) {
838 $ret = '!' . $gender . '!';
840 // Male/female or company?
842 case 'M': $ret = getMessage('GENDER_M'); break;
843 case 'F': $ret = getMessage('GENDER_F'); break;
844 case 'C': $ret = getMessage('GENDER_C'); break;
846 // Please report bugs on unknown genders
847 debug_report_bug(sprintf("Unknown gender %s detected.", $gender));
851 // Return translated gender
855 // "Translates" the user status
856 function translateUserStatus ($status) {
857 // Generate message depending on status
862 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
867 $ret = getMessage('ACCOUNT_DELETED');
871 // Please report all unknown status
872 debug_report_bug(sprintf("Unknown status %s detected.", $status));
880 // Generates an URL for the dereferer
881 function generateDerefererUrl ($URL) {
882 // Don't de-refer our own links!
883 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
884 // De-refer this link
885 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
892 // Generates an URL for the frametester
893 function generateFrametesterUrl ($URL) {
894 // Prepare frametester URL
895 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
896 encodeString(compileUriCode($URL))
899 // Return the new URL
900 return $frametesterUrl;
903 // Count entries from e.g. a selection box
904 function countSelection ($array) {
906 if (!is_array($array)) {
908 debug_report_bug(__FUNCTION__.': No array provided.');
915 foreach ($array as $key => $selected) {
917 if (!empty($selected)) $ret++;
920 // Return counted selections
924 // Generate XHTML code for the CAPTCHA
925 function generateCaptchaCode ($code, $type, $DATA, $userid) {
926 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
929 // Generates a timestamp (some wrapper for mktime())
930 function makeTime ($hours, $minutes, $seconds, $stamp) {
931 // Extract day, month and year from given timestamp
932 $days = date('d', $stamp);
933 $months = date('m', $stamp);
934 $years = date('Y', $stamp);
936 // Create timestamp for wished time which depends on extracted date
947 // Redirects to an URL and if neccessarry extends it with own base URL
948 function redirectToUrl ($URL, $allowSpider = true) {
950 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
952 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
953 $rel = ' rel="external"';
955 // Do we have internal or external URL?
956 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
957 // Own (=internal) URL
961 // Three different ways to debug...
962 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
963 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
964 //* DEBUG: */ die($URL);
966 // Simple probe for bots/spiders from search engines
967 if ((isSpider()) && ($allowSpider === true)) {
968 // Secure the URL against bad things such als HTML insertions and so on...
969 $URL = secureString($URL);
971 // Set content-type here to fix a missing array element
972 setContentType('text/html');
974 // Output new location link as anchor
975 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
976 } elseif (!headers_sent()) {
977 // Clear own output buffer
978 $GLOBALS['output'] = '';
980 // Load URL when headers are not sent
981 sendHeader('Location: '.str_replace('&', '&', $URL));
983 // Output error message
984 loadInclude('inc/header.php');
985 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
986 loadInclude('inc/footer.php');
989 // Shut the mailer down here
993 // Wrapper for redirectToUrl but URL comes from a configuration entry
994 function redirectToConfiguredUrl ($configEntry) {
996 $URL = getConfig($configEntry);
1001 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1005 redirectToUrl($URL);
1008 // Compiles the given HTML/mail code
1009 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1010 // Is the code a string?
1011 if (!is_string($code)) {
1012 // Silently return it
1017 $startCompile = microtime(true);
1020 $code = compileRawCode($code, $simple, $constants, $full);
1023 $compiled = microtime(true);
1026 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1028 // Return compiled code
1032 // Compiles the code (use compileCode() only for HTML because of the comments)
1033 // @TODO $simple is deprecated
1034 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1035 // Is the code a string?
1036 if (!is_string($code)) {
1037 // Silently return it
1041 // Init replacement-array with smaller set of security characters
1042 $secChars = $GLOBALS['url_chars'];
1044 // Select full set of chars to replace when we e.g. want to compile URLs
1045 if ($full === true) $secChars = $GLOBALS['security_chars'];
1047 // Compile more through a filter
1048 $code = runFilterChain('compile_code', $code);
1050 // Compile constants
1051 if ($constants === true) {
1052 // BEFORE 0.2.1 : Language and data constants
1053 // WITH 0.2.1+ : Only language constants
1054 $code = str_replace('{--', "\" . getMessage('", str_replace('--}', "') . \"", $code));
1056 // BEFORE 0.2.1 : Not used
1057 // WITH 0.2.1+ : Data constants
1058 $code = str_replace('{!', "\" . constant('", str_replace('!}', "') . \"", $code));
1061 // Compile QUOT and other non-HTML codes
1062 foreach ($secChars['to'] as $k => $to) {
1063 // Do the reversed thing as in inc/libs/security_functions.php
1064 $code = str_replace($to, $secChars['from'][$k], $code);
1067 // Find $content[bla][blub] entries
1068 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1069 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1071 // Are some matches found?
1072 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1073 // Replace all matches
1074 $matchesFound = array();
1075 foreach ($matches[0] as $key => $match) {
1076 // Fuzzy look has failed by default
1077 $fuzzyFound = false;
1079 // Fuzzy look on match if already found
1080 foreach ($matchesFound as $found => $set) {
1082 $test = substr($found, 0, strlen($match));
1084 // Does this entry exist?
1085 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
1086 if ($test == $match) {
1088 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
1095 if ($fuzzyFound === true) continue;
1097 // Take all string elements
1098 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1099 // Replace it in the code
1100 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
1101 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1102 $code = str_replace($match, '".' . $newMatch . '."', $code);
1103 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1104 $matchesFound[$match] = 1;
1105 } elseif (!isset($matchesFound[$match])) {
1106 // Not yet replaced!
1107 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
1108 $code = str_replace($match, '".' . $match . '."', $code);
1109 $matchesFound[$match] = 1;
1118 /************************************************************************
1120 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1121 * $a_sort sortiert: *
1123 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1124 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1125 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1126 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1127 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1129 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1130 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1131 * Sie, dass es doch nicht so schwer ist! :-) *
1133 ************************************************************************/
1134 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1136 while ($primary_key < count($a_sort)) {
1137 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1138 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1140 if ($nums === false) {
1141 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1142 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1143 } elseif ($key != $key2) {
1144 // Sort numbers (E.g.: 9 < 10)
1145 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1146 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1150 // We have found two different values, so let's sort whole array
1151 foreach ($dummy as $sort_key => $sort_val) {
1152 $t = $dummy[$sort_key][$key];
1153 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1154 $dummy[$sort_key][$key2] = $t;
1165 // Write back sorted array
1170 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1173 if ($type == 'yn') {
1174 // This is a yes/no selection only!
1175 if ($id > 0) $prefix .= '[' . $id . ']';
1176 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
1178 // Begin with regular selection box here
1179 if (!empty($prefix)) $prefix .= "_";
1181 if ($id > 0) $type2 .= '[' . $id . ']';
1182 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
1187 for ($idx = 1; $idx < 32; $idx++) {
1188 $OUT .= '<option value="' . $idx . '"';
1189 if ($default == $idx) $OUT .= ' selected="selected"';
1190 $OUT .= '>' . $idx . '</option>';
1194 case 'month': // Month
1195 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
1196 $OUT .= '<option value="' . $idx . '"';
1197 if ($default == $idx) $OUT .= ' selected="selected"';
1198 $OUT .= '>' . $descr . '</option>';
1202 case 'year': // Year
1204 $year = date('Y', time());
1206 // Use configured min age or fixed?
1207 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1209 $startYear = $year - getConfig('min_age');
1212 $startYear = $year - 16;
1215 // Calculate earliest year (100 years old people can still enter Internet???)
1216 $minYear = $year - 100;
1218 // Check if the default value is larger than minimum and bigger than actual year
1219 if (($default > $minYear) && ($default >= $year)) {
1220 for ($idx = $year; $idx < ($year + 11); $idx++) {
1221 $OUT .= '<option value="' . $idx . '"';
1222 if ($default == $idx) $OUT .= ' selected="selected"';
1223 $OUT .= '>' . $idx . '</option>';
1225 } elseif ($default == -1) {
1226 // Current year minus 1
1227 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
1228 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
1231 // Get current year and subtract the configured minimum age
1232 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
1233 // Calculate earliest year depending on extension version
1234 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1235 // Use configured minimum age
1236 $year = date('Y', time()) - getConfig('min_age');
1238 // Use fixed 16 years age
1239 $year = date('Y', time()) - 16;
1242 // Construct year selection list
1243 for ($idx = $minYear; $idx <= $year; $idx++) {
1244 $OUT .= '<option value="' . $idx . '"';
1245 if ($default == $idx) $OUT .= ' selected="selected"';
1246 $OUT .= '>' . $idx . '</option>';
1253 for ($idx = 0; $idx < 60; $idx+=5) {
1254 if (strlen($idx) == 1) $idx = '0' . $idx;
1255 $OUT .= '<option value="' . $idx . '"';
1256 if ($default == $idx) $OUT .= ' selected="selected"';
1257 $OUT .= '>' . $idx . '</option>';
1262 for ($idx = 0; $idx < 24; $idx++) {
1263 if (strlen($idx) == 1) $idx = '0' . $idx;
1264 $OUT .= '<option value="' . $idx . '"';
1265 if ($default == $idx) $OUT .= ' selected="selected"';
1266 $OUT .= '>' . $idx . '</option>';
1271 $OUT .= '<option value="Y"';
1272 if ($default == 'Y') $OUT .= ' selected="selected"';
1273 $OUT .= '>{--YES--}</option><option value="N"';
1274 if ($default != 'Y') $OUT .= ' selected="selected"';
1275 $OUT .= '>{--NO--}</option>';
1278 $OUT .= '</select>';
1283 // Deprecated : $length
1286 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1287 // Build server string
1288 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
1291 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1292 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1293 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1294 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1295 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1297 // Build string from misc data
1298 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1300 // Add more additional data
1301 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1303 // Add referal id, language, theme and userid
1304 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1305 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1306 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1307 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1309 // Calculate number for generating the code
1310 $a = $code + getConfig('_ADD') - 1;
1312 if (isConfigEntrySet('master_salt')) {
1313 // Generate hash with master salt from modula of number with the prime number and other data
1314 $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'));
1316 // Create number from hash
1317 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1319 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1320 $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')));
1322 // Create number from hash
1323 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1326 // At least 10 numbers shall be secure enought!
1327 $len = getConfig('code_length');
1328 if ($len == '0') $len = $length;
1329 if ($len == '0') $len = 10;
1331 // Cut off requested counts of number
1332 $return = substr(str_replace('.', '', $rcode), 0, $len);
1334 // Done building code
1338 // Does only allow numbers
1339 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
1340 // Filter all numbers out
1341 $ret = preg_replace('/[^0123456789]/', '', $num);
1344 if ($castValue === true) $ret = (double)$ret;
1346 // Has the whole value changed?
1347 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
1349 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1356 // Insert the code in $img_code into jpeg or PNG image
1357 function generateImageOrCode ($img_code, $headerSent = true) {
1358 // Is the code size oversized or shouldn't we display it?
1359 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1360 // Stop execution of function here because of over-sized code length
1361 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1362 } elseif ($headerSent === false) {
1363 // Return an HTML code here
1364 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
1368 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1371 getConfig('img_type')
1375 if (isFileReadable($img)) {
1376 // Switch image type
1377 switch (getConfig('img_type')) {
1379 // Okay, load image and hide all errors
1380 $image = imagecreatefromjpeg($img);
1384 // Okay, load image and hide all errors
1385 $image = imagecreatefrompng($img);
1389 // Exit function here
1390 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1394 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1395 $text_color = imagecolorallocate($image, 0, 0, 0);
1397 // Insert code into image
1398 imagestring($image, 5, 14, 2, $img_code, $text_color);
1400 // Return to browser
1401 sendHeader('Content-Type: image/' . getConfig('img_type'));
1403 // Output image with matching image factory
1404 switch (getConfig('img_type')) {
1405 case 'jpg': imagejpeg($image); break;
1406 case 'png': imagepng($image); break;
1409 // Remove image from memory
1410 imagedestroy($image);
1412 // Create selection box or array of splitted timestamp
1413 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1414 // Do not continue if ONE_DAY is absend
1415 if (!isConfigEntrySet('ONE_DAY')) {
1416 // And return the timestamp itself or empty array
1417 if ($return_array === true) {
1424 // Calculate 2-seconds timestamp
1425 $stamp = round($timestamp);
1426 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1428 // Do we have a leap year?
1430 $TEST = date('Y', time()) / 4;
1431 $M1 = date('m', time());
1432 $M2 = date('m', (time() + $timestamp));
1434 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1435 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1437 // First of all years...
1438 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1439 //* DEBUG: */ print("Y={$Y}<br />");
1441 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1442 //* DEBUG: */ print("M={$M}<br />");
1444 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1445 //* DEBUG: */ print("W={$W}<br />");
1447 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1448 //* DEBUG: */ print("D={$D}<br />");
1450 $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));
1451 //* DEBUG: */ print("h={$h}<br />");
1453 $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));
1454 //* DEBUG: */ print("m={$m}<br />");
1455 // And at last seconds...
1456 $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));
1457 //* DEBUG: */ print("s={$s}<br />");
1459 // Is seconds zero and time is < 60 seconds?
1460 if (($s == '0') && ($timestamp < 60)) {
1462 $s = round($timestamp);
1466 // Now we convert them in seconds...
1468 if ($return_array) {
1469 // Just put all data in an array for later use
1481 $OUT = '<div align="' . $align . '">';
1482 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1485 if (isInString('Y', $display) || (empty($display))) {
1486 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
1489 if (isInString('M', $display) || (empty($display))) {
1490 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
1493 if (isInString('W', $display) || (empty($display))) {
1494 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
1497 if (isInString('D', $display) || (empty($display))) {
1498 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
1501 if (isInString('h', $display) || (empty($display))) {
1502 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
1505 if (isInString('m', $display) || (empty($display))) {
1506 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
1509 if (isInString('s', $display) || (empty($display))) {
1510 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
1516 if (isInString('Y', $display) || (empty($display))) {
1517 // Generate year selection
1518 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
1519 for ($idx = 0; $idx <= 10; $idx++) {
1520 $OUT .= '<option class="mini_select" value="' . $idx . '"';
1521 if ($idx == $Y) $OUT .= ' selected="selected"';
1522 $OUT .= '>' . $idx . '</option>';
1524 $OUT .= '</select></td>';
1526 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1529 if (isInString('M', $display) || (empty($display))) {
1530 // Generate month selection
1531 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
1532 for ($idx = 0; $idx <= 11; $idx++) {
1533 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1534 if ($idx == $M) $OUT .= ' selected="selected"';
1535 $OUT .= '>' . $idx . '</option>';
1537 $OUT .= '</select></td>';
1539 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1542 if (isInString('W', $display) || (empty($display))) {
1543 // Generate week selection
1544 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
1545 for ($idx = 0; $idx <= 4; $idx++) {
1546 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1547 if ($idx == $W) $OUT .= ' selected="selected"';
1548 $OUT .= '>' . $idx . '</option>';
1550 $OUT .= '</select></td>';
1552 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1555 if (isInString('D', $display) || (empty($display))) {
1556 // Generate day selection
1557 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
1558 for ($idx = 0; $idx <= 31; $idx++) {
1559 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1560 if ($idx == $D) $OUT .= ' selected="selected"';
1561 $OUT .= '>' . $idx . '</option>';
1563 $OUT .= '</select></td>';
1565 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1568 if (isInString('h', $display) || (empty($display))) {
1569 // Generate hour selection
1570 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1571 for ($idx = 0; $idx <= 23; $idx++) {
1572 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1573 if ($idx == $h) $OUT .= ' selected="selected"';
1574 $OUT .= '>' . $idx . '</option>';
1576 $OUT .= '</select></td>';
1578 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1581 if (isInString('m', $display) || (empty($display))) {
1582 // Generate minute selection
1583 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1584 for ($idx = 0; $idx <= 59; $idx++) {
1585 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1586 if ($idx == $m) $OUT .= ' selected="selected"';
1587 $OUT .= '>' . $idx . '</option>';
1589 $OUT .= '</select></td>';
1591 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1594 if (isInString('s', $display) || (empty($display))) {
1595 // Generate second selection
1596 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1597 for ($idx = 0; $idx <= 59; $idx++) {
1598 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1599 if ($idx == $s) $OUT .= ' selected="selected"';
1600 $OUT .= '>' . $idx . '</option>';
1602 $OUT .= '</select></td>';
1604 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1611 // Return generated HTML code
1616 function createTimestampFromSelections ($prefix, $postData) {
1617 // Initial return value
1620 // Do we have a leap year?
1622 $TEST = date('Y', time()) / 4;
1623 $M1 = date('m', time());
1625 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1626 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
1628 // First add years...
1629 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1632 $ret += $postData[$prefix . '_mo'] * 2628000;
1635 $ret += $postData[$prefix . '_we'] * 604800;
1638 $ret += $postData[$prefix . '_da'] * 86400;
1641 $ret += $postData[$prefix . '_ho'] * 3600;
1644 $ret += $postData[$prefix . '_mi'] * 60;
1646 // And at last seconds...
1647 $ret += $postData[$prefix . '_se'];
1649 // Return calculated value
1653 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1654 function createFancyTime ($stamp) {
1655 // Get data array with years/months/weeks/days/...
1656 $data = createTimeSelections($stamp, '', '', '', true);
1658 foreach($data as $k => $v) {
1660 // Value is greater than 0 "eval" data to return string
1661 eval('$ret .= ", ".$v." {--_' . strtoupper($k) . '--}";');
1666 // Do we have something there?
1667 if (strlen($ret) > 0) {
1668 // Remove leading commata and space
1669 $ret = substr($ret, 2);
1672 $ret = '0 {--_SECONDS--}';
1675 // Return fancy time string
1679 // Generates a navigation row for listing emails
1680 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1682 if ($show_form === false) {
1687 for ($page = 1; $page <= $PAGES; $page++) {
1688 // Is the page currently selected or shall we generate a link to it?
1689 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1690 // Is currently selected, so only highlight it
1691 $NAV .= '<strong>-';
1693 // Open anchor tag and add base URL
1694 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1696 // Add userid when we shall show all mails from a single member
1697 if ((isGetRequestParameterSet('userid')) && (bigintval(getRequestParameter('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestParameter('userid'));
1699 // Close open anchor tag
1703 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1704 // Is currently selected, so only highlight it
1705 $NAV .= '-</strong>';
1711 // Add seperator if we have not yet reached total pages
1712 if ($page < $PAGES) {
1718 // Define constants only once
1719 $content['nav'] = $NAV;
1720 $content['span'] = $colspan;
1721 $content['top'] = $TOP;
1723 // Load navigation template
1724 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1726 if ($return === true) {
1727 // Return generated HTML-Code
1735 // Extract host from script name
1736 function extractHostnameFromUrl (&$script) {
1737 // Use default SERVER_URL by default... ;) So?
1738 $url = getConfig('SERVER_URL');
1740 // Is this URL valid?
1741 if (substr($script, 0, 7) == 'http://') {
1742 // Use the hostname from script URL as new hostname
1743 $url = substr($script, 7);
1744 $extract = explode('/', $url);
1746 // Done extracting the URL :)
1749 // Extract host name
1750 $host = str_replace('http://', '', $url);
1751 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1753 // Generate relative URL
1754 //* DEBUG: */ print('SCRIPT=' . $script.'<br />');
1755 if (substr(strtolower($script), 0, 7) == 'http://') {
1756 // But only if http:// is in front!
1757 $script = substr($script, (strlen($url) + 7));
1758 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1760 $script = substr($script, (strlen($url) + 8));
1763 //* DEBUG: */ print('SCRIPT=' . $script.'<br />');
1764 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1770 // Send a GET request
1771 function sendGetRequest ($script, $data = array()) {
1772 // Extract host name from script
1773 $host = extractHostnameFromUrl($script);
1776 $body = http_build_query($data, '', '&');
1778 // Do we have a question-mark in the script?
1779 if (strpos($script, '?') === false) {
1780 // No, so first char must be question mark
1781 $body = '?' . $body;
1784 $body = '&' . $body;
1790 // Remove trailed & to make it more conform
1791 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
1793 // Generate GET request header
1794 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1795 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1796 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1797 if (isConfigEntrySet('FULL_VERSION')) {
1798 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1800 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1802 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
1803 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1804 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
1805 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1806 $request .= getConfig('HTTP_EOL');
1808 // Send the raw request
1809 $response = sendRawRequest($host, $request);
1811 // Return the result to the caller function
1815 // Send a POST request
1816 function sendPostRequest ($script, $postData) {
1817 // Is postData an array?
1818 if (!is_array($postData)) {
1820 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1821 return array('', '', '');
1824 // Extract host name from script
1825 $host = extractHostnameFromUrl($script);
1827 // Construct request body
1828 $body = http_build_query($postData, '', '&');
1830 // Generate POST request header
1831 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
1832 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1833 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1834 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1835 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1836 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1837 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1838 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1839 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
1840 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1841 $request .= getConfig('HTTP_EOL');
1846 // Send the raw request
1847 $response = sendRawRequest($host, $request);
1849 // Return the result to the caller function
1853 // Sends a raw request to another host
1854 function sendRawRequest ($host, $request) {
1855 // Init errno and errdesc with 'all fine' values
1856 $errno = '0'; $errdesc = '';
1859 $response = array('', '', '');
1861 // Default is not to use proxy
1864 // Are proxy settins set?
1865 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1871 loadIncludeOnce('inc/classes/resolver.class.php');
1873 // Get resolver instance
1874 $resolver = new HostnameResolver();
1877 //* DEBUG: */ die('SCRIPT=' . $script.'<br />');
1878 if ($useProxy === true) {
1879 // Resolve hostname into IP address
1880 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
1882 // Connect to host through proxy connection
1883 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1885 // Resolve hostname into IP address
1886 $ip = $resolver->resolveHostname($host);
1888 // Connect to host directly
1889 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
1893 if (!is_resource($fp)) {
1895 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
1897 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
1898 // Cannot set non-blocking mode or timeout
1899 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
1904 if ($useProxy === true) {
1905 // Setup proxy tunnel
1906 $response = setupProxyTunnel($host, $fp);
1908 // If the response is invalid, abort
1909 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
1910 // Invalid response!
1911 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
1917 fwrite($fp, $request);
1920 $start = microtime(true);
1923 while (!feof($fp)) {
1924 // Get info from stream
1925 $info = stream_get_meta_data($fp);
1927 // Is it timed out? 15 seconds is a really patient...
1928 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1930 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1936 // Get line from stream
1937 $line = fgets($fp, 128);
1939 // Ignore empty lines because of non-blocking mode
1941 // uslepp a little to avoid 100% CPU load
1948 // Add it to response
1949 $response[] = trim($line);
1955 // Time request if debug-mode is enabled
1956 if (isDebugModeEnabled()) {
1957 // Add debug message...
1958 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1961 // Skip first empty lines
1963 foreach ($resp as $idx => $line) {
1965 $line = trim($line);
1967 // Is this line empty?
1970 array_shift($response);
1972 // Abort on first non-empty line
1977 //* DEBUG: */ print('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1978 //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1980 // Proxy agent found or something went wrong?
1981 if (!isset($response[0])) {
1982 // No response, maybe timeout
1983 $response = array('', '', '');
1984 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1985 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1986 // Proxy header detected, so remove two lines
1987 array_shift($response);
1988 array_shift($response);
1991 // Was the request successfull?
1992 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1993 // Not found / access forbidden
1994 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1995 $response = array('', '', '');
2002 // Sets up a proxy tunnel for given hostname and through resource
2003 function setupProxyTunnel ($host, $resource) {
2005 $response = array('', '', '');
2007 // Generate CONNECT request header
2008 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
2009 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
2011 // Use login data to proxy? (username at least!)
2012 if (getConfig('proxy_username') != '') {
2014 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
2015 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
2018 // Add last new-line
2019 $proxyTunnel .= getConfig('HTTP_EOL');
2020 //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
2023 fwrite($fp, $proxyTunnel);
2027 // No response received
2031 // Read the first line
2032 $resp = trim(fgets($fp, 10240));
2033 $respArray = explode(' ', $resp);
2034 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
2035 // Invalid response!
2043 // Taken from www.php.net isInStringIgnoreCase() user comments
2044 function isEmailValid ($email) {
2045 // Check first part of email address
2046 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
2049 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
2052 $regex = '@^' . $first . '\@' . $domain . '$@iU';
2054 // Return check result
2055 return preg_match($regex, $email);
2058 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2059 function isUrlValid ($URL, $compile=true) {
2060 // Trim URL a little
2061 $URL = trim(urldecode($URL));
2062 //* DEBUG: */ outputHtml($URL.'<br />');
2064 // Compile some chars out...
2065 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
2066 //* DEBUG: */ outputHtml($URL.'<br />');
2068 // Check for the extension filter
2069 if (isExtensionActive('filter')) {
2070 // Use the extension's filter set
2071 return FILTER_VALIDATE_URL($URL, false);
2074 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2075 // https:// in front of the URLs
2076 return isUrlValidSimple($URL);
2079 // Generate a list of administrative links to a given userid
2080 function generateMemberAdminActionLinks ($userid, $status = '') {
2081 // Make sure userid is a number
2082 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
2084 // Define all main targets
2085 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2087 // Begin of navigation links
2090 foreach ($targetArray as $tar) {
2091 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
2092 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
2093 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2094 // Locked accounts shall be unlocked
2095 $OUT .= 'UNLOCK_USER';
2097 // All other status is fine
2098 $OUT .= strtoupper($tar);
2100 $OUT .= '_TITLE--}">{--ADMIN_';
2101 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2102 // Locked accounts shall be unlocked
2103 $OUT .= 'UNLOCK_USER';
2105 // All other status is fine
2106 $OUT .= strtoupper($tar);
2108 $OUT .= '--}</a></span>|';
2111 // Finish navigation link
2112 $OUT = substr($OUT, 0, -7) . ']';
2118 // Generate an email link
2119 function generateEmailLink ($email, $table = 'admins') {
2120 // Default email link (INSECURE! Spammer can read this by harvester programs)
2121 $EMAIL = 'mailto:' . $email;
2123 // Check for several extensions
2124 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2125 // Create email link for contacting admin in guest area
2126 $EMAIL = generateAdminEmailLink($email);
2127 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
2128 // Create email link for contacting a member within admin area (or later in other areas, too?)
2129 $EMAIL = generateUserEmailLink($email, 'admin');
2130 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2131 // Create email link to contact sponsor within admin area (or like the link above?)
2132 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2135 // Shall I close the link when there is no admin?
2136 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2138 // Return email link
2142 // Generate a hash for extra-security for all passwords
2143 function generateHash ($plainText, $salt = '', $hash = true) {
2145 //* DEBUG: */ outputHtml('plainText=' . $plainText . ',salt=' . $salt . ',hash='.intval($hash).'<br />');
2147 // Is the required extension 'sql_patches' there and a salt is not given?
2148 // 0123 4 43 3 4 432 2 3 32 2 3 3210
2149 if ((((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')))) {
2150 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2151 if ($hash === true) {
2152 // Is plain password
2153 return md5($plainText);
2155 // Is already a hash
2160 // Do we miss an arry element here?
2161 if (!isConfigEntrySet('file_hash')) {
2163 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2166 // When the salt is empty build a new one, else use the first x configured characters as the salt
2168 // Build server string for more entropy
2169 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2172 $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');
2175 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2177 // Calculate number for generating the code
2178 $a = time() + getConfig('_ADD') - 1;
2180 // Generate SHA1 sum from modula of number and the prime number
2181 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2182 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2183 $sha1 = scrambleString($sha1);
2184 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2185 //* DEBUG: */ $sha1b = descrambleString($sha1);
2186 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2188 // Generate the password salt string
2189 $salt = substr($sha1, 0, getConfig('salt_length'));
2190 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2193 //* DEBUG: */ outputHtml('salt=' . $salt . '<br />');
2194 $salt = substr($salt, 0, getConfig('salt_length'));
2195 //* DEBUG: */ outputHtml('salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />');
2197 // Sanity check on salt
2198 if (strlen($salt) != getConfig('salt_length')) {
2200 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2204 // Generate final hash (for debug output)
2205 $finalHash = $salt . sha1($salt . $plainText);
2208 //* DEBUG: */ outputHtml('finalHash=' . $finalHash);
2214 // Scramble a string
2215 function scrambleString($str) {
2219 // Final check, in case of failture it will return unscrambled string
2220 if (strlen($str) > 40) {
2221 // The string is to long
2223 } elseif (strlen($str) == 40) {
2225 $scrambleNums = explode(':', getConfig('pass_scramble'));
2227 // Generate new numbers
2228 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2231 // Compare both lengths and abort if different
2232 if (strlen($str) != count($scrambleNums)) return $str;
2234 // Scramble string here
2235 //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2236 for ($idx = 0; $idx < strlen($str); $idx++) {
2237 // Get char on scrambled position
2238 $char = substr($str, $scrambleNums[$idx], 1);
2240 // Add it to final output string
2241 $scrambled .= $char;
2244 // Return scrambled string
2245 //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2249 // De-scramble a string scrambled by scrambleString()
2250 function descrambleString($str) {
2251 // Scramble only 40 chars long strings
2252 if (strlen($str) != 40) return $str;
2254 // Load numbers from config
2255 $scrambleNums = explode(':', getConfig('pass_scramble'));
2258 if (count($scrambleNums) != 40) return $str;
2260 // Begin descrambling
2261 $orig = str_repeat(' ', 40);
2262 //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2263 for ($idx = 0; $idx < 40; $idx++) {
2264 $char = substr($str, $idx, 1);
2265 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2268 // Return scrambled string
2269 //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2273 // Generated a "string" for scrambling
2274 function genScrambleString ($len) {
2275 // Prepare array for the numbers
2276 $scrambleNumbers = array();
2278 // First we need to setup randomized numbers from 0 to 31
2279 for ($idx = 0; $idx < $len; $idx++) {
2281 $rand = mt_rand(0, ($len -1));
2283 // Check for it by creating more numbers
2284 while (array_key_exists($rand, $scrambleNumbers)) {
2285 $rand = mt_rand(0, ($len -1));
2289 $scrambleNumbers[$rand] = $rand;
2292 // So let's create the string for storing it in database
2293 $scrambleString = implode(':', $scrambleNumbers);
2294 return $scrambleString;
2297 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2298 function encodeHashForCookie ($passHash) {
2299 // Return vanilla password hash
2302 // Is a secret key and master salt already initialized?
2303 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
2304 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2305 // Only calculate when the secret key is generated
2306 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getConfig('secret_key')));
2307 if ((strlen($passHash) != 49) || (strlen(getConfig('secret_key')) != 40)) {
2308 // Both keys must have same length so return unencrypted
2309 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getConfig('secret_key')) . '!=40');
2313 $newHash = ''; $start = 9;
2314 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
2315 for ($idx = 0; $idx < 20; $idx++) {
2316 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getConfig('secret_key'))), 2));
2317 $part2 = hexdec(substr(getConfig('secret_key'), $start, 2));
2318 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
2319 $mod = dechex($idx);
2320 if ($part1 > $part2) {
2321 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2322 } elseif ($part2 > $part1) {
2323 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2325 $mod = substr($mod, 0, 2);
2326 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
2327 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
2328 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
2333 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
2334 $ret = generateHash($newHash, getConfig('master_salt'));
2338 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
2342 // Fix "deleted" cookies
2343 function fixDeletedCookies ($cookies) {
2344 // Is this an array with entries?
2345 if ((is_array($cookies)) && (count($cookies) > 0)) {
2346 // Then check all cookies if they are marked as deleted!
2347 foreach ($cookies as $cookieName) {
2348 // Is the cookie set to "deleted"?
2349 if (getSession($cookieName) == 'deleted') {
2350 setSession($cookieName, '');
2356 // Output error messages in a fasioned way and die...
2357 function app_die ($F, $L, $message) {
2358 // Check if Script is already dieing and not let it kill itself another 1000 times
2359 if (!isset($GLOBALS['app_died'])) {
2360 // Make sure, that the script realy realy diese here and now
2361 $GLOBALS['app_died'] = true;
2363 // Set content type as text/html
2364 setContentType('text/html');
2367 loadIncludeOnce('inc/header.php');
2369 // Rewrite message for output
2370 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2372 // Better log this message away
2373 if ($F != 'debug_report_bug') logDebugMessage($F, $L, $message);
2375 // Load the message template
2376 loadTemplate('app_die_message', false, $message);
2379 loadIncludeOnce('inc/footer.php');
2381 // Script tried to kill itself twice
2382 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2386 // Display parsing time and number of SQL queries in footer
2387 function displayParsingTime() {
2388 // Is the timer started?
2389 if (!isset($GLOBALS['startTime'])) {
2395 $endTime = microtime(true);
2397 // "Explode" both times
2398 $start = explode(' ', $GLOBALS['startTime']);
2399 $end = explode(' ', $endTime);
2400 $runTime = $end[0] - $start[0];
2401 if ($runTime < 0) $runTime = '0';
2404 // @TODO This can be easily moved out after the merge from EL branch to this is complete
2406 'run_time' => translateComma($runTime),
2407 'sql_time' => translateComma(getConfig('sql_time') * 1000),
2410 // Load the template
2411 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
2414 // Check wether a boolean constant is set
2415 // Taken from user comments in PHP documentation for function constant()
2416 function isBooleanConstantAndTrue ($constName) { // : Boolean
2417 // Failed by default
2421 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2423 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-CACHE!<br />");
2424 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2427 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-RESOLVE!<br />");
2428 if (defined($constName)) {
2430 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-FOUND!<br />");
2431 $res = (constant($constName) === true);
2435 $GLOBALS['cache_array']['const'][$constName] = $res;
2437 //* DEBUG: */ var_dump($res);
2443 // Checks if a given apache module is loaded
2444 function isApacheModuleLoaded ($apacheModule) {
2445 // Check it and return result
2446 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2449 // Get current theme name
2450 function getCurrentTheme () {
2451 // The default theme is 'default'... ;-)
2454 // Do we have ext-theme installed and active?
2455 if (isExtensionActive('theme')) {
2456 // Call inner method
2457 $ret = getActualTheme();
2460 // Return theme value
2464 // Generates an error code from given account status
2465 function generateErrorCodeFromUserStatus ($status='') {
2466 // If no status is provided, use the default, cached
2467 if ((empty($status)) && (isMember())) {
2469 $status = getUserData('status');
2472 // Default error code if unknown account status
2473 $errorCode = getCode('UNKNOWN_STATUS');
2475 // Generate constant name
2476 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2478 // Is the constant there?
2479 if (isCodeSet($codeName)) {
2481 $errorCode = getCode($codeName);
2484 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2487 // Return error code
2491 // Back-ported from the new ship-simu engine. :-)
2492 function debug_get_printable_backtrace () {
2494 $backtrace = "<ol>\n";
2496 // Get and prepare backtrace for output
2497 $backtraceArray = debug_backtrace();
2498 foreach ($backtraceArray as $key => $trace) {
2499 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2500 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2501 if (!isset($trace['args'])) $trace['args'] = array();
2502 $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";
2506 $backtrace .= "</ol>\n";
2508 // Return the backtrace
2512 // A mail-able backtrace
2513 function debug_get_mailable_backtrace () {
2517 // Get and prepare backtrace for output
2518 $backtraceArray = debug_backtrace();
2519 foreach ($backtraceArray as $key => $trace) {
2520 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2521 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2522 if (!isset($trace['args'])) $trace['args'] = array();
2523 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2526 // Return the backtrace
2530 // Output a debug backtrace to the user
2531 function debug_report_bug ($message = '', $sendEmail = true) {
2532 // Is this already called?
2533 if (isset($GLOBALS[__FUNCTION__])) {
2535 print 'Message:'.$message.'<br />Backtrace:<pre>';
2536 debug_print_backtrace();
2540 // Set this function as called
2541 $GLOBALS[__FUNCTION__] = true;
2546 // Is the optional message set?
2547 if (!empty($message)) {
2549 $debug = sprintf("Note: %s<br />\n",
2553 // @TODO Add a little more infos here
2554 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2558 $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>";
2559 $debug .= debug_get_printable_backtrace();
2560 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2561 $debug .= "Thank you for finding bugs.";
2563 // Send an email? (e.g. not wanted for evaluation errors)
2564 if (($sendEmail === true) && (!isInstallationPhase())) {
2567 'message' => trim($message),
2568 'backtrace' => trim(debug_get_mailable_backtrace())
2571 // Send email to webmaster
2572 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2576 app_die(__FUNCTION__, __LINE__, $debug);
2579 // Generates a ***weak*** seed
2580 function generateSeed () {
2581 return microtime(true) * 100000;
2584 // Converts a message code to a human-readable message
2585 function getMessageFromErrorCode ($code) {
2589 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2590 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2591 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2592 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2593 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2594 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2595 case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2596 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2597 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2598 case getCode('ACCOUNT_LOCKED') : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2599 case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2600 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2601 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2602 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2603 case getCode('MODULE_MEM_ONLY') : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestParameter('mod')); break;
2604 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2605 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2606 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2607 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestParameter('blist'), 0); break;
2608 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2609 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2610 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2611 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2612 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2613 case getCode('MORE_RECEIVERS3') : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
2614 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2615 case getCode('NO_MAIL_TYPE') : $message = getMessage('MEMBER_NO_MAIL_TYPE_SELECTED'); break;
2616 case getCode('UNKNOWN_ERROR') : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
2617 case getCode('UNKNOWN_STATUS') : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
2619 case getCode('ERROR_MAILID'):
2620 if (isExtensionActive('mailid', true)) {
2621 $message = getMessage('ERROR_CONFIRMING_MAIL');
2623 $message = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'mailid');
2627 case getCode('EXTENSION_PROBLEM'):
2628 if (isGetRequestParameterSet('ext')) {
2629 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
2631 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2635 case getCode('URL_TLOCK'):
2636 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2637 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2638 array(bigintval(getRequestParameter('id'))), __FILE__, __LINE__);
2640 // Load timestamp from last order
2641 list($timestamp) = SQL_FETCHROW($result);
2644 SQL_FREERESULT($result);
2646 // Translate it for templates
2647 $timestamp = generateDateTime($timestamp, 1);
2649 // Calculate hours...
2650 $STD = round(getConfig('url_tlock') / 60 / 60);
2653 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2656 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2658 // Finally contruct the message
2659 // @TODO Rewrite this old lost code to a template
2660 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2661 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2662 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2666 // Missing/invalid code
2667 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2670 logDebugMessage(__FUNCTION__, __LINE__, $message);
2674 // Return the message
2678 // Compile characters which are allowed in URLs
2679 function compileUriCode ($code, $simple = true) {
2680 // Compile constants
2681 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2683 // Compile QUOT and other non-HTML codes
2684 $code = str_replace('{DOT}', '.',
2685 str_replace('{SLASH}', '/',
2686 str_replace('{QUOT}', "'",
2687 str_replace('{DOLLAR}', '$',
2688 str_replace('{OPEN_ANCHOR}', '(',
2689 str_replace('{CLOSE_ANCHOR}', ')',
2690 str_replace('{OPEN_SQR}', '[',
2691 str_replace('{CLOSE_SQR}', ']',
2692 str_replace('{PER}', '%',
2696 // Return compiled code
2700 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2701 function isUrlValidSimple ($url) {
2703 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2705 // Allows http and https
2706 $http = "(http|https)+(:\/\/)";
2708 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2709 // Test double-domains (e.g. .de.vu)
2710 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2712 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2714 $dir = "((/)+([-_\.[:alnum:]])+)*";
2716 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2717 // ... and the string after and including question character
2718 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2719 // Pattern for URLs like http://url/dir/doc.html?var=value
2720 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2721 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2722 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2723 // Pattern for URLs like http://url/dir/?var=value
2724 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2725 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2726 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2727 // Pattern for URLs like http://url/dir/page.ext
2728 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2729 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2730 $pattern['ipdp'] = $http . $ip . $dir . $page;
2731 // Pattern for URLs like http://url/dir
2732 $pattern['d1d'] = $http . $domain1 . $dir;
2733 $pattern['d2d'] = $http . $domain2 . $dir;
2734 $pattern['ipd'] = $http . $ip . $dir;
2735 // Pattern for URLs like http://url/?var=value
2736 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2737 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2738 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2739 // Pattern for URLs like http://url?var=value
2740 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2741 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2742 $pattern['ipg12'] = $http . $ip . $getstring1;
2744 // Test all patterns
2746 foreach ($pattern as $key => $pat) {
2748 if (isDebugRegularExpressionEnabled()) {
2749 // @TODO Are these convertions still required?
2750 $pat = str_replace('.', "\.", $pat);
2751 $pat = str_replace('@', "\@", $pat);
2752 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2755 // Check if expression matches
2756 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
2759 if ($reg === true) break;
2762 // Return true/false
2766 // Wtites data to a config.php-style file
2767 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2768 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2769 // Initialize some variables
2775 // Is the file there and read-/write-able?
2776 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2777 $search = 'CFG: ' . $comment;
2778 $tmp = $FQFN . '.tmp';
2780 // Open the source file
2781 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2783 // Is the resource valid?
2784 if (is_resource($fp)) {
2785 // Open temporary file
2786 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2788 // Is the resource again valid?
2789 if (is_resource($fp_tmp)) {
2790 // Mark temporary file as readable
2791 $GLOBALS['file_readable'][$tmp] = true;
2794 while (!feof($fp)) {
2795 // Read from source file
2796 $line = fgets ($fp, 1024);
2798 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2801 if ($next === $seek) {
2803 $line = $prefix . $DATA . $suffix . "\n";
2809 // Write to temp file
2810 fwrite($fp_tmp, $line);
2816 // Finished writing tmp file
2820 // Close source file
2823 if (($done === true) && ($found === true)) {
2824 // Copy back tmp file and delete tmp :-)
2825 copyFileVerified($tmp, $FQFN, 0644);
2826 return removeFile($tmp);
2827 } elseif ($found === false) {
2828 outputHtml('<strong>CHANGE:</strong> 404!');
2830 outputHtml('<strong>TMP:</strong> UNDONE!');
2834 // File not found, not readable or writeable
2835 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2838 // An error was detected!
2841 // Send notification to admin
2842 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2843 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2845 sendAdminsEmails($subject, $templateName, $content, $userid);
2847 // Send out out-dated way
2848 $message = loadEmailTemplate($templateName, $content, $userid);
2849 sendAdminEmails($subject, $message);
2853 // Debug message logger
2854 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2855 // Is debug mode enabled?
2856 if ((isDebugModeEnabled()) || ($force === true)) {
2858 $message = str_replace("\r", '', str_replace("\n", '', $message));
2860 // Log this message away, we better don't call app_die() here to prevent an endless loop
2861 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2862 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2867 // Handle extra values
2868 function handleExtraValues ($filterFunction, $value, $extraValue) {
2869 // Default is the value itself
2872 // Do we have a special filter function?
2873 if (!empty($filterFunction)) {
2874 // Does the filter function exist?
2875 if (function_exists($filterFunction)) {
2876 // Do we have extra parameters here?
2877 if (!empty($extraValue)) {
2878 // Put both parameters in one new array by default
2879 $args = array($value, $extraValue);
2881 // If we have an array simply use it and pre-extend it with our value
2882 if (is_array($extraValue)) {
2883 // Make the new args array
2884 $args = merge_array(array($value), $extraValue);
2887 // Call the multi-parameter call-back
2888 $ret = call_user_func_array($filterFunction, $args);
2890 // One parameter call
2891 $ret = call_user_func($filterFunction, $value);
2900 // Converts timestamp selections into a timestamp
2901 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2902 // Init test variable
2906 // Get last three chars
2907 $test = substr($id, -3);
2909 // Improved way of checking! :-)
2910 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2911 // Found a multi-selection for timings?
2912 $test = substr($id, 0, -3);
2913 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)) {
2914 // Generate timestamp
2915 $postData[$test] = createTimestampFromSelections($test, $postData);
2916 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2917 $GLOBALS['skip_config'][$test] = true;
2919 // Remove data from array
2920 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2921 unset($postData[$test . '_' . $rem]);
2932 // Reverts the german decimal comma into Computer decimal dot
2933 function convertCommaToDot ($str) {
2934 // Default float is not a float... ;-)
2937 // Which language is selected?
2938 switch (getLanguage()) {
2939 case 'de': // German language
2940 // Remove german thousand dots first
2941 $str = str_replace('.', '', $str);
2943 // Replace german commata with decimal dot and cast it
2944 $float = (float)str_replace(',', '.', $str);
2947 default: // US and so on
2948 // Remove thousand dots first and cast
2949 $float = (float)str_replace(',', '', $str);
2957 // Handle menu-depending failed logins and return the rendered content
2958 function handleLoginFailures ($accessLevel) {
2959 // Default output is empty ;-)
2962 // Is the session data set?
2963 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
2964 // Ignore zero values
2965 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
2966 // Non-guest has login failures found, get both data and prepare it for template
2967 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "accessLevel={$accessLevel}<br />");
2969 'login_failures' => getSession('mailer_' . $accessLevel . '_failures'),
2970 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
2974 $OUT = loadTemplate('login_failures', true, $content);
2977 // Reset session data
2978 setSession('mailer_' . $accessLevel . '_failures', '');
2979 setSession('mailer_' . $accessLevel . '_last_failure', '');
2982 // Return rendered content
2987 function rebuildCache ($cache, $inc = '', $force = false) {
2989 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
2991 // Shall I remove the cache file?
2992 if (isCacheInstanceValid()) {
2994 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2996 $GLOBALS['cache_instance']->removeCacheFile($force);
2999 // Include file given?
3002 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3004 // Is the include there?
3005 if (isIncludeReadable($inc)) {
3006 // And rebuild it from scratch
3007 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
3010 // Include not found!
3011 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3017 // Determines the real remote address
3018 function determineRealRemoteAddress () {
3019 // Is a proxy in use?
3020 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3022 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3023 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3024 // Yet, another proxy
3025 $address = $_SERVER['HTTP_CLIENT_IP'];
3027 // The regular address when no proxy was used
3028 $address = $_SERVER['REMOTE_ADDR'];
3031 // This strips out the real address from proxy output
3032 if (strstr($address, ',')) {
3033 $addressArray = explode(',', $address);
3034 $address = $addressArray[0];
3037 // Return the result
3041 // Adds a bonus mail to the queue
3042 // This is a high-level function!
3043 function addNewBonusMail ($data, $mode = '', $output=true) {
3044 // Use mode from data if not set and availble ;-)
3045 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3047 // Generate receiver list
3048 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3051 if (!empty($receiver)) {
3052 // Add bonus mail to queue
3053 addBonusMailToQueue(
3065 // Mail inserted into bonus pool
3066 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3067 } elseif ($output) {
3068 // More entered than can be reached!
3069 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3072 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3076 // Determines referal id and sets it
3077 function determineReferalId () {
3078 // Skip this in non-html-mode and outside ref.php
3079 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3081 // Check if refid is set
3082 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3084 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3085 // The variable user comes from the click-counter script click.php and we only accept this here
3086 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
3087 } elseif (isPostRequestParameterSet('refid')) {
3088 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3089 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
3090 } elseif (isGetRequestParameterSet('refid')) {
3091 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3092 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
3093 } elseif (isGetRequestParameterSet('ref')) {
3094 // Set refid=ref (the referal link uses such variable)
3095 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
3096 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3097 // Set session refid als global
3098 $GLOBALS['refid'] = bigintval(getSession('refid'));
3099 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3100 // Select a random user which has confirmed enougth mails
3101 $GLOBALS['refid'] = determineRandomReferalId();
3102 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (getConfig('def_refid') > 0)) {
3103 // Set default refid as refid in URL
3104 $GLOBALS['refid'] = getConfig('def_refid');
3106 // No default id when sql_patches is not installed or none set
3107 $GLOBALS['refid'] = '0';
3110 // Set cookie when default refid > 0
3111 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3112 // Default is not found
3115 // Do we have nickname or userid set?
3116 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3117 // Nickname in URL, so load the id
3118 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3119 } elseif ($GLOBALS['refid'] > 0) {
3120 // Direct userid entered
3121 $found = fetchUserData($GLOBALS['refid']);
3124 // Is the record valid?
3125 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3126 // No, then reset referal id
3127 $GLOBALS['refid'] = getConfig('def_refid');
3131 setSession('refid', $GLOBALS['refid']);
3134 // Return determined refid
3135 return $GLOBALS['refid'];
3138 // Enables the reset mode and runs it
3139 function doReset () {
3140 // Enable the reset mode
3141 $GLOBALS['reset_enabled'] = true;
3144 runFilterChain('reset');
3147 // Our shutdown-function
3148 function shutdown () {
3149 // Call the filter chain 'shutdown'
3150 runFilterChain('shutdown', null);
3152 // Check if not in installation phase and the link is up
3153 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
3155 SQL_CLOSE(__FILE__, __LINE__);
3156 } elseif (!isInstallationPhase()) {
3158 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3161 // Stop executing here
3166 function initMemberId () {
3167 $GLOBALS['member_id'] = '0';
3170 // Setter for member id
3171 function setMemberId ($memberid) {
3172 // We should not set member id to zero
3173 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3176 $GLOBALS['member_id'] = bigintval($memberid);
3179 // Getter for member id or returns zero
3180 function getMemberId () {
3181 // Default member id
3184 // Is the member id set?
3185 if (isMemberIdSet()) {
3187 $memberid = $GLOBALS['member_id'];
3194 // Checks ether the member id is set
3195 function isMemberIdSet () {
3196 return (isset($GLOBALS['member_id']));
3199 // Handle message codes from URL
3200 function handleCodeMessage () {
3201 if (isGetRequestParameterSet('code')) {
3202 // Default extension is 'unknown'
3205 // Is extension given?
3206 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
3208 // Convert the 'code' parameter from URL to a human-readable message
3209 $message = getMessageFromErrorCode(getRequestParameter('code'));
3211 // Load message template
3212 loadTemplate('message', false, $message);
3216 // Setter for extra title
3217 function setExtraTitle ($extraTitle) {
3218 $GLOBALS['extra_title'] = $extraTitle;
3221 // Getter for extra title
3222 function getExtraTitle () {
3223 // Is the extra title set?
3224 if (!isExtraTitleSet()) {
3225 // No, then abort here
3226 debug_report_bug('extra_title is not set!');
3230 return $GLOBALS['extra_title'];
3233 // Checks if the extra title is set
3234 function isExtraTitleSet () {
3235 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3238 // Generates a 'extension foo inactive' message
3239 function generateExtensionInactiveMessage ($ext_name) {
3240 // Is the extension empty?
3241 if (empty($ext_name)) {
3242 // This should not happen
3243 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3247 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3249 // Is an admin logged in?
3251 // Then output admin message
3252 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3255 // Return prepared message
3259 // Generates a 'extension foo not installed' message
3260 function generateExtensionNotInstalledMessage ($ext_name) {
3261 // Is the extension empty?
3262 if (empty($ext_name)) {
3263 // This should not happen
3264 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3268 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3270 // Is an admin logged in?
3272 // Then output admin message
3273 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3276 // Return prepared message
3280 // Generates a message depending on if the extension is not installed or not
3282 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3286 // Is the extension not installed or just deactivated?
3287 switch (isExtensionInstalled($ext_name)) {
3288 case true; // Deactivated!
3289 $message = generateExtensionInactiveMessage($ext_name);
3292 case false; // Not installed!
3293 $message = generateExtensionNotInstalledMessage($ext_name);
3296 default: // Should not happen!
3297 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3298 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3302 // Return the message
3306 // Reads a directory recursively by default and searches for files not matching
3307 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3308 // a whole directory.
3309 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3310 // Add default entries we should exclude
3311 $excludeArray[] = '.';
3312 $excludeArray[] = '..';
3313 $excludeArray[] = '.svn';
3314 $excludeArray[] = '.htaccess';
3316 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3321 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3324 while ($baseFile = readdir($dirPointer)) {
3325 // Exclude '.', '..' and entries in $excludeArray automatically
3326 if (in_array($baseFile, $excludeArray, true)) {
3328 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3332 // Construct include filename and FQFN
3333 $fileName = $baseDir . $baseFile;
3334 $FQFN = getConfig('PATH') . $fileName;
3336 // Remove double slashes
3337 $FQFN = str_replace('//', '/', $FQFN);
3339 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3340 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3341 // These Lines are only for debugging!!
3342 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3343 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3344 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3350 // Skip also files with non-matching prefix genericly
3351 if (($recursive === true) && (isDirectory($FQFN))) {
3352 // Is a redirectory so read it as well
3353 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3355 // And skip further processing
3357 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3359 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3361 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3362 // Skip wrong suffix as well
3363 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3365 } elseif (!isFileReadable($FQFN)) {
3366 // Not readable so skip it
3367 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3371 // Is the file a PHP script or other?
3372 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3373 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3374 // Is this a valid include file?
3375 if ($extension == '.php') {
3376 // Remove both for extension name
3377 $extName = substr($baseFile, strlen($prefix), -4);
3379 // Is the extension valid and active?
3380 if (isExtensionNameValid($extName)) {
3381 // Then add this file
3382 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3383 $files[] = $fileName;
3385 // Add non-extension files as well
3386 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3387 if ($addBaseDir === true) {
3388 $files[] = $fileName;
3390 $files[] = $baseFile;
3394 // We found .php file but should not search for them, why?
3395 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3397 } elseif (substr($baseFile, -4, 4) == $extension) {
3398 // Other, generic file found
3399 $files[] = $fileName;
3404 closedir($dirPointer);
3409 // Return array with include files
3410 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3414 // Maps a module name into a database table name
3415 function mapModuleToTable ($moduleName) {
3416 // Map only these, still lame code...
3417 switch ($moduleName) {
3418 // 'index' is the guest's menu
3419 case 'index': $moduleName = 'guest'; break;
3420 // ... and 'login' the member's menu
3421 case 'login': $moduleName = 'member'; break;
3422 // Anything else will not be mapped, silently.
3429 // Add SQL debug data to array for later output
3430 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3431 // Already executed?
3432 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3433 // Then abort here, we don't need to profile a query twice
3437 // Remeber this as profiled (or not, but we don't care here)
3438 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3440 // Do we have cache?
3441 if (!isset($GLOBALS['debug_sql_available'])) {
3442 // Check it and cache it in $GLOBALS
3443 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3446 // Don't execute anything here if we don't need or ext-other is missing
3447 if ($GLOBALS['debug_sql_available'] === false) {
3453 'num_rows' => SQL_NUMROWS($result),
3454 'affected' => SQL_AFFECTEDROWS(),
3455 'sql_str' => $sqlString,
3456 'timing' => $timing,
3457 'file' => basename($F),
3462 $GLOBALS['debug_sqls'][] = $record;
3465 // Initializes the cache instance
3466 function initCacheInstance () {
3467 // Load include for CacheSystem class
3468 loadIncludeOnce('inc/classes/cachesystem.class.php');
3470 // Initialize cache system only when it's needed
3471 $GLOBALS['cache_instance'] = new CacheSystem();
3472 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3473 // Failed to initialize cache sustem
3474 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3478 // Getter for message from array or raw message
3479 function getMessageFromIndexedArray ($message, $pos, $array) {
3480 // Check if the requested message was found in array
3481 if (isset($array[$pos])) {
3482 // ... if yes then use it!
3483 $ret = $array[$pos];
3485 // ... else use default message
3493 // Print code with line numbers
3494 function linenumberCode ($code) {
3495 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3496 $count_lines = count($codeE);
3498 $r = 'Line | Code:<br />';
3499 foreach($codeE as $line => $c) {
3500 $r .= '<div class="line"><span class="linenum">';
3501 if ($count_lines == 1) {
3504 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3509 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3512 return '<div class="code">' . $r . '</div>';
3515 // Convert ';' to ', ' for e.g. receiver list
3516 function convertReceivers ($old) {
3517 return str_replace(';', ', ', $old);
3520 // Determines the right page title
3521 function determinePageTitle () {
3522 // Config and database connection valid?
3523 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3527 // Title decoration enabled?
3528 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3530 // Do we have some extra title?
3531 if (isExtraTitleSet()) {
3533 $TITLE .= getExtraTitle() . ' by ';
3537 $TITLE .= getConfig('MAIN_TITLE');
3539 // Add title of module? (middle decoration will also be added!)
3540 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3541 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3544 // Add title from what file
3546 if (getModule() == 'login') $mode = 'member';
3547 elseif (getModule() == 'index') $mode = 'guest';
3548 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3550 // Add title decorations? (right)
3551 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3553 // Remember title in constant for the template
3554 $pageTitle = $TITLE;
3555 } elseif ((isInstalled()) && (isAdminRegistered())) {
3556 // Installed, admin registered but no ext-sql_patches
3557 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3558 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3559 // Installed but no admin registered
3560 $pageTitle = getMessage('SETUP_OF_MXCHANGE');
3561 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3562 // Installation mode
3563 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3565 // Configuration not found!
3566 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3568 // Do not add the fatal message in installation mode
3569 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3573 return decodeEntities($pageTitle);
3576 // Checks wethere there is a cache file there. This function is cached.
3577 function isTemplateCached ($template) {
3578 // Do we have cached this result?
3579 if (!isset($GLOBALS['template_cache'][$template])) {
3581 $FQFN = generateCacheFqfn($template);
3584 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3588 return $GLOBALS['template_cache'][$template];
3591 // Flushes non-flushed template cache to disk
3592 function flushTemplateCache ($template, $eval) {
3593 // Is this cache flushed?
3594 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3596 $FQFN = generateCacheFqfn($template);
3598 // Replace username with a call
3599 $eval = str_replace('$username', '".getUsername()."', $eval);
3602 writeToFile($FQFN, $eval, true);
3606 // Reads a template cache
3607 function readTemplateCache ($template) {
3609 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3611 $FQFN = generateCacheFqfn($template);
3614 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3618 return $GLOBALS['template_eval'][$template];
3621 // Escapes quotes (default is only double-quotes)
3622 function escapeQuotes ($str, $single = false) {
3623 // Should we escape all?
3624 if ($single === true) {
3625 // Escape all (including null)
3626 $str = addslashes($str);
3628 // Escape only double-quotes but prevent double-quoting
3629 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3632 // Return the escaped string
3636 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3637 function escapeJavaScriptQuotes ($str) {
3638 // Replace all double-quotes and secure back-ticks
3639 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3645 // Send out mails depending on the 'mod/modes' combination
3646 // @TODO Lame description for this function
3647 function sendModeMails ($mod, $modes) {
3649 if (fetchUserData(getMemberId())) {
3650 // Extract salt from cookie
3651 $salt = substr(getSession('u_hash'), 0, -40);
3653 // Now let's compare passwords
3654 $hash = encodeHashForCookie(getUserData('password'));
3656 // Does the hash match or should we change it?
3657 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
3659 $content = getUserDataArray();
3662 $content['gender'] = translateGender($content['gender']);
3664 // Clear/init the content variable
3665 $content['message'] = '';
3668 // @TODO Move this in a filter
3671 foreach ($modes as $mode) {
3673 case 'normal': break; // Do not add any special lines
3674 case 'email': // Email was changed!
3675 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestParameter('old_email')."\n";
3678 case 'pass': // Password was changed
3679 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3683 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3684 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3689 if (isExtensionActive('country')) {
3690 // Replace code with description
3691 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
3694 // Merge content with data from POST
3695 $content = merge_array($content, postRequestArray());
3698 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3700 if (getConfig('admin_notify') == 'Y') {
3701 // The admin needs to be notified about a profile change
3702 $message_admin = 'admin_mydata_notify';
3703 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3706 $message_admin = '';
3710 // Set subject lines
3711 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3713 // Output success message
3714 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3717 default: // Unsupported module!
3718 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3719 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
3723 // Passwords mismatch
3724 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
3727 // Could not load profile
3728 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
3731 // Send email to user if required
3732 if ((!empty($sub_mem)) && (!empty($message))) {
3734 sendEmail($content['email'], $sub_mem, $message);
3737 // Send only if no other error has occured
3738 if (empty($content)) {
3739 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3741 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3742 } elseif (getConfig('admin_notify') == 'Y') {
3743 // Cannot send mails to admin!
3744 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3747 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3752 loadTemplate('admin_settings_saved', false, $content);
3755 // Generates a 'selection box' from given array
3756 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
3758 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3759 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3761 // Walk through all options
3762 foreach ($options as $option) {
3763 // Add the <option> entry
3764 if (empty($optionContent)) {
3765 // ... from template
3766 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
3769 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3773 // Finish selection box
3774 $OUT .= '</select>';
3778 'selection_box' => $OUT,
3779 'module' => getModule(),
3783 // Load template and return it
3784 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
3787 // Get a module from filename and access level
3788 function getModuleFromFileName ($file, $accessLevel) {
3789 // Default is 'invalid';
3790 $modCheck = 'invalid';
3792 // @TODO This is still very static, rewrite it somehow
3793 switch ($accessLevel) {
3795 $modCheck = 'admin';
3801 $modCheck = getModule();
3804 default: // Unsupported file name / access level
3805 debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3813 // Encodes an URL for adding session id, etc.
3814 function encodeUrl ($url, $outputMode = '0') {
3815 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
3816 if ((strpos($url, session_name()) !== false) || (getOutputMode() == -3)) return $url;
3818 // Do we have a valid session?
3819 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3821 // Determine right seperator
3822 $seperator = '&';
3823 if (strpos($url, '?') === false) {
3826 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3832 if (session_id() != '') {
3833 $url .= $seperator . session_name() . '=' . session_id();
3838 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3840 $url = '{?URL?}/' . $url;
3847 // Simple check for spider
3848 function isSpider () {
3850 $userAgent = strtolower(detectUserAgent(true));
3852 // It should not be empty, if so it is better a spider/bot
3853 if (empty($userAgent)) return true;
3856 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
3859 // Prepares the header for HTML output
3860 function loadHtmlHeader () {
3862 // 1.) pre_page_header (mainly loads the page_header template and includes
3863 // meta description)
3864 runFilterChain('pre_page_header');
3866 // Here can be something be added, but normally one of the two filters
3867 // around this line should do the job for you.
3869 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
3870 // to close the head-tag)
3871 // Include more header data here
3872 runFilterChain('post_page_header');
3875 // Adds page header and footer to output array element
3876 function addPageHeaderFooter () {
3880 // Add them all together. This is maybe to simple
3881 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
3882 // Add page part if set
3883 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
3886 // Transfer $OUT to 'output'
3887 $GLOBALS['output'] = $OUT;
3890 // Generates meta description for current module and 'what' value
3891 function generateMetaDescriptionCode () {
3892 // Only include from guest area and if sql_patches has correct version
3893 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3894 // Construct dynamic description
3895 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
3897 // Output it directly
3898 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
3902 unset($GLOBALS['ref_level']);
3905 // Generates an FQFN for template cache from the given template name
3906 function generateCacheFqfn ($template) {
3908 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
3909 // Generate the FQFN
3910 $GLOBALS['template_cache_fqfn'][$template] = sprintf("%s_compiled/html/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3914 return $GLOBALS['template_cache_fqfn'][$template];
3917 // Function to search for the last modified file
3918 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
3920 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
3921 // Does it match what we are looking for? (We skip a lot files already!)
3922 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
3923 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
3925 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
3926 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
3928 // Walk through all entries
3929 foreach ($ds as $d) {
3930 // Generate proper FQFN
3931 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir . '/' . $d);
3933 // Is it a file and readable?
3934 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
3935 if (isFileReadable($FQFN)) {
3936 // $FQFN is a readable file so extract the requested data from it
3937 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
3938 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
3940 // Is the file more recent?
3941 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
3942 // This file is newer as the file before
3943 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
3944 $last_changed['path_name'] = $FQFN;
3945 $last_changed[$lookFor] = $check;
3949 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
3954 // "Fixes" null or empty string to count of dashes
3955 function fixNullEmptyToDashes ($str, $num) {
3956 // Use str as default
3960 if ((is_null($str)) || (trim($str) == '')) {
3962 $return = str_repeat('-', $num);
3965 // Return final string
3969 // Handles the braces [] of a field (e.g. value of 'name' attribute)
3970 function handleFieldWithBraces ($field) {
3971 // Are there braces [] at the end?
3972 if (substr($field, -2, 2) == '[]') {
3973 // Try to find one and replace it. I do it this way to allow easy
3974 // extending of this code.
3975 foreach (array('admin_list_builder_id_value') as $key) {
3976 // Is the cache entry set?
3977 if (isset($GLOBALS[$key])) {
3979 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
3991 //////////////////////////////////////////////////
3992 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3993 //////////////////////////////////////////////////
3995 if (!function_exists('html_entity_decode')) {
3996 // Taken from documentation on www.php.net
3997 function html_entity_decode ($string) {
3998 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3999 $trans_tbl = array_flip($trans_tbl);
4000 return strtr($string, $trans_tbl);
4004 if (!function_exists('http_build_query')) {
4005 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
4006 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
4008 foreach ((array)$data as $k => $v) {
4009 if (is_int($k) && $prefix != null) {
4010 $k = urlencode($prefix . $k);
4013 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
4015 if (is_array($v) || is_object($v)) {
4016 array_push($ret, http_build_query($v, '', $sep, $k));
4018 array_push($ret, $k.'='.urlencode($v));
4022 if (empty($sep)) $sep = ini_get('arg_separator.output');
4024 return implode($sep, $ret);