2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/25/2003 *
4 * =================== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
46 function outputHtml ($htmlCode, $newLine = true) {
48 if (!isset($GLOBALS['output'])) $GLOBALS['output'] = '';
51 $username = getMessage('USERNAME_UNKNOWN');
52 if (isset($GLOBALS['username'])) $username = getUsername();
54 // Do we have HTML-Code here?
55 if (!empty($htmlCode)) {
56 // Yes, so we handle it as you have configured
57 switch (getConfig('OUTPUT_MODE')) {
59 // That's why you don't need any \n at the end of your HTML code... :-)
60 if (getPhpCaching() == 'on') {
61 // Output into PHP's internal buffer
62 outputRawCode($htmlCode);
64 // That's why you don't need any \n at the end of your HTML code... :-)
65 if ($newLine === true) print("\n");
67 // Render mode for old or lame servers...
68 $GLOBALS['output'] .= $htmlCode;
70 // That's why you don't need any \n at the end of your HTML code... :-)
71 if ($newLine === true) $GLOBALS['output'] .= "\n";
76 // If we are switching from render to direct output rendered code
77 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
79 // The same as above... ^
80 outputRawCode($htmlCode);
81 if ($newLine === true) print("\n");
85 // Huh, something goes wrong or maybe you have edited config.php ???
86 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
89 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
90 // Output cached HTML code
91 $GLOBALS['output'] = ob_get_contents();
93 // Clear output buffer for later output if output is found
94 if (!empty($GLOBALS['output'])) {
98 // Extension 'rewrite' installed?
99 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
100 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
103 // Send all HTTP headers
106 // Compile and run finished rendered HTML code
107 compileFinalOutput();
109 // Output code here, DO NOT REMOVE! ;-)
110 outputRawCode($GLOBALS['output']);
111 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
112 // Rewrite links when rewrite extension is active
113 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
114 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
117 // Send all HTTP headers
120 // Compile and run finished rendered HTML code
121 compileFinalOutput();
123 // Output code here, DO NOT REMOVE! ;-)
124 outputRawCode($GLOBALS['output']);
126 // And flush all headers
131 // Sends out all headers required for HTTP/1.1 reply
132 function sendHttpHeaders () {
134 $now = gmdate('D, d M Y H:i:s') . ' GMT';
137 sendHeader('HTTP/1.1 200 OK');
139 // General headers for no caching
140 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
141 sendHeader('Last-Modified: ' . $now);
142 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
143 sendHeader('Pragma: no-cache'); // HTTP/1.0
144 sendHeader('Connection: Close');
145 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
146 sendHeader('Content-Language: ' . getLanguage());
149 // Compiles the final output
150 function compileFinalOutput () {
154 // Add page header and footer
155 addPageHeaderFooter();
158 while (((strpos($GLOBALS['output'], '{--') !== false) || (strpos($GLOBALS['output'], '{!') !== false) || (strpos($GLOBALS['output'], '{?') !== false) || (strpos($GLOBALS['output'], '{%') !== false)) && ($cnt < 3)) {
159 // Init common variables
164 //* DEBUG: */ print '<pre>'.htmlentities($GLOBALS['output']).'</pre>';
165 $eval = '$newContent = "' . compileCode(escapeQuotes($GLOBALS['output'])) . '";';
166 //* DEBUG: */ die('<pre>'.htmlentities($eval).'</pre>');
169 // Was that eval okay?
170 if (empty($newContent)) {
171 // Something went wrong!
172 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
176 $GLOBALS['output'] = $newContent;
183 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
184 // Compress it for HTTP gzip
185 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
188 sendHeader('Content-Encoding: gzip');
189 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
190 // Compress it for HTTP deflate
191 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
194 sendHeader('Content-Encoding: deflate');
198 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
204 // Output the raw HTML code
205 function outputRawCode ($htmlCode) {
206 // Output stripped HTML code to avoid broken JavaScript code, etc.
207 print(str_replace('{BACK}', "\\", $htmlCode));
209 // Flush the output if only getPhpCaching() is not 'on'
210 if (getPhpCaching() != 'on') {
216 // Init fatal message array
217 function initFatalMessages () {
218 $GLOBALS['fatal_messages'] = array();
221 // Getter for whole fatal error messages
222 function getFatalArray () {
223 return $GLOBALS['fatal_messages'];
226 // Add a fatal error message to the queue array
227 function addFatalMessage ($F, $L, $message, $extra = '') {
228 if (is_array($extra)) {
229 // Multiple extras for a message with masks
230 $message = call_user_func_array('sprintf', $extra);
231 } elseif (!empty($extra)) {
232 // $message is text with a mask plus extras to insert into the text
233 $message = sprintf($message, $extra);
236 // Add message to $GLOBALS['fatal_messages']
237 $GLOBALS['fatal_messages'][] = $message;
239 // Log fatal messages away
240 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
243 // Getter for total fatal message count
244 function getTotalFatalErrors () {
248 // Do we have at least the first entry?
249 if (!empty($GLOBALS['fatal_messages'][0])) {
251 $count = count($GLOBALS['fatal_messages']);
258 // Load a template file and return it's content (only it's name; do not use ' or ")
259 function loadTemplate ($template, $return = false, $content = array()) {
260 // @TODO Remove this sanity-check if all is fine
261 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
263 // @TODO Try to rewrite all $DATA to $content
267 if (isTemplateCached($template)) {
268 // Evaluate the cache
269 eval(readTemplateCache($template));
270 } elseif (!isset($GLOBALS['template_eval'][$template])) {
271 // Add more variables which you want to use in your template files
272 $username = getUsername();
274 // Make all template names lowercase
275 $template = strtolower($template);
279 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
282 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
283 $extraPath = detectExtraTemplatePath($template);;
285 ////////////////////////
286 // Generate file name //
287 ////////////////////////
288 $FQFN = $basePath . $extraPath . $template . '.tpl';
290 // Does the special template exists?
291 if (!isFileReadable($FQFN)) {
292 // Reset to default template
293 $FQFN = $basePath . $template . '.tpl';
296 // Now does the final template exists?
297 if (isFileReadable($FQFN)) {
298 // Count the template load
299 incrementConfigEntry('num_templates');
301 // The local file does exists so we load it. :)
302 $GLOBALS['tpl_content'] = readFromFile($FQFN);
304 // Do we have to compile the code?
306 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)) {
307 // Normal HTML output?
308 if (getOutputMode() == '0') {
309 // Add surrounding HTML comments to help finding bugs faster
310 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
312 // Prepare eval() command
313 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
314 } elseif (substr($template, 0, 3) == 'js_') {
315 // JavaScripts don't like entities and timings
316 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
318 // Prepare eval() command, other output doesn't like entities, maybe
319 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
322 // Add surrounding HTML comments to help finding bugs faster
323 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
324 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
327 // Cache the eval() command here
328 $GLOBALS['template_eval'][$template] = $eval;
331 eval($GLOBALS['template_eval'][$template]);
332 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
333 // Only admins shall see this warning or when installation mode is active
334 $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
335 (' . $template . ')<br />
337 {--TEMPLATE_CONTENT--}
338 <pre>' . print_r($content, true) . '</pre>
340 <pre>' . print_r($DATA, true) . '</pre>
344 $GLOBALS['template_eval'][$template] = '404';
348 eval($GLOBALS['template_eval'][$template]);
351 // Do we have some content to output or return?
353 // Not empty so let's put it out! ;)
354 if ($return === true) {
355 // Return the HTML code
361 } elseif (isDebugModeEnabled()) {
362 // Warning, empty output!
363 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
367 // Detects the extra template path from given template name
368 function detectExtraTemplatePath ($template) {
373 if (!isset($GLOBALS['extra_path'][$template])) {
374 // Check for admin/guest/member/etc. templates
375 if (substr($template, 0, 6) == 'admin_') {
376 // Admin template found
377 $extraPath = 'admin/';
378 } elseif (substr($template, 0, 6) == 'guest_') {
379 // Guest template found
380 $extraPath = 'guest/';
381 } elseif (substr($template, 0, 7) == 'member_') {
382 // Member template found
383 $extraPath = 'member/';
384 } elseif (substr($template, 0, 7) == 'select_') {
385 // Selection template found
386 $extraPath = 'select/';
387 } elseif (substr($template, 0, 8) == 'install_') {
388 // Installation template found
389 $extraPath = 'install/';
390 } elseif (substr($template, 0, 4) == 'ext_') {
391 // Extension template found
393 } elseif (substr($template, 0, 3) == 'la_') {
394 // 'Logical-area' template found
396 } elseif (substr($template, 0, 3) == 'js_') {
397 // JavaScript template found
399 } elseif (substr($template, 0, 5) == 'menu_') {
400 // Menu template found
401 $extraPath = 'menu/';
403 // Test for extension
404 $test = substr($template, 0, strpos($template, '_'));
406 // Probe for valid extension name
407 if (isExtensionNameValid($test)) {
408 // Set extra path to extension's name
409 $extraPath = $test . '/';
414 $GLOBALS['extra_path'][$template] = $extraPath;
418 return $GLOBALS['extra_path'][$template];
421 // Loads an email template and compiles it
422 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
425 // Make sure all template names are lowercase!
426 $template = strtolower($template);
428 // Default 'nickname' if extension is not installed
431 // Neutral email address is default
432 $email = getConfig('WEBMASTER');
434 // Is content an array?
435 if (is_array($content)) {
436 // Add expiration to array
437 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
438 // Will never expire!
439 $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
440 } elseif (isConfigEntrySet('auto_purge')) {
441 // Create nice date string
442 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
445 $content['expiration'] = getMessage('MAIL_NO_CONFIG_AUTO_PURGE');
450 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content).'<br />');
451 if (($userid > 0) && (is_array($content))) {
452 // If nickname extension is installed, fetch nickname as well
453 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
454 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
456 fetchUserData($userid, 'nickname');
458 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
460 fetchUserData($userid);
463 // Merge data if valid
464 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
465 if (isUserDataValid()) {
466 $content = merge_array($content, getUserDataArray());
468 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
471 // Translate M to male or F to female if present
472 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
474 // Overwrite email from data if present
475 if (isset($content['email'])) $email = $content['email'];
477 // Store email for some functions in global $DATA array
478 // @TODO Do only use $content, not $DATA or raw variables
479 $DATA['email'] = $email;
482 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
485 $extraPath = detectExtraTemplatePath($template);
487 // Generate full FQFN
488 $FQFN = $basePath . $extraPath . $template . '.tpl';
490 // Does the special template exists?
491 if (!isFileReadable($FQFN)) {
492 // Reset to default template
493 $FQFN = $basePath . $template . '.tpl';
496 // Now does the final template exists?
498 if (isFileReadable($FQFN)) {
499 // The local file does exists so we load it. :)
500 $GLOBALS['tpl_content'] = readFromFile($FQFN);
503 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
504 eval($GLOBALS['tpl_content']);
505 } elseif (!empty($template)) {
506 // Template file not found!
507 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
508 {--TEMPLATE_CONTENT--}
509 <pre>' . print_r($content, true) . '</pre>
511 <pre>' . print_r($DATA, true) . '</pre>
514 // Debug mode not active? Then remove the HTML tags
515 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
517 // No template name supplied!
518 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
521 // Is there some content?
522 if (empty($newContent)) {
524 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
526 // Add last error if the required function exists
527 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
530 // Remove content and data
538 // Send mail out to an email address
539 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
540 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail},SUBJECT={$subject}<br />");
542 // Compile subject line (for POINTS constant etc.)
543 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
546 if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
547 // Value detected, is the message extension installed?
548 // @TODO Extension 'msg' does not exist
549 if (isExtensionActive('msg')) {
550 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
553 // Does the user exist?
554 if (fetchUserData($toEmail)) {
556 $toEmail = getUserData('email');
559 $toEmail = getConfig('WEBMASTER');
562 } elseif ($toEmail == '0') {
564 $toEmail = getConfig('WEBMASTER');
566 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
568 // Check for PHPMailer or debug-mode
569 if (!checkPhpMailerUsage()) {
570 // Not in PHPMailer-Mode
571 if (empty($mailHeader)) {
572 // Load email header template
573 $mailHeader = loadEmailTemplate('header');
576 $mailHeader .= loadEmailTemplate('header');
578 } elseif (isDebugModeEnabled()) {
579 if (empty($mailHeader)) {
580 // Load email header template
581 $mailHeader = loadEmailTemplate('header');
584 $mailHeader .= loadEmailTemplate('header');
589 eval('$toEmail = "' . compileRawCode(escapeQuotes($toEmail)) . '";');
592 eval('$message = "' . str_replace('$', '$', compileRawCode(escapeQuotes($message))) . '";');
594 // Fix HTML parameter (default is no!)
595 if (empty($isHtml)) $isHtml = 'N';
596 if (isDebugModeEnabled()) {
597 // In debug mode we want to display the mail instead of sending it away so we can debug this part
599 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
600 To : ' . htmlentities(utf8_decode($toEmail)) . '
601 Subject : ' . htmlentities(utf8_decode($subject)) . '
602 Message : ' . htmlentities(utf8_decode($message)) . '
604 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
605 // Send mail as HTML away
606 return sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
607 } elseif (!empty($toEmail)) {
609 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
610 } elseif ($isHtml != 'Y') {
612 return sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
616 // Check to use wether legacy mail() command or PHPMailer class
617 // @TODO Rewrite this to an extension 'smtp'
619 function checkPhpMailerUsage() {
620 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
623 // Send out a raw email with PHPMailer class or legacy mail() command
624 function sendRawEmail ($toEmail, $subject, $message, $from) {
625 // Just compile all again, to put out all configs, etc.
626 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
627 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
628 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
629 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
631 // Shall we use PHPMailer class or legacy mode?
632 if (checkPhpMailerUsage()) {
633 // Use PHPMailer class with SMTP enabled
634 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
635 loadIncludeOnce('inc/phpmailer/class.smtp.php');
638 $mail = new PHPMailer();
640 // Set charset to UTF-8
641 $mail->CharSet = 'UTF-8';
643 // Path for PHPMailer
644 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
647 $mail->SMTPAuth = true;
648 $mail->Host = getConfig('SMTP_HOSTNAME');
650 $mail->Username = getConfig('SMTP_USER');
651 $mail->Password = getConfig('SMTP_PASSWORD');
653 $mail->From = getConfig('WEBMASTER');
657 $mail->FromName = getConfig('MAIN_TITLE');
658 $mail->Subject = $subject;
659 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
660 $mail->Body = $message;
661 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
662 $mail->WordWrap = 70;
665 $mail->Body = decodeEntities($message);
667 $mail->AddAddress($toEmail, '');
668 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
669 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
670 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
673 // Has an error occured?
674 if (!empty($mail->ErrorInfo)) {
676 logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
685 // Use legacy mail() command
686 return mail($toEmail, $subject, decodeEntities($message), $from);
690 // Generate a password in a specified length or use default password length
691 function generatePassword ($length = '0') {
692 // Auto-fix invalid length of zero
693 if ($length == '0') $length = getConfig('pass_len');
695 // Initialize array with all allowed chars
696 $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,-,+,_,/,.');
698 // Start creating password
700 for ($i = '0'; $i < $length; $i++) {
701 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
704 // When the size is below 40 we can also add additional security by scrambling
705 // it. Otherwise we may corrupt hashes
706 if (strlen($PASS) <= 40) {
707 // Also scramble the password
708 $PASS = scrambleString($PASS);
711 // Return the password
715 // Generates a human-readable timestamp from the Uni* stamp
716 function generateDateTime ($time, $mode = '0') {
717 // Filter out numbers
718 $time = bigintval($time);
720 // If the stamp is zero it mostly didn't "happen"
723 return getMessage('NEVER_HAPPENED');
726 switch (getLanguage()) {
727 case 'de': // German date / time format
729 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
730 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
731 case '2': $ret = date('d.m.Y|H:i', $time); break;
732 case '3': $ret = date('d.m.Y', $time); break;
734 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
739 default: // Default is the US date / time format!
741 case '0': $ret = date('r', $time); break;
742 case '1': $ret = date('Y-m-d - g:i A', $time); break;
743 case '2': $ret = date('y-m-d|H:i', $time); break;
744 case '3': $ret = date('y-m-d', $time); break;
746 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
755 // Translates Y/N to yes/no
756 function translateYesNo ($yn) {
758 $translated = '??? (' . $yn . ')';
760 case 'Y': $translated = getMessage('YES'); break;
761 case 'N': $translated = getMessage('NO'); break;
764 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
772 // Translates the "pool type" into human-readable
773 function translatePoolType ($type) {
774 // Default?type is unknown
775 $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
778 $constName = sprintf("POOL_TYPE_%s", $type);
781 if (isMessageIdValid($constName)) {
783 $translated = getMessage($constName);
786 // Return "translation"
790 // Translates the american decimal dot into a german comma
791 function translateComma ($dotted, $cut = true, $max = '0') {
792 // First, cast all to double, due to PHP changes
793 $dotted = (double) $dotted;
795 // Default is 3 you can change this in admin area "Misc -> Misc Options"
796 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
798 // Use from config is default
799 $maxComma = getConfig('max_comma');
801 // Use from parameter?
802 if ($max > 0) $maxComma = $max;
805 if (($cut === true) && ($max == '0')) {
806 // Test for commata if in cut-mode
807 $com = explode('.', $dotted);
808 if (count($com) < 2) {
809 // Don't display commatas even if there are none... ;-)
815 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
818 switch (getLanguage()) {
819 case 'de': // German language
820 $dotted = number_format($dotted, $maxComma, ',', '.');
823 default: // All others
824 $dotted = number_format($dotted, $maxComma, '.', ',');
828 // Return translated value
832 // Translate Uni*-like gender to human-readable
833 function translateGender ($gender) {
835 $ret = '!' . $gender . '!';
837 // Male/female or company?
839 case 'M': $ret = getMessage('GENDER_M'); break;
840 case 'F': $ret = getMessage('GENDER_F'); break;
841 case 'C': $ret = getMessage('GENDER_C'); break;
843 // Please report bugs on unknown genders
844 debug_report_bug(sprintf("Unknown gender %s detected.", $gender));
848 // Return translated gender
852 // "Translates" the user status
853 function translateUserStatus ($status) {
854 // Generate message depending on status
859 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
864 $ret = getMessage('ACCOUNT_DELETED');
868 // Please report all unknown status
869 debug_report_bug(sprintf("Unknown status %s detected.", $status));
877 // Generates an URL for the dereferer
878 function generateDerefererUrl ($URL) {
879 // Don't de-refer our own links!
880 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
881 // De-refer this link
882 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
889 // Generates an URL for the frametester
890 function generateFrametesterUrl ($URL) {
891 // Prepare frametester URL
892 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
893 encodeString(compileUriCode($URL))
896 // Return the new URL
897 return $frametesterUrl;
900 // Count entries from e.g. a selection box
901 function countSelection ($array) {
903 if (!is_array($array)) {
905 debug_report_bug(__FUNCTION__.': No array provided.');
912 foreach ($array as $key => $selected) {
914 if (!empty($selected)) $ret++;
917 // Return counted selections
921 // Generate XHTML code for the CAPTCHA
922 function generateCaptchaCode ($code, $type, $DATA, $userid) {
923 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
926 // Generates a timestamp (some wrapper for mktime())
927 function makeTime ($hours, $minutes, $seconds, $stamp) {
928 // Extract day, month and year from given timestamp
929 $days = date('d', $stamp);
930 $months = date('m', $stamp);
931 $years = date('Y', $stamp);
933 // Create timestamp for wished time which depends on extracted date
944 // Redirects to an URL and if neccessarry extends it with own base URL
945 function redirectToUrl ($URL, $allowSpider = true) {
947 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
949 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
950 $rel = ' rel="external"';
952 // Do we have internal or external URL?
953 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
954 // Own (=internal) URL
958 // Three different ways to debug...
959 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
960 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
961 //* DEBUG: */ die($URL);
963 // Simple probe for bots/spiders from search engines
964 if ((isSpider()) && ($allowSpider === true)) {
965 // Secure the URL against bad things such als HTML insertions and so on...
966 $URL = secureString($URL);
968 // Set content-type here to fix a missing array element
969 setContentType('text/html');
971 // Output new location link as anchor
972 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
973 } elseif (!headers_sent()) {
974 // Clear own output buffer
975 $GLOBALS['output'] = '';
977 // Load URL when headers are not sent
978 sendHeader('Location: '.str_replace('&', '&', $URL));
980 // Output error message
981 loadInclude('inc/header.php');
982 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
983 loadInclude('inc/footer.php');
986 // Shut the mailer down here
990 // Wrapper for redirectToUrl but URL comes from a configuration entry
991 function redirectToConfiguredUrl ($configEntry) {
993 $URL = getConfig($configEntry);
998 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
1002 redirectToUrl($URL);
1005 // Compiles the given HTML/mail code
1006 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1007 // Is the code a string?
1008 if (!is_string($code)) {
1009 // Silently return it
1014 $startCompile = microtime(true);
1017 $code = compileRawCode($code, $simple, $constants, $full);
1020 $compiled = microtime(true);
1023 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1025 // Return compiled code
1029 // Compiles the code (use compileCode() only for HTML because of the comments)
1030 // @TODO $simple is deprecated
1031 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1032 // Is the code a string?
1033 if (!is_string($code)) {
1034 // Silently return it
1038 // Init replacement-array with smaller set of security characters
1039 $secChars = $GLOBALS['url_chars'];
1041 // Select full set of chars to replace when we e.g. want to compile URLs
1042 if ($full === true) $secChars = $GLOBALS['security_chars'];
1044 // Compile more through a filter
1045 $code = runFilterChain('compile_code', $code);
1047 // Compile constants
1048 if ($constants === true) {
1049 // BEFORE 0.2.1 : Language and data constants
1050 // WITH 0.2.1+ : Only language constants
1051 $code = str_replace('{--', "\" . getMessage('", str_replace('--}', "') . \"", $code));
1053 // BEFORE 0.2.1 : Not used
1054 // WITH 0.2.1+ : Data constants
1055 $code = str_replace('{!', "\" . constant('", str_replace('!}', "') . \"", $code));
1058 // Compile QUOT and other non-HTML codes
1059 foreach ($secChars['to'] as $k => $to) {
1060 // Do the reversed thing as in inc/libs/security_functions.php
1061 $code = str_replace($to, $secChars['from'][$k], $code);
1064 // Find $content[bla][blub] entries
1065 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1066 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1068 // Are some matches found?
1069 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1070 // Replace all matches
1071 $matchesFound = array();
1072 foreach ($matches[0] as $key => $match) {
1073 // Fuzzy look has failed by default
1074 $fuzzyFound = false;
1076 // Fuzzy look on match if already found
1077 foreach ($matchesFound as $found => $set) {
1079 $test = substr($found, 0, strlen($match));
1081 // Does this entry exist?
1082 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
1083 if ($test == $match) {
1085 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
1092 if ($fuzzyFound === true) continue;
1094 // Take all string elements
1095 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1096 // Replace it in the code
1097 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
1098 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1099 $code = str_replace($match, '".' . $newMatch . '."', $code);
1100 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1101 $matchesFound[$match] = 1;
1102 } elseif (!isset($matchesFound[$match])) {
1103 // Not yet replaced!
1104 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
1105 $code = str_replace($match, '".' . $match . '."', $code);
1106 $matchesFound[$match] = 1;
1115 /************************************************************************
1117 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1118 * $a_sort sortiert: *
1120 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1121 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1122 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1123 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1124 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1126 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1127 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1128 * Sie, dass es doch nicht so schwer ist! :-) *
1130 ************************************************************************/
1131 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1133 while ($primary_key < count($a_sort)) {
1134 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1135 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1137 if ($nums === false) {
1138 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1139 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1140 } elseif ($key != $key2) {
1141 // Sort numbers (E.g.: 9 < 10)
1142 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1143 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1147 // We have found two different values, so let's sort whole array
1148 foreach ($dummy as $sort_key => $sort_val) {
1149 $t = $dummy[$sort_key][$key];
1150 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1151 $dummy[$sort_key][$key2] = $t;
1162 // Write back sorted array
1167 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1170 if ($type == 'yn') {
1171 // This is a yes/no selection only!
1172 if ($id > 0) $prefix .= "[" . $id."]";
1173 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1175 // Begin with regular selection box here
1176 if (!empty($prefix)) $prefix .= "_";
1178 if ($id > 0) $type2 .= "[" . $id."]";
1179 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1184 for ($idx = 1; $idx < 32; $idx++) {
1185 $OUT .= "<option value=\"" . $idx."\"";
1186 if ($default == $idx) $OUT .= ' selected="selected"';
1187 $OUT .= ">" . $idx."</option>\n";
1191 case 'month': // Month
1192 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1193 $OUT .= "<option value=\"" . $month."\"";
1194 if ($default == $month) $OUT .= ' selected="selected"';
1195 $OUT .= ">" . $descr."</option>\n";
1199 case 'year': // Year
1201 $year = date('Y', time());
1203 // Use configured min age or fixed?
1204 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1206 $startYear = $year - getConfig('min_age');
1209 $startYear = $year - 16;
1212 // Calculate earliest year (100 years old people can still enter Internet???)
1213 $minYear = $year - 100;
1215 // Check if the default value is larger than minimum and bigger than actual year
1216 if (($default > $minYear) && ($default >= $year)) {
1217 for ($idx = $year; $idx < ($year + 11); $idx++) {
1218 $OUT .= "<option value=\"" . $idx."\"";
1219 if ($default == $idx) $OUT .= ' selected="selected"';
1220 $OUT .= ">" . $idx."</option>\n";
1222 } elseif ($default == -1) {
1223 // Current year minus 1
1224 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1226 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1229 // Get current year and subtract the configured minimum age
1230 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1231 // Calculate earliest year depending on extension version
1232 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1233 // Use configured minimum age
1234 $year = date('Y', time()) - getConfig('min_age');
1236 // Use fixed 16 years age
1237 $year = date('Y', time()) - 16;
1240 // Construct year selection list
1241 for ($idx = $minYear; $idx <= $year; $idx++) {
1242 $OUT .= "<option value=\"" . $idx."\"";
1243 if ($default == $idx) $OUT .= ' selected="selected"';
1244 $OUT .= ">" . $idx."</option>\n";
1251 for ($idx = '0'; $idx < 60; $idx+=5) {
1252 if (strlen($idx) == 1) $idx = '0' . $idx;
1253 $OUT .= "<option value=\"" . $idx."\"";
1254 if ($default == $idx) $OUT .= ' selected="selected"';
1255 $OUT .= ">" . $idx."</option>\n";
1260 for ($idx = '0'; $idx < 24; $idx++) {
1261 if (strlen($idx) == 1) $idx = '0' . $idx;
1262 $OUT .= "<option value=\"" . $idx."\"";
1263 if ($default == $idx) $OUT .= ' selected="selected"';
1264 $OUT .= ">" . $idx."</option>\n";
1269 $OUT .= "<option value=\"Y\"";
1270 if ($default == 'Y') $OUT .= ' selected="selected"';
1271 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1272 if ($default != 'Y') $OUT .= ' selected="selected"';
1273 $OUT .= ">{--NO--}</option>\n";
1276 $OUT .= " </select>\n";
1281 // Deprecated : $length
1284 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1285 // Build server string
1286 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
1289 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1290 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1291 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1292 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1293 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1295 // Build string from misc data
1296 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1298 // Add more additional data
1299 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1301 // Add referal id, language, theme and userid
1302 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1303 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1304 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1305 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1307 // Calculate number for generating the code
1308 $a = $code + getConfig('_ADD') - 1;
1310 if (isConfigEntrySet('master_salt')) {
1311 // Generate hash with master salt from modula of number with the prime number and other data
1312 $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'));
1314 // Create number from hash
1315 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1317 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1318 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, getConfig('salt_length')));
1320 // Create number from hash
1321 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1324 // At least 10 numbers shall be secure enought!
1325 $len = getConfig('code_length');
1326 if ($len == '0') $len = $length;
1327 if ($len == '0') $len = 10;
1329 // Cut off requested counts of number
1330 $return = substr(str_replace('.', '', $rcode), 0, $len);
1332 // Done building code
1336 // Does only allow numbers
1337 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
1338 // Filter all numbers out
1339 $ret = preg_replace('/[^0123456789]/', '', $num);
1342 if ($castValue === true) $ret = (double)$ret;
1344 // Has the whole value changed?
1345 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
1347 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1354 // Insert the code in $img_code into jpeg or PNG image
1355 function generateImageOrCode ($img_code, $headerSent = true) {
1356 // Is the code size oversized or shouldn't we display it?
1357 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1358 // Stop execution of function here because of over-sized code length
1359 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1360 } elseif ($headerSent === false) {
1361 // Return an HTML code here
1362 return "<img src=\"{%url=img.php?code=" . $img_code."%}\" alt=\"Image\" />\n";
1366 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1369 getConfig('img_type')
1373 if (isFileReadable($img)) {
1374 // Switch image type
1375 switch (getConfig('img_type'))
1378 // Okay, load image and hide all errors
1379 $image = imagecreatefromjpeg($img);
1383 // Okay, load image and hide all errors
1384 $image = imagecreatefrompng($img);
1388 // Exit function here
1389 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1393 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1394 $text_color = imagecolorallocate($image, 0, 0, 0);
1396 // Insert code into image
1397 imagestring($image, 5, 14, 2, $img_code, $text_color);
1399 // Return to browser
1400 sendHeader('Content-Type: image/' . getConfig('img_type'));
1402 // Output image with matching image factory
1403 switch (getConfig('img_type')) {
1404 case 'jpg': imagejpeg($image); break;
1405 case 'png': imagepng($image); break;
1408 // Remove image from memory
1409 imagedestroy($image);
1411 // Create selection box or array of splitted timestamp
1412 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1413 // Do not continue if ONE_DAY is absend
1414 if (!isConfigEntrySet('ONE_DAY')) {
1415 // And return the timestamp itself or empty array
1416 if ($return_array === true) {
1423 // Calculate 2-seconds timestamp
1424 $stamp = round($timestamp);
1425 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1427 // Do we have a leap year?
1429 $TEST = date('Y', time()) / 4;
1430 $M1 = date('m', time());
1431 $M2 = date('m', (time() + $timestamp));
1433 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1434 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1436 // First of all years...
1437 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1438 //* DEBUG: */ print("Y={$Y}<br />");
1440 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1441 //* DEBUG: */ print("M={$M}<br />");
1443 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1444 //* DEBUG: */ print("W={$W}<br />");
1446 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1447 //* DEBUG: */ print("D={$D}<br />");
1449 $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));
1450 //* DEBUG: */ print("h={$h}<br />");
1452 $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));
1453 //* DEBUG: */ print("m={$m}<br />");
1454 // And at last seconds...
1455 $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));
1456 //* DEBUG: */ print("s={$s}<br />");
1458 // Is seconds zero and time is < 60 seconds?
1459 if (($s == '0') && ($timestamp < 60)) {
1461 $s = round($timestamp);
1465 // Now we convert them in seconds...
1467 if ($return_array) {
1468 // Just put all data in an array for later use
1480 $OUT = "<div align=\"" . $align."\">\n";
1481 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"timebox_table dashed\">\n";
1484 if (isInString('Y', $display) || (empty($display))) {
1485 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1488 if (isInString('M', $display) || (empty($display))) {
1489 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1492 if (isInString('W', $display) || (empty($display))) {
1493 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1496 if (isInString('D', $display) || (empty($display))) {
1497 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1500 if (isInString('h', $display) || (empty($display))) {
1501 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1504 if (isInString('m', $display) || (empty($display))) {
1505 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1508 if (isInString('s', $display) || (empty($display))) {
1509 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1515 if (isInString('Y', $display) || (empty($display))) {
1516 // Generate year selection
1517 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ye\" size=\"1\">\n";
1518 for ($idx = '0'; $idx <= 10; $idx++) {
1519 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1520 if ($idx == $Y) $OUT .= ' selected="selected"';
1521 $OUT .= ">" . $idx."</option>\n";
1523 $OUT .= " </select></td>\n";
1525 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1528 if (isInString('M', $display) || (empty($display))) {
1529 // Generate month selection
1530 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mo\" size=\"1\">\n";
1531 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>\n";
1537 $OUT .= " </select></td>\n";
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\">\n";
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>\n";
1550 $OUT .= " </select></td>\n";
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\">\n";
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>\n";
1563 $OUT .= " </select></td>\n";
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\">\n";
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>\n";
1576 $OUT .= " </select></td>\n";
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\">\n";
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>\n";
1589 $OUT .= " </select></td>\n";
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\">\n";
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>\n";
1602 $OUT .= " </select></td>\n";
1604 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1607 $OUT .= "</table>\n";
1609 // Return generated HTML code
1615 function createTimestampFromSelections ($prefix, $postData) {
1616 // Initial return value
1619 // Do we have a leap year?
1621 $TEST = date('Y', time()) / 4;
1622 $M1 = date('m', time());
1623 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1624 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
1625 // First add years...
1626 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1628 $ret += $postData[$prefix . '_mo'] * 2628000;
1630 $ret += $postData[$prefix . '_we'] * 604800;
1632 $ret += $postData[$prefix . '_da'] * 86400;
1634 $ret += $postData[$prefix . '_ho'] * 3600;
1636 $ret += $postData[$prefix . '_mi'] * 60;
1637 // And at last seconds...
1638 $ret += $postData[$prefix . '_se'];
1639 // Return calculated value
1643 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1644 function createFancyTime ($stamp) {
1645 // Get data array with years/months/weeks/days/...
1646 $data = createTimeSelections($stamp, '', '', '', true);
1648 foreach($data as $k => $v) {
1650 // Value is greater than 0 "eval" data to return string
1651 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1656 // Do we have something there?
1657 if (strlen($ret) > 0) {
1658 // Remove leading commata and space
1659 $ret = substr($ret, 2);
1662 $ret = "0 {--_SECONDS--}";
1665 // Return fancy time string
1669 // Generates a navigation row for listing emails
1670 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1672 if ($show_form === false) {
1677 for ($page = 1; $page <= $PAGES; $page++) {
1678 // Is the page currently selected or shall we generate a link to it?
1679 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1680 // Is currently selected, so only highlight it
1681 $NAV .= '<strong>-';
1683 // Open anchor tag and add base URL
1684 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1686 // Add userid when we shall show all mails from a single member
1687 if ((isGetRequestParameterSet('userid')) && (bigintval(getRequestParameter('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestParameter('userid'));
1689 // Close open anchor tag
1693 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1694 // Is currently selected, so only highlight it
1695 $NAV .= '-</strong>';
1701 // Add seperator if we have not yet reached total pages
1702 if ($page < $PAGES) $NAV .= ' | ';
1705 // Define constants only once
1706 $content['nav'] = $NAV;
1707 $content['span'] = $colspan;
1708 $content['top'] = $TOP;
1710 // Load navigation template
1711 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1713 if ($return === true) {
1714 // Return generated HTML-Code
1722 // Extract host from script name
1723 function extractHostnameFromUrl (&$script) {
1724 // Use default SERVER_URL by default... ;) So?
1725 $url = getConfig('SERVER_URL');
1727 // Is this URL valid?
1728 if (substr($script, 0, 7) == 'http://') {
1729 // Use the hostname from script URL as new hostname
1730 $url = substr($script, 7);
1731 $extract = explode('/', $url);
1733 // Done extracting the URL :)
1736 // Extract host name
1737 $host = str_replace('http://', '', $url);
1738 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1740 // Generate relative URL
1741 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1742 if (substr(strtolower($script), 0, 7) == 'http://') {
1743 // But only if http:// is in front!
1744 $script = substr($script, (strlen($url) + 7));
1745 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1747 $script = substr($script, (strlen($url) + 8));
1750 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1751 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1757 // Send a GET request
1758 function sendGetRequest ($script, $data = array()) {
1759 // Extract host name from script
1760 $host = extractHostnameFromUrl($script);
1763 $body = http_build_query($data, '', '&');
1765 // Do we have a question-mark in the script?
1766 if (strpos($script, '?') === false) {
1767 // No, so first char must be question mark
1768 $body = '?' . $body;
1771 $body = '&' . $body;
1777 // Remove trailed & to make it more conform
1778 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
1780 // Generate GET request header
1781 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1782 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1783 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1784 if (isConfigEntrySet('FULL_VERSION')) {
1785 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1787 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1789 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
1790 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1791 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
1792 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1793 $request .= getConfig('HTTP_EOL');
1795 // Send the raw request
1796 $response = sendRawRequest($host, $request);
1798 // Return the result to the caller function
1802 // Send a POST request
1803 function sendPostRequest ($script, $postData) {
1804 // Is postData an array?
1805 if (!is_array($postData)) {
1807 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1808 return array('', '', '');
1811 // Extract host name from script
1812 $host = extractHostnameFromUrl($script);
1814 // Construct request body
1815 $body = http_build_query($postData, '', '&');
1817 // Generate POST request header
1818 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
1819 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1820 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1821 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1822 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1823 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1824 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1825 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1826 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
1827 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1828 $request .= getConfig('HTTP_EOL');
1833 // Send the raw request
1834 $response = sendRawRequest($host, $request);
1836 // Return the result to the caller function
1840 // Sends a raw request to another host
1841 function sendRawRequest ($host, $request) {
1842 // Init errno and errdesc with 'all fine' values
1843 $errno = '0'; $errdesc = '';
1846 $response = array('', '', '');
1848 // Default is not to use proxy
1851 // Are proxy settins set?
1852 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1858 loadIncludeOnce('inc/classes/resolver.class.php');
1860 // Get resolver instance
1861 $resolver = new HostnameResolver();
1864 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1865 if ($useProxy === true) {
1866 // Resolve hostname into IP address
1867 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
1869 // Connect to host through proxy connection
1870 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1872 // Resolve hostname into IP address
1873 $ip = $resolver->resolveHostname($host);
1875 // Connect to host directly
1876 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
1880 if (!is_resource($fp)) {
1882 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
1884 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
1885 // Cannot set non-blocking mode or timeout
1886 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
1891 if ($useProxy === true) {
1892 // Setup proxy tunnel
1893 $response = setupProxyTunnel($host, $fp);
1895 // If the response is invalid, abort
1896 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
1897 // Invalid response!
1898 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
1904 fwrite($fp, $request);
1907 $start = microtime(true);
1910 while (!feof($fp)) {
1911 // Get info from stream
1912 $info = stream_get_meta_data($fp);
1914 // Is it timed out? 15 seconds is a really patient...
1915 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1917 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1923 // Get line from stream
1924 $line = fgets($fp, 128);
1926 // Ignore empty lines because of non-blocking mode
1928 // uslepp a little to avoid 100% CPU load
1935 // Add it to response
1936 $response[] = trim($line);
1942 // Time request if debug-mode is enabled
1943 if (isDebugModeEnabled()) {
1944 // Add debug message...
1945 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1948 // Skip first empty lines
1950 foreach ($resp as $idx => $line) {
1952 $line = trim($line);
1954 // Is this line empty?
1957 array_shift($response);
1959 // Abort on first non-empty line
1964 //* DEBUG: */ print('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1965 //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1967 // Proxy agent found or something went wrong?
1968 if (!isset($response[0])) {
1969 // No response, maybe timeout
1970 $response = array('', '', '');
1971 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1972 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1973 // Proxy header detected, so remove two lines
1974 array_shift($response);
1975 array_shift($response);
1978 // Was the request successfull?
1979 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1980 // Not found / access forbidden
1981 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1982 $response = array('', '', '');
1989 // Sets up a proxy tunnel for given hostname and through resource
1990 function setupProxyTunnel ($host, $resource) {
1992 $response = array('', '', '');
1994 // Generate CONNECT request header
1995 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1996 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1998 // Use login data to proxy? (username at least!)
1999 if (getConfig('proxy_username') != '') {
2001 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
2002 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
2005 // Add last new-line
2006 $proxyTunnel .= getConfig('HTTP_EOL');
2007 //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
2010 fwrite($fp, $proxyTunnel);
2014 // No response received
2018 // Read the first line
2019 $resp = trim(fgets($fp, 10240));
2020 $respArray = explode(' ', $resp);
2021 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
2022 // Invalid response!
2030 // Taken from www.php.net isInStringIgnoreCase() user comments
2031 function isEmailValid ($email) {
2032 // Check first part of email address
2033 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
2036 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
2039 $regex = '@^' . $first . '\@' . $domain . '$@iU';
2041 // Return check result
2042 return preg_match($regex, $email);
2045 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2046 function isUrlValid ($URL, $compile=true) {
2047 // Trim URL a little
2048 $URL = trim(urldecode($URL));
2049 //* DEBUG: */ outputHtml($URL.'<br />');
2051 // Compile some chars out...
2052 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
2053 //* DEBUG: */ outputHtml($URL.'<br />');
2055 // Check for the extension filter
2056 if (isExtensionActive('filter')) {
2057 // Use the extension's filter set
2058 return FILTER_VALIDATE_URL($URL, false);
2061 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2062 // https:// in front of the URLs
2063 return isUrlValidSimple($URL);
2066 // Generate a list of administrative links to a given userid
2067 function generateMemberAdminActionLinks ($userid, $status = '') {
2068 // Make sure userid is a number
2069 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
2071 // Define all main targets
2072 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2074 // Begin of navigation links
2077 foreach ($targetArray as $tar) {
2078 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
2079 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
2080 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2081 // Locked accounts shall be unlocked
2082 $OUT .= 'UNLOCK_USER';
2084 // All other status is fine
2085 $OUT .= strtoupper($tar);
2087 $OUT .= '_TITLE--}">{--ADMIN_';
2088 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2089 // Locked accounts shall be unlocked
2090 $OUT .= 'UNLOCK_USER';
2092 // All other status is fine
2093 $OUT .= strtoupper($tar);
2095 $OUT .= '--}</a></span> | ';
2098 // Finish navigation link
2099 $OUT = substr($OUT, 0, -7) . ']';
2105 // Generate an email link
2106 function generateEmailLink ($email, $table = 'admins') {
2107 // Default email link (INSECURE! Spammer can read this by harvester programs)
2108 $EMAIL = 'mailto:' . $email;
2110 // Check for several extensions
2111 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2112 // Create email link for contacting admin in guest area
2113 $EMAIL = generateAdminEmailLink($email);
2114 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
2115 // Create email link for contacting a member within admin area (or later in other areas, too?)
2116 $EMAIL = generateUserEmailLink($email, 'admin');
2117 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2118 // Create email link to contact sponsor within admin area (or like the link above?)
2119 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2122 // Shall I close the link when there is no admin?
2123 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2125 // Return email link
2129 // Generate a hash for extra-security for all passwords
2130 function generateHash ($plainText, $salt = '', $hash = true) {
2132 //* DEBUG: */ outputHtml('plainText=' . $plainText . ',salt=' . $salt . ',hash='.intval($hash).'<br />');
2134 // Is the required extension 'sql_patches' there and a salt is not given?
2135 // 0123 4 43 3 4 432 2 3 32 2 3 3210
2136 if ((((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')))) {
2137 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2138 if ($hash === true) {
2139 // Is plain password
2140 return md5($plainText);
2142 // Is already a hash
2147 // Do we miss an arry element here?
2148 if (!isConfigEntrySet('file_hash')) {
2150 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2153 // When the salt is empty build a new one, else use the first x configured characters as the salt
2155 // Build server string for more entropy
2156 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2159 $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');
2162 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2164 // Calculate number for generating the code
2165 $a = time() + getConfig('_ADD') - 1;
2167 // Generate SHA1 sum from modula of number and the prime number
2168 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2169 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2170 $sha1 = scrambleString($sha1);
2171 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2172 //* DEBUG: */ $sha1b = descrambleString($sha1);
2173 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2175 // Generate the password salt string
2176 $salt = substr($sha1, 0, getConfig('salt_length'));
2177 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2180 //* DEBUG: */ outputHtml('salt=' . $salt . '<br />');
2181 $salt = substr($salt, 0, getConfig('salt_length'));
2182 //* DEBUG: */ outputHtml('salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />');
2184 // Sanity check on salt
2185 if (strlen($salt) != getConfig('salt_length')) {
2187 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2191 // Generate final hash (for debug output)
2192 $finalHash = $salt . sha1($salt . $plainText);
2195 //* DEBUG: */ outputHtml('finalHash=' . $finalHash);
2201 // Scramble a string
2202 function scrambleString($str) {
2206 // Final check, in case of failture it will return unscrambled string
2207 if (strlen($str) > 40) {
2208 // The string is to long
2210 } elseif (strlen($str) == 40) {
2212 $scrambleNums = explode(':', getConfig('pass_scramble'));
2214 // Generate new numbers
2215 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2218 // Compare both lengths and abort if different
2219 if (strlen($str) != count($scrambleNums)) return $str;
2221 // Scramble string here
2222 //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2223 for ($idx = '0'; $idx < strlen($str); $idx++) {
2224 // Get char on scrambled position
2225 $char = substr($str, $scrambleNums[$idx], 1);
2227 // Add it to final output string
2228 $scrambled .= $char;
2231 // Return scrambled string
2232 //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2236 // De-scramble a string scrambled by scrambleString()
2237 function descrambleString($str) {
2238 // Scramble only 40 chars long strings
2239 if (strlen($str) != 40) return $str;
2241 // Load numbers from config
2242 $scrambleNums = explode(':', getConfig('pass_scramble'));
2245 if (count($scrambleNums) != 40) return $str;
2247 // Begin descrambling
2248 $orig = str_repeat(' ', 40);
2249 //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2250 for ($idx = '0'; $idx < 40; $idx++) {
2251 $char = substr($str, $idx, 1);
2252 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2255 // Return scrambled string
2256 //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2260 // Generated a "string" for scrambling
2261 function genScrambleString ($len) {
2262 // Prepare array for the numbers
2263 $scrambleNumbers = array();
2265 // First we need to setup randomized numbers from 0 to 31
2266 for ($idx = '0'; $idx < $len; $idx++) {
2268 $rand = mt_rand(0, ($len -1));
2270 // Check for it by creating more numbers
2271 while (array_key_exists($rand, $scrambleNumbers)) {
2272 $rand = mt_rand(0, ($len -1));
2276 $scrambleNumbers[$rand] = $rand;
2279 // So let's create the string for storing it in database
2280 $scrambleString = implode(':', $scrambleNumbers);
2281 return $scrambleString;
2284 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2285 function encodeHashForCookie ($passHash) {
2286 // Return vanilla password hash
2289 // Is a secret key and master salt already initialized?
2290 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
2291 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2292 // Only calculate when the secret key is generated
2293 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getConfig('secret_key')));
2294 if ((strlen($passHash) != 49) || (strlen(getConfig('secret_key')) != 40)) {
2295 // Both keys must have same length so return unencrypted
2296 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getConfig('secret_key')) . '!=40');
2300 $newHash = ''; $start = 9;
2301 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
2302 for ($idx = 0; $idx < 20; $idx++) {
2303 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getConfig('secret_key'))), 2));
2304 $part2 = hexdec(substr(getConfig('secret_key'), $start, 2));
2305 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
2306 $mod = dechex($idx);
2307 if ($part1 > $part2) {
2308 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2309 } elseif ($part2 > $part1) {
2310 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2312 $mod = substr($mod, 0, 2);
2313 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
2314 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
2315 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
2320 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
2321 $ret = generateHash($newHash, getConfig('master_salt'));
2325 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
2329 // Fix "deleted" cookies
2330 function fixDeletedCookies ($cookies) {
2331 // Is this an array with entries?
2332 if ((is_array($cookies)) && (count($cookies) > 0)) {
2333 // Then check all cookies if they are marked as deleted!
2334 foreach ($cookies as $cookieName) {
2335 // Is the cookie set to "deleted"?
2336 if (getSession($cookieName) == 'deleted') {
2337 setSession($cookieName, '');
2343 // Output error messages in a fasioned way and die...
2344 function app_die ($F, $L, $message) {
2345 // Check if Script is already dieing and not let it kill itself another 1000 times
2346 if (!isset($GLOBALS['app_died'])) {
2347 // Make sure, that the script realy realy diese here and now
2348 $GLOBALS['app_died'] = true;
2350 // Set content type as text/html
2351 setContentType('text/html');
2354 loadIncludeOnce('inc/header.php');
2356 // Rewrite message for output
2357 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2359 // Better log this message away
2360 if ($F != 'debug_report_bug') logDebugMessage($F, $L, $message);
2362 // Load the message template
2363 loadTemplate('app_die_message', false, $message);
2366 loadIncludeOnce('inc/footer.php');
2368 // Script tried to kill itself twice
2369 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2373 // Display parsing time and number of SQL queries in footer
2374 function displayParsingTime() {
2375 // Is the timer started?
2376 if (!isset($GLOBALS['startTime'])) {
2382 $endTime = microtime(true);
2384 // "Explode" both times
2385 $start = explode(' ', $GLOBALS['startTime']);
2386 $end = explode(' ', $endTime);
2387 $runTime = $end[0] - $start[0];
2388 if ($runTime < 0) $runTime = '0';
2392 'runtime' => translateComma($runTime),
2393 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2396 // Load the template
2397 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
2400 // Check wether a boolean constant is set
2401 // Taken from user comments in PHP documentation for function constant()
2402 function isBooleanConstantAndTrue ($constName) { // : Boolean
2403 // Failed by default
2407 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2409 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-CACHE!<br />");
2410 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2413 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-RESOLVE!<br />");
2414 if (defined($constName)) {
2416 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-FOUND!<br />");
2417 $res = (constant($constName) === true);
2421 $GLOBALS['cache_array']['const'][$constName] = $res;
2423 //* DEBUG: */ var_dump($res);
2429 // Checks if a given apache module is loaded
2430 function isApacheModuleLoaded ($apacheModule) {
2431 // Check it and return result
2432 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2435 // Get current theme name
2436 function getCurrentTheme () {
2437 // The default theme is 'default'... ;-)
2440 // Do we have ext-theme installed and active?
2441 if (isExtensionActive('theme')) {
2442 // Call inner method
2443 $ret = getActualTheme();
2446 // Return theme value
2450 // Generates an error code from given account status
2451 function generateErrorCodeFromUserStatus ($status='') {
2452 // If no status is provided, use the default, cached
2453 if ((empty($status)) && (isMember())) {
2455 $status = getUserData('status');
2458 // Default error code if unknown account status
2459 $errorCode = getCode('UNKNOWN_STATUS');
2461 // Generate constant name
2462 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2464 // Is the constant there?
2465 if (isCodeSet($codeName)) {
2467 $errorCode = getCode($codeName);
2470 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2473 // Return error code
2477 // Back-ported from the new ship-simu engine. :-)
2478 function debug_get_printable_backtrace () {
2480 $backtrace = "<ol>\n";
2482 // Get and prepare backtrace for output
2483 $backtraceArray = debug_backtrace();
2484 foreach ($backtraceArray as $key => $trace) {
2485 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2486 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2487 if (!isset($trace['args'])) $trace['args'] = array();
2488 $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";
2492 $backtrace .= "</ol>\n";
2494 // Return the backtrace
2498 // A mail-able backtrace
2499 function debug_get_mailable_backtrace () {
2503 // Get and prepare backtrace for output
2504 $backtraceArray = debug_backtrace();
2505 foreach ($backtraceArray as $key => $trace) {
2506 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2507 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2508 if (!isset($trace['args'])) $trace['args'] = array();
2509 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2512 // Return the backtrace
2516 // Output a debug backtrace to the user
2517 function debug_report_bug ($message = '', $sendEmail = true) {
2518 // Is this already called?
2519 if (isset($GLOBALS[__FUNCTION__])) {
2521 print 'Message:'.$message.'<br />Backtrace:<pre>';
2522 debug_print_backtrace();
2526 // Set this function as called
2527 $GLOBALS[__FUNCTION__] = true;
2532 // Is the optional message set?
2533 if (!empty($message)) {
2535 $debug = sprintf("Note: %s<br />\n",
2539 // @TODO Add a little more infos here
2540 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2544 $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>";
2545 $debug .= debug_get_printable_backtrace();
2546 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2547 $debug .= "Thank you for finding bugs.";
2549 // Send an email? (e.g. not wanted for evaluation errors)
2550 if (($sendEmail === true) && (!isInstallationPhase())) {
2553 'message' => trim($message),
2554 'backtrace' => trim(debug_get_mailable_backtrace())
2557 // Send email to webmaster
2558 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2562 app_die(__FUNCTION__, __LINE__, $debug);
2565 // Generates a ***weak*** seed
2566 function generateSeed () {
2567 return microtime(true) * 100000;
2570 // Converts a message code to a human-readable message
2571 function getMessageFromErrorCode ($code) {
2575 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2576 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2577 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2578 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2579 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2580 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2581 case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2582 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2583 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2584 case getCode('ACCOUNT_LOCKED') : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2585 case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2586 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2587 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2588 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2589 case getCode('MODULE_MEM_ONLY') : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestParameter('mod')); break;
2590 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2591 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2592 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2593 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestParameter('blist'), 0); break;
2594 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2595 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2596 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2597 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2598 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2599 case getCode('MORE_RECEIVERS3') : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
2600 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2601 case getCode('NO_MAIL_TYPE') : $message = getMessage('MEMBER_NO_MAIL_TYPE_SELECTED'); break;
2602 case getCode('UNKNOWN_ERROR') : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
2603 case getCode('UNKNOWN_STATUS') : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
2605 case getCode('ERROR_MAILID'):
2606 if (isExtensionActive('mailid', true)) {
2607 $message = getMessage('ERROR_CONFIRMING_MAIL');
2609 $message = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'mailid');
2613 case getCode('EXTENSION_PROBLEM'):
2614 if (isGetRequestParameterSet('ext')) {
2615 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
2617 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2621 case getCode('URL_TLOCK'):
2622 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2623 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2624 array(bigintval(getRequestParameter('id'))), __FILE__, __LINE__);
2626 // Load timestamp from last order
2627 list($timestamp) = SQL_FETCHROW($result);
2630 SQL_FREERESULT($result);
2632 // Translate it for templates
2633 $timestamp = generateDateTime($timestamp, 1);
2635 // Calculate hours...
2636 $STD = round(getConfig('url_tlock') / 60 / 60);
2639 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2642 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2644 // Finally contruct the message
2645 // @TODO Rewrite this old lost code to a template
2646 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2647 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2648 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2652 // Missing/invalid code
2653 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2656 logDebugMessage(__FUNCTION__, __LINE__, $message);
2660 // Return the message
2664 // Compile characters which are allowed in URLs
2665 function compileUriCode ($code, $simple = true) {
2666 // Compile constants
2667 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2669 // Compile QUOT and other non-HTML codes
2670 $code = str_replace('{DOT}', '.',
2671 str_replace('{SLASH}', '/',
2672 str_replace('{QUOT}', "'",
2673 str_replace('{DOLLAR}', '$',
2674 str_replace('{OPEN_ANCHOR}', '(',
2675 str_replace('{CLOSE_ANCHOR}', ')',
2676 str_replace('{OPEN_SQR}', '[',
2677 str_replace('{CLOSE_SQR}', ']',
2678 str_replace('{PER}', '%',
2682 // Return compiled code
2686 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2687 function isUrlValidSimple ($url) {
2689 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2691 // Allows http and https
2692 $http = "(http|https)+(:\/\/)";
2694 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2695 // Test double-domains (e.g. .de.vu)
2696 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2698 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2700 $dir = "((/)+([-_\.[:alnum:]])+)*";
2702 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2703 // ... and the string after and including question character
2704 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2705 // Pattern for URLs like http://url/dir/doc.html?var=value
2706 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2707 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2708 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2709 // Pattern for URLs like http://url/dir/?var=value
2710 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2711 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2712 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2713 // Pattern for URLs like http://url/dir/page.ext
2714 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2715 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2716 $pattern['ipdp'] = $http . $ip . $dir . $page;
2717 // Pattern for URLs like http://url/dir
2718 $pattern['d1d'] = $http . $domain1 . $dir;
2719 $pattern['d2d'] = $http . $domain2 . $dir;
2720 $pattern['ipd'] = $http . $ip . $dir;
2721 // Pattern for URLs like http://url/?var=value
2722 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2723 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2724 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2725 // Pattern for URLs like http://url?var=value
2726 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2727 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2728 $pattern['ipg12'] = $http . $ip . $getstring1;
2730 // Test all patterns
2732 foreach ($pattern as $key => $pat) {
2734 if (isDebugRegularExpressionEnabled()) {
2735 // @TODO Are these convertions still required?
2736 $pat = str_replace('.', "\.", $pat);
2737 $pat = str_replace('@', "\@", $pat);
2738 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2741 // Check if expression matches
2742 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
2745 if ($reg === true) break;
2748 // Return true/false
2752 // Wtites data to a config.php-style file
2753 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2754 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2755 // Initialize some variables
2761 // Is the file there and read-/write-able?
2762 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2763 $search = 'CFG: ' . $comment;
2764 $tmp = $FQFN . '.tmp';
2766 // Open the source file
2767 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2769 // Is the resource valid?
2770 if (is_resource($fp)) {
2771 // Open temporary file
2772 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2774 // Is the resource again valid?
2775 if (is_resource($fp_tmp)) {
2776 // Mark temporary file as readable
2777 $GLOBALS['file_readable'][$tmp] = true;
2780 while (!feof($fp)) {
2781 // Read from source file
2782 $line = fgets ($fp, 1024);
2784 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2787 if ($next === $seek) {
2789 $line = $prefix . $DATA . $suffix . "\n";
2795 // Write to temp file
2796 fwrite($fp_tmp, $line);
2802 // Finished writing tmp file
2806 // Close source file
2809 if (($done === true) && ($found === true)) {
2810 // Copy back tmp file and delete tmp :-)
2811 copyFileVerified($tmp, $FQFN, 0644);
2812 return removeFile($tmp);
2813 } elseif ($found === false) {
2814 outputHtml('<strong>CHANGE:</strong> 404!');
2816 outputHtml('<strong>TMP:</strong> UNDONE!');
2820 // File not found, not readable or writeable
2821 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2824 // An error was detected!
2827 // Send notification to admin
2828 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2829 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2831 sendAdminsEmails($subject, $templateName, $content, $userid);
2833 // Send out out-dated way
2834 $message = loadEmailTemplate($templateName, $content, $userid);
2835 sendAdminEmails($subject, $message);
2839 // Debug message logger
2840 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2841 // Is debug mode enabled?
2842 if ((isDebugModeEnabled()) || ($force === true)) {
2844 $message = str_replace("\r", '', str_replace("\n", '', $message));
2846 // Log this message away, we better don't call app_die() here to prevent an endless loop
2847 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2848 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2853 // Handle extra values
2854 function handleExtraValues ($filterFunction, $value, $extraValue) {
2855 // Default is the value itself
2858 // Do we have a special filter function?
2859 if (!empty($filterFunction)) {
2860 // Does the filter function exist?
2861 if (function_exists($filterFunction)) {
2862 // Do we have extra parameters here?
2863 if (!empty($extraValue)) {
2864 // Put both parameters in one new array by default
2865 $args = array($value, $extraValue);
2867 // If we have an array simply use it and pre-extend it with our value
2868 if (is_array($extraValue)) {
2869 // Make the new args array
2870 $args = merge_array(array($value), $extraValue);
2873 // Call the multi-parameter call-back
2874 $ret = call_user_func_array($filterFunction, $args);
2876 // One parameter call
2877 $ret = call_user_func($filterFunction, $value);
2886 // Converts timestamp selections into a timestamp
2887 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2888 // Init test variable
2892 // Get last three chars
2893 $test = substr($id, -3);
2895 // Improved way of checking! :-)
2896 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2897 // Found a multi-selection for timings?
2898 $test = substr($id, 0, -3);
2899 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)) {
2900 // Generate timestamp
2901 $postData[$test] = createTimestampFromSelections($test, $postData);
2902 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2903 $GLOBALS['skip_config'][$test] = true;
2905 // Remove data from array
2906 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2907 unset($postData[$test . '_' . $rem]);
2918 // Reverts the german decimal comma into Computer decimal dot
2919 function convertCommaToDot ($str) {
2920 // Default float is not a float... ;-)
2923 // Which language is selected?
2924 switch (getLanguage()) {
2925 case 'de': // German language
2926 // Remove german thousand dots first
2927 $str = str_replace('.', '', $str);
2929 // Replace german commata with decimal dot and cast it
2930 $float = (float)str_replace(',', '.', $str);
2933 default: // US and so on
2934 // Remove thousand dots first and cast
2935 $float = (float)str_replace(',', '', $str);
2943 // Handle menu-depending failed logins and return the rendered content
2944 function handleLoginFailures ($accessLevel) {
2945 // Default output is empty ;-)
2948 // Is the session data set?
2949 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
2950 // Ignore zero values
2951 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
2952 // Non-guest has login failures found, get both data and prepare it for template
2953 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "accessLevel={$accessLevel}<br />");
2955 'login_failures' => getSession('mailer_' . $accessLevel . '_failures'),
2956 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
2960 $OUT = loadTemplate('login_failures', true, $content);
2963 // Reset session data
2964 setSession('mailer_' . $accessLevel . '_failures', '');
2965 setSession('mailer_' . $accessLevel . '_last_failure', '');
2968 // Return rendered content
2973 function rebuildCache ($cache, $inc = '', $force = false) {
2975 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
2977 // Shall I remove the cache file?
2978 if (isCacheInstanceValid()) {
2980 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2982 $GLOBALS['cache_instance']->removeCacheFile($force);
2985 // Include file given?
2988 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
2990 // Is the include there?
2991 if (isIncludeReadable($inc)) {
2992 // And rebuild it from scratch
2993 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
2996 // Include not found!
2997 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3003 // Determines the real remote address
3004 function determineRealRemoteAddress () {
3005 // Is a proxy in use?
3006 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3008 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3009 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3010 // Yet, another proxy
3011 $address = $_SERVER['HTTP_CLIENT_IP'];
3013 // The regular address when no proxy was used
3014 $address = $_SERVER['REMOTE_ADDR'];
3017 // This strips out the real address from proxy output
3018 if (strstr($address, ',')) {
3019 $addressArray = explode(',', $address);
3020 $address = $addressArray[0];
3023 // Return the result
3027 // Adds a bonus mail to the queue
3028 // This is a high-level function!
3029 function addNewBonusMail ($data, $mode = '', $output=true) {
3030 // Use mode from data if not set and availble ;-)
3031 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3033 // Generate receiver list
3034 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3037 if (!empty($receiver)) {
3038 // Add bonus mail to queue
3039 addBonusMailToQueue(
3051 // Mail inserted into bonus pool
3052 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3053 } elseif ($output) {
3054 // More entered than can be reached!
3055 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3058 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3062 // Determines referal id and sets it
3063 function determineReferalId () {
3064 // Skip this in non-html-mode and outside ref.php
3065 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3067 // Check if refid is set
3068 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3070 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3071 // The variable user comes from the click-counter script click.php and we only accept this here
3072 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
3073 } elseif (isPostRequestParameterSet('refid')) {
3074 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3075 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
3076 } elseif (isGetRequestParameterSet('refid')) {
3077 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3078 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
3079 } elseif (isGetRequestParameterSet('ref')) {
3080 // Set refid=ref (the referal link uses such variable)
3081 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
3082 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3083 // Set session refid als global
3084 $GLOBALS['refid'] = bigintval(getSession('refid'));
3085 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3086 // Select a random user which has confirmed enougth mails
3087 $GLOBALS['refid'] = determineRandomReferalId();
3088 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (getConfig('def_refid') > 0)) {
3089 // Set default refid as refid in URL
3090 $GLOBALS['refid'] = getConfig('def_refid');
3092 // No default id when sql_patches is not installed or none set
3093 $GLOBALS['refid'] = '0';
3096 // Set cookie when default refid > 0
3097 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3098 // Default is not found
3101 // Do we have nickname or userid set?
3102 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3103 // Nickname in URL, so load the id
3104 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3105 } elseif ($GLOBALS['refid'] > 0) {
3106 // Direct userid entered
3107 $found = fetchUserData($GLOBALS['refid']);
3110 // Is the record valid?
3111 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3112 // No, then reset referal id
3113 $GLOBALS['refid'] = getConfig('def_refid');
3117 setSession('refid', $GLOBALS['refid']);
3120 // Return determined refid
3121 return $GLOBALS['refid'];
3124 // Enables the reset mode and runs it
3125 function doReset () {
3126 // Enable the reset mode
3127 $GLOBALS['reset_enabled'] = true;
3130 runFilterChain('reset');
3133 // Our shutdown-function
3134 function shutdown () {
3135 // Call the filter chain 'shutdown'
3136 runFilterChain('shutdown', null);
3138 // Check if not in installation phase and the link is up
3139 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
3141 SQL_CLOSE(__FILE__, __LINE__);
3142 } elseif (!isInstallationPhase()) {
3144 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3147 // Stop executing here
3152 function initMemberId () {
3153 $GLOBALS['member_id'] = '0';
3156 // Setter for member id
3157 function setMemberId ($memberid) {
3158 // We should not set member id to zero
3159 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3162 $GLOBALS['member_id'] = bigintval($memberid);
3165 // Getter for member id or returns zero
3166 function getMemberId () {
3167 // Default member id
3170 // Is the member id set?
3171 if (isMemberIdSet()) {
3173 $memberid = $GLOBALS['member_id'];
3180 // Checks ether the member id is set
3181 function isMemberIdSet () {
3182 return (isset($GLOBALS['member_id']));
3185 // Handle message codes from URL
3186 function handleCodeMessage () {
3187 if (isGetRequestParameterSet('code')) {
3188 // Default extension is 'unknown'
3191 // Is extension given?
3192 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
3194 // Convert the 'code' parameter from URL to a human-readable message
3195 $message = getMessageFromErrorCode(getRequestParameter('code'));
3197 // Load message template
3198 loadTemplate('message', false, $message);
3202 // Setter for extra title
3203 function setExtraTitle ($extraTitle) {
3204 $GLOBALS['extra_title'] = $extraTitle;
3207 // Getter for extra title
3208 function getExtraTitle () {
3209 // Is the extra title set?
3210 if (!isExtraTitleSet()) {
3211 // No, then abort here
3212 debug_report_bug('extra_title is not set!');
3216 return $GLOBALS['extra_title'];
3219 // Checks if the extra title is set
3220 function isExtraTitleSet () {
3221 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3224 // Generates a 'extension foo inactive' message
3225 function generateExtensionInactiveMessage ($ext_name) {
3226 // Is the extension empty?
3227 if (empty($ext_name)) {
3228 // This should not happen
3229 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3233 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3235 // Is an admin logged in?
3237 // Then output admin message
3238 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3241 // Return prepared message
3245 // Generates a 'extension foo not installed' message
3246 function generateExtensionNotInstalledMessage ($ext_name) {
3247 // Is the extension empty?
3248 if (empty($ext_name)) {
3249 // This should not happen
3250 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3254 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3256 // Is an admin logged in?
3258 // Then output admin message
3259 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3262 // Return prepared message
3266 // Generates a message depending on if the extension is not installed or not
3268 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3272 // Is the extension not installed or just deactivated?
3273 switch (isExtensionInstalled($ext_name)) {
3274 case true; // Deactivated!
3275 $message = generateExtensionInactiveMessage($ext_name);
3278 case false; // Not installed!
3279 $message = generateExtensionNotInstalledMessage($ext_name);
3282 default: // Should not happen!
3283 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3284 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3288 // Return the message
3292 // Reads a directory recursively by default and searches for files not matching
3293 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3294 // a whole directory.
3295 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3296 // Add default entries we should exclude
3297 $excludeArray[] = '.';
3298 $excludeArray[] = '..';
3299 $excludeArray[] = '.svn';
3300 $excludeArray[] = '.htaccess';
3302 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3307 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3310 while ($baseFile = readdir($dirPointer)) {
3311 // Exclude '.', '..' and entries in $excludeArray automatically
3312 if (in_array($baseFile, $excludeArray, true)) {
3314 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3318 // Construct include filename and FQFN
3319 $fileName = $baseDir . $baseFile;
3320 $FQFN = getConfig('PATH') . $fileName;
3322 // Remove double slashes
3323 $FQFN = str_replace('//', '/', $FQFN);
3325 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3326 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3327 // These Lines are only for debugging!!
3328 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3329 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3330 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3336 // Skip also files with non-matching prefix genericly
3337 if (($recursive === true) && (isDirectory($FQFN))) {
3338 // Is a redirectory so read it as well
3339 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3341 // And skip further processing
3343 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3345 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3347 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3348 // Skip wrong suffix as well
3349 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3351 } elseif (!isFileReadable($FQFN)) {
3352 // Not readable so skip it
3353 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3357 // Is the file a PHP script or other?
3358 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3359 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3360 // Is this a valid include file?
3361 if ($extension == '.php') {
3362 // Remove both for extension name
3363 $extName = substr($baseFile, strlen($prefix), -4);
3365 // Is the extension valid and active?
3366 if (isExtensionNameValid($extName)) {
3367 // Then add this file
3368 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3369 $files[] = $fileName;
3371 // Add non-extension files as well
3372 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3373 if ($addBaseDir === true) {
3374 $files[] = $fileName;
3376 $files[] = $baseFile;
3380 // We found .php file but should not search for them, why?
3381 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3383 } elseif (substr($baseFile, -4, 4) == $extension) {
3384 // Other, generic file found
3385 $files[] = $fileName;
3390 closedir($dirPointer);
3395 // Return array with include files
3396 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3400 // Maps a module name into a database table name
3401 function mapModuleToTable ($moduleName) {
3402 // Map only these, still lame code...
3403 switch ($moduleName) {
3404 // 'index' is the guest's menu
3405 case 'index': $moduleName = 'guest'; break;
3406 // ... and 'login' the member's menu
3407 case 'login': $moduleName = 'member'; break;
3408 // Anything else will not be mapped, silently.
3415 // Add SQL debug data to array for later output
3416 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3417 // Already executed?
3418 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3419 // Then abort here, we don't need to profile a query twice
3423 // Remeber this as profiled (or not, but we don't care here)
3424 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3426 // Do we have cache?
3427 if (!isset($GLOBALS['debug_sql_available'])) {
3428 // Check it and cache it in $GLOBALS
3429 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3432 // Don't execute anything here if we don't need or ext-other is missing
3433 if ($GLOBALS['debug_sql_available'] === false) {
3439 'num_rows' => SQL_NUMROWS($result),
3440 'affected' => SQL_AFFECTEDROWS(),
3441 'sql_str' => $sqlString,
3442 'timing' => $timing,
3443 'file' => basename($F),
3448 $GLOBALS['debug_sqls'][] = $record;
3451 // Initializes the cache instance
3452 function initCacheInstance () {
3453 // Load include for CacheSystem class
3454 loadIncludeOnce('inc/classes/cachesystem.class.php');
3456 // Initialize cache system only when it's needed
3457 $GLOBALS['cache_instance'] = new CacheSystem();
3458 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3459 // Failed to initialize cache sustem
3460 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3464 // Getter for message from array or raw message
3465 function getMessageFromIndexedArray ($message, $pos, $array) {
3466 // Check if the requested message was found in array
3467 if (isset($array[$pos])) {
3468 // ... if yes then use it!
3469 $ret = $array[$pos];
3471 // ... else use default message
3479 // Print code with line numbers
3480 function linenumberCode ($code) {
3481 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3482 $count_lines = count($codeE);
3484 $r = 'Line | Code:<br />';
3485 foreach($codeE as $line => $c) {
3486 $r .= '<div class="line"><span class="linenum">';
3487 if ($count_lines == 1) {
3490 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3495 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3498 return '<div class="code">' . $r . '</div>';
3501 // Convert ';' to ', ' for e.g. receiver list
3502 function convertReceivers ($old) {
3503 return str_replace(';', ', ', $old);
3506 // Determines the right page title
3507 function determinePageTitle () {
3508 // Config and database connection valid?
3509 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3513 // Title decoration enabled?
3514 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3516 // Do we have some extra title?
3517 if (isExtraTitleSet()) {
3519 $TITLE .= getExtraTitle() . ' by ';
3523 $TITLE .= getConfig('MAIN_TITLE');
3525 // Add title of module? (middle decoration will also be added!)
3526 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3527 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3530 // Add title from what file
3532 if (getModule() == 'login') $mode = 'member';
3533 elseif (getModule() == 'index') $mode = 'guest';
3534 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3536 // Add title decorations? (right)
3537 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3539 // Remember title in constant for the template
3540 $pageTitle = $TITLE;
3541 } elseif ((isInstalled()) && (isAdminRegistered())) {
3542 // Installed, admin registered but no ext-sql_patches
3543 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3544 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3545 // Installed but no admin registered
3546 $pageTitle = getMessage('SETUP_OF_MXCHANGE');
3547 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3548 // Installation mode
3549 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3551 // Configuration not found!
3552 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3554 // Do not add the fatal message in installation mode
3555 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3559 return decodeEntities($pageTitle);
3562 // Checks wethere there is a cache file there. This function is cached.
3563 function isTemplateCached ($template) {
3564 // Do we have cached this result?
3565 if (!isset($GLOBALS['template_cache'][$template])) {
3567 $FQFN = generateCacheFqfn($template);
3570 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3574 return $GLOBALS['template_cache'][$template];
3577 // Flushes non-flushed template cache to disk
3578 function flushTemplateCache ($template, $eval) {
3579 // Is this cache flushed?
3580 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3582 $FQFN = generateCacheFqfn($template);
3584 // Replace username with a call
3585 $eval = str_replace('$username', '".getUsername()."', $eval);
3588 writeToFile($FQFN, $eval, true);
3592 // Reads a template cache
3593 function readTemplateCache ($template) {
3595 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3597 $FQFN = generateCacheFqfn($template);
3600 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3604 return $GLOBALS['template_eval'][$template];
3607 // Escapes quotes (default is only double-quotes)
3608 function escapeQuotes ($str, $single = false) {
3609 // Should we escape all?
3610 if ($single === true) {
3611 // Escape all (including null)
3612 $str = addslashes($str);
3614 // Escape only double-quotes but prevent double-quoting
3615 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3618 // Return the escaped string
3622 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3623 function escapeJavaScriptQuotes ($str) {
3624 // Replace all double-quotes and secure back-ticks
3625 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3631 // Send out mails depending on the 'mod/modes' combination
3632 // @TODO Lame description for this function
3633 function sendModeMails ($mod, $modes) {
3635 if (fetchUserData(getMemberId())) {
3636 // Extract salt from cookie
3637 $salt = substr(getSession('u_hash'), 0, -40);
3639 // Now let's compare passwords
3640 $hash = encodeHashForCookie(getUserData('password'));
3642 // Does the hash match or should we change it?
3643 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
3645 $content = getUserDataArray();
3648 $content['gender'] = translateGender($content['gender']);
3650 // Clear/init the content variable
3651 $content['message'] = '';
3654 // @TODO Move this in a filter
3657 foreach ($modes as $mode) {
3659 case 'normal': break; // Do not add any special lines
3660 case 'email': // Email was changed!
3661 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestParameter('old_email')."\n";
3664 case 'pass': // Password was changed
3665 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3669 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3670 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3675 if (isExtensionActive('country')) {
3676 // Replace code with description
3677 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
3680 // Merge content with data from POST
3681 $content = merge_array($content, postRequestArray());
3684 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3686 if (getConfig('admin_notify') == 'Y') {
3687 // The admin needs to be notified about a profile change
3688 $message_admin = 'admin_mydata_notify';
3689 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3692 $message_admin = '';
3696 // Set subject lines
3697 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3699 // Output success message
3700 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3703 default: // Unsupported module!
3704 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3705 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
3709 // Passwords mismatch
3710 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
3713 // Could not load profile
3714 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
3717 // Send email to user if required
3718 if ((!empty($sub_mem)) && (!empty($message))) {
3720 sendEmail($content['email'], $sub_mem, $message);
3723 // Send only if no other error has occured
3724 if (empty($content)) {
3725 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3727 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3728 } elseif (getConfig('admin_notify') == 'Y') {
3729 // Cannot send mails to admin!
3730 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3733 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3738 loadTemplate('admin_settings_saved', false, $content);
3741 // Generates a 'selection box' from given array
3742 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent='') {
3744 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3745 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3747 // Walk through all options
3748 foreach ($options as $option) {
3749 // Add the <option> entry
3750 if (empty($optionContent)) {
3751 // ... from template
3752 $OUT .= loadTemplate('select_' . $name . '_option', true, $option);
3755 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3759 // Finish selection box
3760 $OUT .= '</select>';
3764 'selection_box' => $OUT,
3765 'module' => getModule(),
3769 // Load template and return it
3770 return loadTemplate('select_' . $name . '_box', true, $content);
3773 // Get a module from filename and access level
3774 function getModuleFromFileName ($file, $accessLevel) {
3775 // Default is 'invalid';
3776 $modCheck = 'invalid';
3778 // @TODO This is still very static, rewrite it somehow
3779 switch ($accessLevel) {
3781 $modCheck = 'admin';
3787 $modCheck = getModule();
3790 default: // Unsupported file name / access level
3791 debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3799 // Encodes an URL for adding session id, etc.
3800 function encodeUrl ($url, $outputMode = '0') {
3801 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
3802 if ((strpos($url, session_name()) !== false) || (getOutputMode() == -3)) return $url;
3804 // Do we have a valid session?
3805 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3807 // Determine right seperator
3808 $seperator = '&';
3809 if (strpos($url, '?') === false) {
3812 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3818 if (session_id() != '') {
3819 $url .= $seperator . session_name() . '=' . session_id();
3824 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3826 $url = '{?URL?}/' . $url;
3833 // Simple check for spider
3834 function isSpider () {
3836 $userAgent = strtolower(detectUserAgent(true));
3838 // It should not be empty, if so it is better a spider/bot
3839 if (empty($userAgent)) return true;
3842 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
3845 // Prepares the header for HTML output
3846 function loadHtmlHeader () {
3848 // 1.) pre_page_header (mainly loads the page_header template and includes
3849 // meta description)
3850 runFilterChain('pre_page_header');
3852 // Here can be something be added, but normally one of the two filters
3853 // around this line should do the job for you.
3855 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
3856 // to close the head-tag)
3857 // Include more header data here
3858 runFilterChain('post_page_header');
3861 // Adds page header and footer to output array element
3862 function addPageHeaderFooter () {
3866 // Add them all together. This is maybe to simple
3867 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
3868 // Add page part if set
3869 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
3872 // Transfer $OUT to 'output'
3873 $GLOBALS['output'] = $OUT;
3876 // Generates meta description for current module and 'what' value
3877 function generateMetaDescriptionCode () {
3878 // Only include from guest area
3879 if (getModule() == 'index') {
3880 // Construct dynamic description
3881 $DESCR = '{?MAIN_TITLE?} '.trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
3883 // Output it directly
3884 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
3888 unset($GLOBALS['ref_level']);
3891 // Generates an FQFN for template cache from the given template name
3892 function generateCacheFqfn ($template) {
3894 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
3895 // Generate the FQFN
3896 $GLOBALS['template_cache_fqfn'][$template] = sprintf("%s_compiled/html/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3900 return $GLOBALS['template_cache_fqfn'][$template];
3903 // Function to search for the last modified file
3904 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
3906 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
3907 // Does it match what we are looking for? (We skip a lot files already!)
3908 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
3909 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
3911 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
3912 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
3914 // Walk through all entries
3915 foreach ($ds as $d) {
3916 // Generate proper FQFN
3917 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir . '/' . $d);
3919 // Is it a file and readable?
3920 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
3921 if (isFileReadable($FQFN)) {
3922 // $FQFN is a readable file so extract the requested data from it
3923 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
3924 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
3926 // Is the file more recent?
3927 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
3928 // This file is newer as the file before
3929 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
3930 $last_changed['path_name'] = $FQFN;
3931 $last_changed[$lookFor] = $check;
3935 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
3940 // "Fixes" null or empty string to count of dashes
3941 function fixNullEmptyToDashes ($str, $num) {
3942 // Use str as default
3946 if ((is_null($str)) || (trim($str) == '')) {
3948 $return = str_repeat('-', $num);
3951 // Return final string
3955 // Handles the braces [] of a field (e.g. value of 'name' attribute)
3956 function handleFieldWithBraces ($field) {
3957 // Are there braces [] at the end?
3958 if (substr($field, -2, 2) == '[]') {
3959 // Try to find one and replace it. I do it this way to allow easy
3960 // extending of this code.
3961 foreach (array('admin_list_builder_id_value') as $key) {
3962 // Is the cache entry set?
3963 if (isset($GLOBALS[$key])) {
3965 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
3977 //////////////////////////////////////////////////
3978 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3979 //////////////////////////////////////////////////
3981 if (!function_exists('html_entity_decode')) {
3982 // Taken from documentation on www.php.net
3983 function html_entity_decode ($string) {
3984 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3985 $trans_tbl = array_flip($trans_tbl);
3986 return strtr($string, $trans_tbl);
3990 if (!function_exists('http_build_query')) {
3991 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
3992 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
3994 foreach ((array)$data as $k => $v) {
3995 if (is_int($k) && $prefix != null) {
3996 $k = urlencode($prefix . $k);
3999 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
4001 if (is_array($v) || is_object($v)) {
4002 array_push($ret, http_build_query($v, '', $sep, $k));
4004 array_push($ret, $k.'='.urlencode($v));
4008 if (empty($sep)) $sep = ini_get('arg_separator.output');
4010 return implode($sep, $ret);