2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/25/2003 *
4 * =================== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
46 function outputHtml ($htmlCode, $newLine = true) {
48 if (!isset($GLOBALS['output'])) {
49 $GLOBALS['output'] = '';
52 // Do we have HTML-Code here?
53 if (!empty($htmlCode)) {
54 // Yes, so we handle it as you have configured
55 switch (getConfig('OUTPUT_MODE')) {
57 // That's why you don't need any \n at the end of your HTML code... :-)
58 if (getPhpCaching() == 'on') {
59 // Output into PHP's internal buffer
60 outputRawCode($htmlCode);
62 // That's why you don't need any \n at the end of your HTML code... :-)
63 if ($newLine === true) print("\n");
65 // Render mode for old or lame servers...
66 $GLOBALS['output'] .= $htmlCode;
68 // That's why you don't need any \n at the end of your HTML code... :-)
69 if ($newLine === true) $GLOBALS['output'] .= "\n";
74 // If we are switching from render to direct output rendered code
75 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
77 // The same as above... ^
78 outputRawCode($htmlCode);
79 if ($newLine === true) print("\n");
83 // Huh, something goes wrong or maybe you have edited config.php ???
84 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
87 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
88 // Output cached HTML code
89 $GLOBALS['output'] = ob_get_contents();
91 // Clear output buffer for later output if output is found
92 if (!empty($GLOBALS['output'])) {
96 // Send all HTTP headers
99 // Compile and run finished rendered HTML code
100 compileFinalOutput();
102 // Output code here, DO NOT REMOVE! ;-)
103 outputRawCode($GLOBALS['output']);
104 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
105 // Send all HTTP headers
108 // Compile and run finished rendered HTML code
109 compileFinalOutput();
111 // Output code here, DO NOT REMOVE! ;-)
112 outputRawCode($GLOBALS['output']);
114 // And flush all headers
119 // Sends out all headers required for HTTP/1.1 reply
120 function sendHttpHeaders () {
122 $now = gmdate('D, d M Y H:i:s') . ' GMT';
125 sendHeader('HTTP/1.1 ' . getHttpStatus());
127 // General headers for no caching
128 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
129 sendHeader('Last-Modified: ' . $now);
130 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
131 sendHeader('Pragma: no-cache'); // HTTP/1.0
132 sendHeader('Connection: Close');
133 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
134 sendHeader('Content-Language: ' . getLanguage());
137 // Compiles the final output
138 function compileFinalOutput () {
142 // Add page header and footer
143 addPageHeaderFooter();
146 while (((strpos($GLOBALS['output'], '{--') !== false) || (strpos($GLOBALS['output'], '{DQUOTE}') !== false) || (strpos($GLOBALS['output'], '{!') !== false) || (strpos($GLOBALS['output'], '{?') !== false) || (strpos($GLOBALS['output'], '{%') !== false)) && ($cnt < 3)) {
147 // Init common variables
152 //* DEBUG: */ print '<pre>'.htmlentities($GLOBALS['output']).'</pre>';
153 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($GLOBALS['output']))) . '";';
154 //* DEBUG: */ die('<pre>'.htmlentities($eval).'</pre>');
156 //* DEBUG: */ die('<pre>'.htmlentities($newContent).'</pre>');
158 // Was that eval okay?
159 if (empty($newContent)) {
160 // Something went wrong!
161 debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
165 $GLOBALS['output'] = $newContent;
171 // Extension 'rewrite' installed?
172 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
173 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
177 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
178 // Compress it for HTTP gzip
179 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
182 sendHeader('Content-Encoding: gzip');
183 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
184 // Compress it for HTTP deflate
185 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
188 sendHeader('Content-Encoding: deflate');
192 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
198 // Output the raw HTML code
199 function outputRawCode ($htmlCode) {
200 // Output stripped HTML code to avoid broken JavaScript code, etc.
201 print(str_replace('{BACK}', "\\", $htmlCode));
203 // Flush the output if only getPhpCaching() is not 'on'
204 if (getPhpCaching() != 'on') {
210 // Init fatal message array
211 function initFatalMessages () {
212 $GLOBALS['fatal_messages'] = array();
215 // Getter for whole fatal error messages
216 function getFatalArray () {
217 return $GLOBALS['fatal_messages'];
220 // Add a fatal error message to the queue array
221 function addFatalMessage ($F, $L, $message, $extra = '') {
222 if (is_array($extra)) {
223 // Multiple extras for a message with masks
224 $message = call_user_func_array('sprintf', $extra);
225 } elseif (!empty($extra)) {
226 // $message is text with a mask plus extras to insert into the text
227 $message = sprintf($message, $extra);
230 // Add message to $GLOBALS['fatal_messages']
231 $GLOBALS['fatal_messages'][] = $message;
233 // Log fatal messages away
234 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
237 // Getter for total fatal message count
238 function getTotalFatalErrors () {
242 // Do we have at least the first entry?
243 if (!empty($GLOBALS['fatal_messages'][0])) {
245 $count = count($GLOBALS['fatal_messages']);
252 // Load a template file and return it's content (only it's name; do not use ' or ")
253 function loadTemplate ($template, $return = false, $content = array()) {
254 // @TODO Remove this sanity-check if all is fine
255 if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
257 // @TODO Try to rewrite all $DATA to $content
261 if (isTemplateCached($template)) {
262 // Evaluate the cache
263 eval(readTemplateCache($template));
264 } elseif (!isset($GLOBALS['template_eval'][$template])) {
265 // Make all template names lowercase
266 $template = strtolower($template);
270 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
273 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
274 $extraPath = detectExtraTemplatePath($template);;
276 ////////////////////////
277 // Generate file name //
278 ////////////////////////
279 $FQFN = $basePath . $extraPath . $template . '.tpl';
281 // Does the special template exists?
282 if (!isFileReadable($FQFN)) {
283 // Reset to default template
284 $FQFN = $basePath . $template . '.tpl';
287 // Now does the final template exists?
288 if (isFileReadable($FQFN)) {
289 // Count the template load
290 incrementConfigEntry('num_templates');
292 // The local file does exists so we load it. :)
293 $GLOBALS['tpl_content'] = readFromFile($FQFN);
295 // Do we have to compile the code?
297 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)) {
298 // Normal HTML output?
299 if (getOutputMode() == '0') {
300 // Add surrounding HTML comments to help finding bugs faster
301 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
303 // Prepare eval() command
304 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
305 } elseif (substr($template, 0, 3) == 'js_') {
306 // JavaScripts don't like entities and timings
307 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
309 // Prepare eval() command, other output doesn't like entities, maybe
310 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
313 // Add surrounding HTML comments to help finding bugs faster
314 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
315 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
318 // Cache the eval() command here
319 $GLOBALS['template_eval'][$template] = $eval;
320 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
321 // Only admins shall see this warning or when installation mode is active
322 $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
323 (' . $template . ')<br />
325 {--TEMPLATE_CONTENT--}
326 <pre>' . print_r($content, true) . '</pre>
328 <pre>' . print_r($DATA, true) . '</pre>
332 $GLOBALS['template_eval'][$template] = '404';
337 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
339 eval($GLOBALS['template_eval'][$template]);
342 // Do we have some content to output or return?
344 // Not empty so let's put it out! ;)
345 if ($return === true) {
346 // Return the HTML code
352 } elseif (isDebugModeEnabled()) {
353 // Warning, empty output!
354 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
358 // Detects the extra template path from given template name
359 function detectExtraTemplatePath ($template) {
364 if (!isset($GLOBALS['extra_path'][$template])) {
365 // Check for admin/guest/member/etc. templates
366 if (substr($template, 0, 6) == 'admin_') {
367 // Admin template found
368 $extraPath = 'admin/';
369 } elseif (substr($template, 0, 6) == 'guest_') {
370 // Guest template found
371 $extraPath = 'guest/';
372 } elseif (substr($template, 0, 7) == 'member_') {
373 // Member template found
374 $extraPath = 'member/';
375 } elseif (substr($template, 0, 7) == 'select_') {
376 // Selection template found
377 $extraPath = 'select/';
378 } elseif (substr($template, 0, 8) == 'install_') {
379 // Installation template found
380 $extraPath = 'install/';
381 } elseif (substr($template, 0, 4) == 'ext_') {
382 // Extension template found
384 } elseif (substr($template, 0, 3) == 'la_') {
385 // 'Logical-area' template found
387 } elseif (substr($template, 0, 3) == 'js_') {
388 // JavaScript template found
390 } elseif (substr($template, 0, 5) == 'menu_') {
391 // Menu template found
392 $extraPath = 'menu/';
394 // Test for extension
395 $test = substr($template, 0, strpos($template, '_'));
397 // Probe for valid extension name
398 if (isExtensionNameValid($test)) {
399 // Set extra path to extension's name
400 $extraPath = $test . '/';
405 $GLOBALS['extra_path'][$template] = $extraPath;
409 return $GLOBALS['extra_path'][$template];
412 // Loads an email template and compiles it
413 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
416 // Make sure all template names are lowercase!
417 $template = strtolower($template);
419 // Default 'nickname' if extension is not installed
422 // Neutral email address is default
423 $email = getConfig('WEBMASTER');
425 // Is content an array?
426 if (is_array($content)) {
427 // Add expiration to array
428 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
429 // Will never expire!
430 $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
431 } elseif (isConfigEntrySet('auto_purge')) {
432 // Create nice date string
433 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
436 $content['expiration'] = getMessage('MAIL_NO_CONFIG_AUTO_PURGE');
441 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content).'<br />');
442 if (($userid > 0) && (is_array($content))) {
443 // If nickname extension is installed, fetch nickname as well
444 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
445 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
447 fetchUserData($userid, 'nickname');
449 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
451 fetchUserData($userid);
454 // Merge data if valid
455 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
456 if (isUserDataValid()) {
457 $content = merge_array($content, getUserDataArray());
459 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
462 // Translate M to male or F to female if present
463 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
465 // Overwrite email from data if present
466 if (isset($content['email'])) $email = $content['email'];
468 // Store email for some functions in global $DATA array
469 // @TODO Do only use $content, not $DATA or raw variables
470 $DATA['email'] = $email;
473 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
476 $extraPath = detectExtraTemplatePath($template);
478 // Generate full FQFN
479 $FQFN = $basePath . $extraPath . $template . '.tpl';
481 // Does the special template exists?
482 if (!isFileReadable($FQFN)) {
483 // Reset to default template
484 $FQFN = $basePath . $template . '.tpl';
487 // Now does the final template exists?
489 if (isFileReadable($FQFN)) {
490 // The local file does exists so we load it. :)
491 $GLOBALS['tpl_content'] = readFromFile($FQFN);
494 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
495 eval($GLOBALS['tpl_content']);
496 } elseif (!empty($template)) {
497 // Template file not found!
498 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
499 {--TEMPLATE_CONTENT--}
500 <pre>' . print_r($content, true) . '</pre>
502 <pre>' . print_r($DATA, true) . '</pre>
505 // Debug mode not active? Then remove the HTML tags
506 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
508 // No template name supplied!
509 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
512 // Is there some content?
513 if (empty($newContent)) {
515 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
517 // Add last error if the required function exists
518 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
521 // Remove content and data
529 // Send mail out to an email address
530 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
531 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail},SUBJECT={$subject}<br />");
533 // Compile subject line (for POINTS constant etc.)
534 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
537 if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
538 // Value detected, is the message extension installed?
539 // @TODO Extension 'msg' does not exist
540 if (isExtensionActive('msg')) {
541 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
544 // Does the user exist?
545 if (fetchUserData($toEmail)) {
547 $toEmail = getUserData('email');
550 $toEmail = getConfig('WEBMASTER');
553 } elseif ($toEmail == '0') {
555 $toEmail = getConfig('WEBMASTER');
557 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
559 // Check for PHPMailer or debug-mode
560 if (!checkPhpMailerUsage()) {
561 // Not in PHPMailer-Mode
562 if (empty($mailHeader)) {
563 // Load email header template
564 $mailHeader = loadEmailTemplate('header');
567 $mailHeader .= loadEmailTemplate('header');
569 } elseif (isDebugModeEnabled()) {
570 if (empty($mailHeader)) {
571 // Load email header template
572 $mailHeader = loadEmailTemplate('header');
575 $mailHeader .= loadEmailTemplate('header');
580 eval('$toEmail = "' . compileRawCode(escapeQuotes($toEmail)) . '";');
583 eval('$message = "' . str_replace('$', '$', compileRawCode(escapeQuotes($message))) . '";');
585 // Fix HTML parameter (default is no!)
586 if (empty($isHtml)) $isHtml = 'N';
587 if (isDebugModeEnabled()) {
588 // In debug mode we want to display the mail instead of sending it away so we can debug this part
590 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
591 To : ' . htmlentities(utf8_decode($toEmail)) . '
592 Subject : ' . htmlentities(utf8_decode($subject)) . '
593 Message : ' . htmlentities(utf8_decode($message)) . '
595 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
596 // Send mail as HTML away
597 return sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
598 } elseif (!empty($toEmail)) {
600 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
601 } elseif ($isHtml != 'Y') {
603 return sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
607 // Check to use wether legacy mail() command or PHPMailer class
608 // @TODO Rewrite this to an extension 'smtp'
610 function checkPhpMailerUsage() {
611 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
614 // Send out a raw email with PHPMailer class or legacy mail() command
615 function sendRawEmail ($toEmail, $subject, $message, $from) {
616 // Just compile all again, to put out all configs, etc.
617 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
618 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
619 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
620 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
622 // Shall we use PHPMailer class or legacy mode?
623 if (checkPhpMailerUsage()) {
624 // Use PHPMailer class with SMTP enabled
625 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
626 loadIncludeOnce('inc/phpmailer/class.smtp.php');
629 $mail = new PHPMailer();
631 // Set charset to UTF-8
632 $mail->CharSet = 'UTF-8';
634 // Path for PHPMailer
635 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
638 $mail->SMTPAuth = true;
639 $mail->Host = getConfig('SMTP_HOSTNAME');
641 $mail->Username = getConfig('SMTP_USER');
642 $mail->Password = getConfig('SMTP_PASSWORD');
644 $mail->From = getConfig('WEBMASTER');
648 $mail->FromName = getConfig('MAIN_TITLE');
649 $mail->Subject = $subject;
650 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
651 $mail->Body = $message;
652 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
653 $mail->WordWrap = 70;
656 $mail->Body = decodeEntities($message);
658 $mail->AddAddress($toEmail, '');
659 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
660 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
661 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
664 // Has an error occured?
665 if (!empty($mail->ErrorInfo)) {
667 logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
676 // Use legacy mail() command
677 return mail($toEmail, $subject, decodeEntities($message), $from);
681 // Generate a password in a specified length or use default password length
682 function generatePassword ($length = '0') {
683 // Auto-fix invalid length of zero
684 if ($length == '0') $length = getConfig('pass_len');
686 // Initialize array with all allowed chars
687 $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,-,+,_,/,.');
689 // Start creating password
691 for ($i = '0'; $i < $length; $i++) {
692 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
695 // When the size is below 40 we can also add additional security by scrambling
696 // it. Otherwise we may corrupt hashes
697 if (strlen($PASS) <= 40) {
698 // Also scramble the password
699 $PASS = scrambleString($PASS);
702 // Return the password
706 // Generates a human-readable timestamp from the Uni* stamp
707 function generateDateTime ($time, $mode = '0') {
708 // Filter out numbers
709 $time = bigintval($time);
711 // If the stamp is zero it mostly didn't "happen"
714 return getMessage('NEVER_HAPPENED');
717 switch (getLanguage()) {
718 case 'de': // German date / time format
720 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
721 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
722 case '2': $ret = date('d.m.Y|H:i', $time); break;
723 case '3': $ret = date('d.m.Y', $time); break;
725 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
730 default: // Default is the US date / time format!
732 case '0': $ret = date('r', $time); break;
733 case '1': $ret = date('Y-m-d - g:i A', $time); break;
734 case '2': $ret = date('y-m-d|H:i', $time); break;
735 case '3': $ret = date('y-m-d', $time); break;
737 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
746 // Translates Y/N to yes/no
747 function translateYesNo ($yn) {
749 $translated = '??? (' . $yn . ')';
751 case 'Y': $translated = getMessage('YES'); break;
752 case 'N': $translated = getMessage('NO'); break;
755 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
763 // Translates the "pool type" into human-readable
764 function translatePoolType ($type) {
765 // Default?type is unknown
766 $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
769 $constName = sprintf("POOL_TYPE_%s", $type);
772 if (isMessageIdValid($constName)) {
774 $translated = getMessage($constName);
777 // Return "translation"
781 // Translates the american decimal dot into a german comma
782 function translateComma ($dotted, $cut = true, $max = '0') {
783 // First, cast all to double, due to PHP changes
784 $dotted = (double) $dotted;
786 // Default is 3 you can change this in admin area "Misc -> Misc Options"
787 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
789 // Use from config is default
790 $maxComma = getConfig('max_comma');
792 // Use from parameter?
793 if ($max > 0) $maxComma = $max;
796 if (($cut === true) && ($max == '0')) {
797 // Test for commata if in cut-mode
798 $com = explode('.', $dotted);
799 if (count($com) < 2) {
800 // Don't display commatas even if there are none... ;-)
806 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
809 switch (getLanguage()) {
810 case 'de': // German language
811 $dotted = number_format($dotted, $maxComma, ',', '.');
814 default: // All others
815 $dotted = number_format($dotted, $maxComma, '.', ',');
819 // Return translated value
823 // Translate Uni*-like gender to human-readable
824 function translateGender ($gender) {
826 $ret = '!' . $gender . '!';
828 // Male/female or company?
830 case 'M': $ret = getMessage('GENDER_M'); break;
831 case 'F': $ret = getMessage('GENDER_F'); break;
832 case 'C': $ret = getMessage('GENDER_C'); break;
834 // Please report bugs on unknown genders
835 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
839 // Return translated gender
843 // "Translates" the user status
844 function translateUserStatus ($status) {
845 // Generate message depending on status
850 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
855 $ret = getMessage('ACCOUNT_DELETED');
859 // Please report all unknown status
860 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
868 // "Translates" 'visible' and 'locked' to a CSS class
869 function translateMenuVisibleLocked ($content, $prefix = '') {
870 // Translate 'visible' and keep an eye on the prefix
871 switch ($content[$prefix . 'visible']) {
873 case 'Y': $content[$prefix . 'visible_css'] = $prefix . 'menu_visible' ; break;
874 case 'N': $content[$prefix . 'visible_css'] = $prefix . 'menu_invisible'; break;
876 // Please report this
877 debug_report_bug('Unsupported visible value detected. content=<pre>'.print_r($content, true).'</pre>');
881 // Translate 'locked' and keep an eye on the prefix
882 switch ($content[$prefix . 'locked']) {
884 case 'Y': $content[$prefix . 'locked_css'] = $prefix . 'menu_locked' ; break;
885 case 'N': $content[$prefix . 'locked_css'] = $prefix . 'menu_unlocked'; break;
887 // Please report this
888 debug_report_bug('Unsupported locked value detected. content=<pre>'.print_r($content, true).'</pre>');
892 // Return the resulting array
896 // Generates an URL for the dereferer
897 function generateDerefererUrl ($URL) {
898 // Don't de-refer our own links!
899 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
900 // De-refer this link
901 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
908 // Generates an URL for the frametester
909 function generateFrametesterUrl ($URL) {
910 // Prepare frametester URL
911 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
912 encodeString(compileUriCode($URL))
915 // Return the new URL
916 return $frametesterUrl;
919 // Count entries from e.g. a selection box
920 function countSelection ($array) {
922 if (!is_array($array)) {
924 debug_report_bug(__FUNCTION__.': No array provided.');
931 foreach ($array as $key => $selected) {
933 if (!empty($selected)) $ret++;
936 // Return counted selections
940 // Generate XHTML code for the CAPTCHA
941 function generateCaptchaCode ($code, $type, $DATA, $userid) {
942 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
945 // Generates a timestamp (some wrapper for mktime())
946 function makeTime ($hours, $minutes, $seconds, $stamp) {
947 // Extract day, month and year from given timestamp
948 $days = date('d', $stamp);
949 $months = date('m', $stamp);
950 $years = date('Y', $stamp);
952 // Create timestamp for wished time which depends on extracted date
963 // Redirects to an URL and if neccessarry extends it with own base URL
964 function redirectToUrl ($URL, $allowSpider = true) {
966 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
968 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
969 $rel = ' rel="external"';
971 // Do we have internal or external URL?
972 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
973 // Own (=internal) URL
977 // Three different ways to debug...
978 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
979 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
980 //* DEBUG: */ die($URL);
982 // Simple probe for bots/spiders from search engines
983 if ((isSpider()) && ($allowSpider === true)) {
984 // Secure the URL against bad things such als HTML insertions and so on...
985 $URL = secureString($URL);
987 // Set content-type here to fix a missing array element
988 setContentType('text/html');
990 // Output new location link as anchor
991 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
992 } elseif (!headers_sent()) {
993 // Clear own output buffer
994 $GLOBALS['output'] = '';
997 setHttpStatus('302 Found');
999 // Load URL when headers are not sent
1000 sendHeader('Location: '.str_replace('&', '&', $URL));
1002 // Output error message
1003 loadInclude('inc/header.php');
1004 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
1005 loadInclude('inc/footer.php');
1008 // Shut the mailer down here
1012 // Wrapper for redirectToUrl but URL comes from a configuration entry
1013 function redirectToConfiguredUrl ($configEntry) {
1015 $URL = getConfig($configEntry);
1018 if (is_null($URL)) {
1020 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Configuration entry %s is not set!", $configEntry));
1024 redirectToUrl($URL);
1027 // Compiles the given HTML/mail code
1028 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1029 // Is the code a string?
1030 if (!is_string($code)) {
1031 // Silently return it
1036 $startCompile = microtime(true);
1039 $code = compileRawCode($code, $simple, $constants, $full);
1042 $compiled = microtime(true);
1045 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1047 // Return compiled code
1051 // Compiles the code (use compileCode() only for HTML because of the comments)
1052 // @TODO $simple is deprecated
1053 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1054 // Is the code a string?
1055 if (!is_string($code)) {
1056 // Silently return it
1060 // Init replacement-array with smaller set of security characters
1061 $secChars = $GLOBALS['url_chars'];
1063 // Select full set of chars to replace when we e.g. want to compile URLs
1064 if ($full === true) $secChars = $GLOBALS['security_chars'];
1066 // Compile more through a filter
1067 $code = runFilterChain('compile_code', $code);
1069 // Compile constants
1070 if ($constants === true) {
1071 // BEFORE 0.2.1 : Language and data constants
1072 // WITH 0.2.1+ : Only language constants
1073 $code = str_replace('{--', "{DQUOTE} . getMessage('", str_replace('--}', "') . {DQUOTE}", $code));
1075 // BEFORE 0.2.1 : Not used
1076 // WITH 0.2.1+ : Data constants
1077 $code = str_replace('{!', "{DQUOTE} . constant('", str_replace('!}', "') . {DQUOTE}", $code));
1080 // Compile QUOT and other non-HTML codes
1081 foreach ($secChars['to'] as $k => $to) {
1082 // Do the reversed thing as in inc/libs/security_functions.php
1083 $code = str_replace($to, $secChars['from'][$k], $code);
1086 // Find $content[bla][blub] entries
1087 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1088 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1090 // Are some matches found?
1091 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1092 // Replace all matches
1093 $matchesFound = array();
1094 foreach ($matches[0] as $key => $match) {
1095 // Fuzzy look has failed by default
1096 $fuzzyFound = false;
1098 // Fuzzy look on match if already found
1099 foreach ($matchesFound as $found => $set) {
1101 $test = substr($found, 0, strlen($match));
1103 // Does this entry exist?
1104 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
1105 if ($test == $match) {
1107 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
1114 if ($fuzzyFound === true) continue;
1116 // Take all string elements
1117 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1118 // Replace it in the code
1119 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
1120 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1121 $code = str_replace($match, '".' . $newMatch . '."', $code);
1122 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1123 $matchesFound[$match] = 1;
1124 } elseif (!isset($matchesFound[$match])) {
1125 // Not yet replaced!
1126 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
1127 $code = str_replace($match, '".' . $match . '."', $code);
1128 $matchesFound[$match] = 1;
1137 /************************************************************************
1139 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1140 * $a_sort sortiert: *
1142 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1143 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1144 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1145 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1146 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1148 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1149 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1150 * Sie, dass es doch nicht so schwer ist! :-) *
1152 ************************************************************************/
1153 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1155 while ($primary_key < count($a_sort)) {
1156 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1157 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1159 if ($nums === false) {
1160 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1161 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1162 } elseif ($key != $key2) {
1163 // Sort numbers (E.g.: 9 < 10)
1164 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1165 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1169 // We have found two different values, so let's sort whole array
1170 foreach ($dummy as $sort_key => $sort_val) {
1171 $t = $dummy[$sort_key][$key];
1172 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1173 $dummy[$sort_key][$key2] = $t;
1184 // Write back sorted array
1189 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1192 if ($type == 'yn') {
1193 // This is a yes/no selection only!
1194 if ($id > 0) $prefix .= '[' . $id . ']';
1195 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
1197 // Begin with regular selection box here
1198 if (!empty($prefix)) $prefix .= "_";
1200 if ($id > 0) $type2 .= '[' . $id . ']';
1201 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
1206 for ($idx = 1; $idx < 32; $idx++) {
1207 $OUT .= '<option value="' . $idx . '"';
1208 if ($default == $idx) $OUT .= ' selected="selected"';
1209 $OUT .= '>' . $idx . '</option>';
1213 case 'month': // Month
1214 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
1215 $OUT .= '<option value="' . $idx . '"';
1216 if ($default == $idx) $OUT .= ' selected="selected"';
1217 $OUT .= '>' . $descr . '</option>';
1221 case 'year': // Year
1223 $year = date('Y', time());
1225 // Use configured min age or fixed?
1226 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1228 $startYear = $year - getConfig('min_age');
1231 $startYear = $year - 16;
1234 // Calculate earliest year (100 years old people can still enter Internet???)
1235 $minYear = $year - 100;
1237 // Check if the default value is larger than minimum and bigger than actual year
1238 if (($default > $minYear) && ($default >= $year)) {
1239 for ($idx = $year; $idx < ($year + 11); $idx++) {
1240 $OUT .= '<option value="' . $idx . '"';
1241 if ($default == $idx) $OUT .= ' selected="selected"';
1242 $OUT .= '>' . $idx . '</option>';
1244 } elseif ($default == -1) {
1245 // Current year minus 1
1246 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
1247 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
1250 // Get current year and subtract the configured minimum age
1251 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
1252 // Calculate earliest year depending on extension version
1253 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1254 // Use configured minimum age
1255 $year = date('Y', time()) - getConfig('min_age');
1257 // Use fixed 16 years age
1258 $year = date('Y', time()) - 16;
1261 // Construct year selection list
1262 for ($idx = $minYear; $idx <= $year; $idx++) {
1263 $OUT .= '<option value="' . $idx . '"';
1264 if ($default == $idx) $OUT .= ' selected="selected"';
1265 $OUT .= '>' . $idx . '</option>';
1272 for ($idx = 0; $idx < 60; $idx+=5) {
1273 if (strlen($idx) == 1) $idx = '0' . $idx;
1274 $OUT .= '<option value="' . $idx . '"';
1275 if ($default == $idx) $OUT .= ' selected="selected"';
1276 $OUT .= '>' . $idx . '</option>';
1281 for ($idx = 0; $idx < 24; $idx++) {
1282 if (strlen($idx) == 1) $idx = '0' . $idx;
1283 $OUT .= '<option value="' . $idx . '"';
1284 if ($default == $idx) $OUT .= ' selected="selected"';
1285 $OUT .= '>' . $idx . '</option>';
1290 $OUT .= '<option value="Y"';
1291 if ($default == 'Y') $OUT .= ' selected="selected"';
1292 $OUT .= '>{--YES--}</option><option value="N"';
1293 if ($default != 'Y') $OUT .= ' selected="selected"';
1294 $OUT .= '>{--NO--}</option>';
1297 $OUT .= '</select>';
1302 // Deprecated : $length
1305 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1306 // Build server string
1307 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
1310 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1311 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1312 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1313 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1314 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1316 // Build string from misc data
1317 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1319 // Add more additional data
1320 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1322 // Add referal id, language, theme and userid
1323 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1324 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1325 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1326 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1328 // Calculate number for generating the code
1329 $a = $code + getConfig('_ADD') - 1;
1331 if (isConfigEntrySet('master_salt')) {
1332 // Generate hash with master salt from modula of number with the prime number and other data
1333 $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'));
1335 // Create number from hash
1336 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1338 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1339 $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')));
1341 // Create number from hash
1342 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1345 // At least 10 numbers shall be secure enought!
1346 $len = getConfig('code_length');
1347 if ($len == '0') $len = $length;
1348 if ($len == '0') $len = 10;
1350 // Cut off requested counts of number
1351 $return = substr(str_replace('.', '', $rcode), 0, $len);
1353 // Done building code
1357 // Does only allow numbers
1358 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
1359 // Filter all numbers out
1360 $ret = preg_replace('/[^0123456789]/', '', $num);
1363 if ($castValue === true) $ret = (double)$ret;
1365 // Has the whole value changed?
1366 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
1368 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret=' . $ret . ', num='. $num);
1375 // Insert the code in $img_code into jpeg or PNG image
1376 function generateImageOrCode ($img_code, $headerSent = true) {
1377 // Is the code size oversized or shouldn't we display it?
1378 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1379 // Stop execution of function here because of over-sized code length
1380 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1381 } elseif ($headerSent === false) {
1382 // Return an HTML code here
1383 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
1387 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1390 getConfig('img_type')
1394 if (isFileReadable($img)) {
1395 // Switch image type
1396 switch (getConfig('img_type')) {
1398 // Okay, load image and hide all errors
1399 $image = imagecreatefromjpeg($img);
1403 // Okay, load image and hide all errors
1404 $image = imagecreatefrompng($img);
1408 // Exit function here
1409 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1413 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1414 $text_color = imagecolorallocate($image, 0, 0, 0);
1416 // Insert code into image
1417 imagestring($image, 5, 14, 2, $img_code, $text_color);
1419 // Return to browser
1420 sendHeader('Content-Type: image/' . getConfig('img_type'));
1422 // Output image with matching image factory
1423 switch (getConfig('img_type')) {
1424 case 'jpg': imagejpeg($image); break;
1425 case 'png': imagepng($image); break;
1428 // Remove image from memory
1429 imagedestroy($image);
1431 // Create selection box or array of splitted timestamp
1432 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1433 // Do not continue if ONE_DAY is absend
1434 if (!isConfigEntrySet('ONE_DAY')) {
1435 // And return the timestamp itself or empty array
1436 if ($return_array === true) {
1443 // Calculate 2-seconds timestamp
1444 $stamp = round($timestamp);
1445 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1447 // Do we have a leap year?
1449 $TEST = date('Y', time()) / 4;
1450 $M1 = date('m', time());
1451 $M2 = date('m', (time() + $timestamp));
1453 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1454 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1456 // First of all years...
1457 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1458 //* DEBUG: */ print("Y={$Y}<br />");
1460 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1461 //* DEBUG: */ print("M={$M}<br />");
1463 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1464 //* DEBUG: */ print("W={$W}<br />");
1466 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1467 //* DEBUG: */ print("D={$D}<br />");
1469 $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));
1470 //* DEBUG: */ print("h={$h}<br />");
1472 $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));
1473 //* DEBUG: */ print("m={$m}<br />");
1474 // And at last seconds...
1475 $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));
1476 //* DEBUG: */ print("s={$s}<br />");
1478 // Is seconds zero and time is < 60 seconds?
1479 if (($s == '0') && ($timestamp < 60)) {
1481 $s = round($timestamp);
1485 // Now we convert them in seconds...
1487 if ($return_array) {
1488 // Just put all data in an array for later use
1500 $OUT = '<div align="' . $align . '">';
1501 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1504 if (isInString('Y', $display) || (empty($display))) {
1505 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
1508 if (isInString('M', $display) || (empty($display))) {
1509 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
1512 if (isInString('W', $display) || (empty($display))) {
1513 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
1516 if (isInString('D', $display) || (empty($display))) {
1517 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
1520 if (isInString('h', $display) || (empty($display))) {
1521 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
1524 if (isInString('m', $display) || (empty($display))) {
1525 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
1528 if (isInString('s', $display) || (empty($display))) {
1529 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
1535 if (isInString('Y', $display) || (empty($display))) {
1536 // Generate year selection
1537 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
1538 for ($idx = 0; $idx <= 10; $idx++) {
1539 $OUT .= '<option class="mini_select" value="' . $idx . '"';
1540 if ($idx == $Y) $OUT .= ' selected="selected"';
1541 $OUT .= '>' . $idx . '</option>';
1543 $OUT .= '</select></td>';
1545 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1548 if (isInString('M', $display) || (empty($display))) {
1549 // Generate month selection
1550 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
1551 for ($idx = 0; $idx <= 11; $idx++) {
1552 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1553 if ($idx == $M) $OUT .= ' selected="selected"';
1554 $OUT .= '>' . $idx . '</option>';
1556 $OUT .= '</select></td>';
1558 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1561 if (isInString('W', $display) || (empty($display))) {
1562 // Generate week selection
1563 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
1564 for ($idx = 0; $idx <= 4; $idx++) {
1565 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1566 if ($idx == $W) $OUT .= ' selected="selected"';
1567 $OUT .= '>' . $idx . '</option>';
1569 $OUT .= '</select></td>';
1571 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1574 if (isInString('D', $display) || (empty($display))) {
1575 // Generate day selection
1576 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
1577 for ($idx = 0; $idx <= 31; $idx++) {
1578 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1579 if ($idx == $D) $OUT .= ' selected="selected"';
1580 $OUT .= '>' . $idx . '</option>';
1582 $OUT .= '</select></td>';
1584 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1587 if (isInString('h', $display) || (empty($display))) {
1588 // Generate hour selection
1589 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1590 for ($idx = 0; $idx <= 23; $idx++) {
1591 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1592 if ($idx == $h) $OUT .= ' selected="selected"';
1593 $OUT .= '>' . $idx . '</option>';
1595 $OUT .= '</select></td>';
1597 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1600 if (isInString('m', $display) || (empty($display))) {
1601 // Generate minute selection
1602 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1603 for ($idx = 0; $idx <= 59; $idx++) {
1604 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1605 if ($idx == $m) $OUT .= ' selected="selected"';
1606 $OUT .= '>' . $idx . '</option>';
1608 $OUT .= '</select></td>';
1610 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1613 if (isInString('s', $display) || (empty($display))) {
1614 // Generate second selection
1615 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1616 for ($idx = 0; $idx <= 59; $idx++) {
1617 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1618 if ($idx == $s) $OUT .= ' selected="selected"';
1619 $OUT .= '>' . $idx . '</option>';
1621 $OUT .= '</select></td>';
1623 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1630 // Return generated HTML code
1635 function createTimestampFromSelections ($prefix, $postData) {
1636 // Initial return value
1639 // Do we have a leap year?
1641 $TEST = date('Y', time()) / 4;
1642 $M1 = date('m', time());
1644 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1645 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
1647 // First add years...
1648 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1651 $ret += $postData[$prefix . '_mo'] * 2628000;
1654 $ret += $postData[$prefix . '_we'] * 604800;
1657 $ret += $postData[$prefix . '_da'] * 86400;
1660 $ret += $postData[$prefix . '_ho'] * 3600;
1663 $ret += $postData[$prefix . '_mi'] * 60;
1665 // And at last seconds...
1666 $ret += $postData[$prefix . '_se'];
1668 // Return calculated value
1672 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1673 function createFancyTime ($stamp) {
1674 // Get data array with years/months/weeks/days/...
1675 $data = createTimeSelections($stamp, '', '', '', true);
1677 foreach($data as $k => $v) {
1679 // Value is greater than 0 "eval" data to return string
1680 eval('$ret .= ", ".$v." {--_' . strtoupper($k) . '--}";');
1685 // Do we have something there?
1686 if (strlen($ret) > 0) {
1687 // Remove leading commata and space
1688 $ret = substr($ret, 2);
1691 $ret = '0 {--_SECONDS--}';
1694 // Return fancy time string
1698 // Generates a navigation row for listing emails
1699 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1701 if ($show_form === false) {
1706 for ($page = 1; $page <= $PAGES; $page++) {
1707 // Is the page currently selected or shall we generate a link to it?
1708 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1709 // Is currently selected, so only highlight it
1710 $NAV .= '<strong>-';
1712 // Open anchor tag and add base URL
1713 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1715 // Add userid when we shall show all mails from a single member
1716 if ((isGetRequestParameterSet('userid')) && (bigintval(getRequestParameter('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestParameter('userid'));
1718 // Close open anchor tag
1722 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1723 // Is currently selected, so only highlight it
1724 $NAV .= '-</strong>';
1730 // Add seperator if we have not yet reached total pages
1731 if ($page < $PAGES) {
1737 // Define constants only once
1738 $content['nav'] = $NAV;
1739 $content['span'] = $colspan;
1740 $content['top'] = $TOP;
1742 // Load navigation template
1743 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1745 if ($return === true) {
1746 // Return generated HTML-Code
1754 // Extract host from script name
1755 function extractHostnameFromUrl (&$script) {
1756 // Use default SERVER_URL by default... ;) So?
1757 $url = getConfig('SERVER_URL');
1759 // Is this URL valid?
1760 if (substr($script, 0, 7) == 'http://') {
1761 // Use the hostname from script URL as new hostname
1762 $url = substr($script, 7);
1763 $extract = explode('/', $url);
1765 // Done extracting the URL :)
1768 // Extract host name
1769 $host = str_replace('http://', '', $url);
1770 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1772 // Generate relative URL
1773 //* DEBUG: */ print('SCRIPT=' . $script.'<br />');
1774 if (substr(strtolower($script), 0, 7) == 'http://') {
1775 // But only if http:// is in front!
1776 $script = substr($script, (strlen($url) + 7));
1777 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1779 $script = substr($script, (strlen($url) + 8));
1782 //* DEBUG: */ print('SCRIPT=' . $script.'<br />');
1783 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1789 // Send a GET request
1790 function sendGetRequest ($script, $data = array()) {
1791 // Extract host name from script
1792 $host = extractHostnameFromUrl($script);
1795 $body = http_build_query($data, '', '&');
1797 // Do we have a question-mark in the script?
1798 if (strpos($script, '?') === false) {
1799 // No, so first char must be question mark
1800 $body = '?' . $body;
1803 $body = '&' . $body;
1809 // Remove trailed & to make it more conform
1810 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
1812 // Generate GET request header
1813 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1814 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1815 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1816 if (isConfigEntrySet('FULL_VERSION')) {
1817 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1819 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1821 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
1822 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1823 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
1824 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1825 $request .= getConfig('HTTP_EOL');
1827 // Send the raw request
1828 $response = sendRawRequest($host, $request);
1830 // Return the result to the caller function
1834 // Send a POST request
1835 function sendPostRequest ($script, $postData) {
1836 // Is postData an array?
1837 if (!is_array($postData)) {
1839 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1840 return array('', '', '');
1843 // Extract host name from script
1844 $host = extractHostnameFromUrl($script);
1846 // Construct request body
1847 $body = http_build_query($postData, '', '&');
1849 // Generate POST request header
1850 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
1851 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1852 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1853 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1854 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1855 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1856 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1857 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1858 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
1859 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1860 $request .= getConfig('HTTP_EOL');
1865 // Send the raw request
1866 $response = sendRawRequest($host, $request);
1868 // Return the result to the caller function
1872 // Sends a raw request to another host
1873 function sendRawRequest ($host, $request) {
1874 // Init errno and errdesc with 'all fine' values
1875 $errno = '0'; $errdesc = '';
1878 $response = array('', '', '');
1880 // Default is not to use proxy
1883 // Are proxy settins set?
1884 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1890 loadIncludeOnce('inc/classes/resolver.class.php');
1892 // Get resolver instance
1893 $resolver = new HostnameResolver();
1896 //* DEBUG: */ die('SCRIPT=' . $script.'<br />');
1897 if ($useProxy === true) {
1898 // Resolve hostname into IP address
1899 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
1901 // Connect to host through proxy connection
1902 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1904 // Resolve hostname into IP address
1905 $ip = $resolver->resolveHostname($host);
1907 // Connect to host directly
1908 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
1912 if (!is_resource($fp)) {
1914 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
1916 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
1917 // Cannot set non-blocking mode or timeout
1918 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
1923 if ($useProxy === true) {
1924 // Setup proxy tunnel
1925 $response = setupProxyTunnel($host, $fp);
1927 // If the response is invalid, abort
1928 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
1929 // Invalid response!
1930 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
1936 fwrite($fp, $request);
1939 $start = microtime(true);
1942 while (!feof($fp)) {
1943 // Get info from stream
1944 $info = stream_get_meta_data($fp);
1946 // Is it timed out? 15 seconds is a really patient...
1947 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1949 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1955 // Get line from stream
1956 $line = fgets($fp, 128);
1958 // Ignore empty lines because of non-blocking mode
1960 // uslepp a little to avoid 100% CPU load
1967 // Add it to response
1968 $response[] = trim($line);
1974 // Time request if debug-mode is enabled
1975 if (isDebugModeEnabled()) {
1976 // Add debug message...
1977 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1980 // Skip first empty lines
1982 foreach ($resp as $idx => $line) {
1984 $line = trim($line);
1986 // Is this line empty?
1989 array_shift($response);
1991 // Abort on first non-empty line
1996 //* DEBUG: */ print('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1997 //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1999 // Proxy agent found or something went wrong?
2000 if (!isset($response[0])) {
2001 // No response, maybe timeout
2002 $response = array('', '', '');
2003 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
2004 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
2005 // Proxy header detected, so remove two lines
2006 array_shift($response);
2007 array_shift($response);
2010 // Was the request successfull?
2011 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
2012 // Not found / access forbidden
2013 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
2014 $response = array('', '', '');
2021 // Sets up a proxy tunnel for given hostname and through resource
2022 function setupProxyTunnel ($host, $resource) {
2024 $response = array('', '', '');
2026 // Generate CONNECT request header
2027 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
2028 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
2030 // Use login data to proxy? (username at least!)
2031 if (getConfig('proxy_username') != '') {
2033 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
2034 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
2037 // Add last new-line
2038 $proxyTunnel .= getConfig('HTTP_EOL');
2039 //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
2042 fwrite($fp, $proxyTunnel);
2046 // No response received
2050 // Read the first line
2051 $resp = trim(fgets($fp, 10240));
2052 $respArray = explode(' ', $resp);
2053 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
2054 // Invalid response!
2062 // Taken from www.php.net isInStringIgnoreCase() user comments
2063 function isEmailValid ($email) {
2064 // Check first part of email address
2065 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
2068 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
2071 $regex = '@^' . $first . '\@' . $domain . '$@iU';
2073 // Return check result
2074 return preg_match($regex, $email);
2077 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2078 function isUrlValid ($URL, $compile=true) {
2079 // Trim URL a little
2080 $URL = trim(urldecode($URL));
2081 //* DEBUG: */ outputHtml($URL.'<br />');
2083 // Compile some chars out...
2084 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
2085 //* DEBUG: */ outputHtml($URL.'<br />');
2087 // Check for the extension filter
2088 if (isExtensionActive('filter')) {
2089 // Use the extension's filter set
2090 return FILTER_VALIDATE_URL($URL, false);
2093 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2094 // https:// in front of the URLs
2095 return isUrlValidSimple($URL);
2098 // Generate a list of administrative links to a given userid
2099 function generateMemberAdminActionLinks ($userid, $status = '') {
2100 // Make sure userid is a number
2101 if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
2103 // Define all main targets
2104 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2106 // Begin of navigation links
2109 foreach ($targetArray as $tar) {
2110 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
2111 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
2112 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2113 // Locked accounts shall be unlocked
2114 $OUT .= 'UNLOCK_USER';
2116 // All other status is fine
2117 $OUT .= strtoupper($tar);
2119 $OUT .= '_TITLE--}">{--ADMIN_';
2120 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2121 // Locked accounts shall be unlocked
2122 $OUT .= 'UNLOCK_USER';
2124 // All other status is fine
2125 $OUT .= strtoupper($tar);
2127 $OUT .= '--}</a></span>|';
2130 // Finish navigation link
2131 $OUT = substr($OUT, 0, -7) . ']';
2137 // Generate an email link
2138 function generateEmailLink ($email, $table = 'admins') {
2139 // Default email link (INSECURE! Spammer can read this by harvester programs)
2140 $EMAIL = 'mailto:' . $email;
2142 // Check for several extensions
2143 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2144 // Create email link for contacting admin in guest area
2145 $EMAIL = generateAdminEmailLink($email);
2146 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
2147 // Create email link for contacting a member within admin area (or later in other areas, too?)
2148 $EMAIL = generateUserEmailLink($email, 'admin');
2149 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2150 // Create email link to contact sponsor within admin area (or like the link above?)
2151 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2154 // Shall I close the link when there is no admin?
2155 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2157 // Return email link
2161 // Generate a hash for extra-security for all passwords
2162 function generateHash ($plainText, $salt = '', $hash = true) {
2164 //* DEBUG: */ outputHtml('plainText=' . $plainText . ',salt=' . $salt . ',hash='.intval($hash).'<br />');
2166 // Is the required extension 'sql_patches' there and a salt is not given?
2167 // 0123 4 43 3 4 432 2 3 32 2 3 3210
2168 if ((((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')))) {
2169 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2170 if ($hash === true) {
2171 // Is plain password
2172 return md5($plainText);
2174 // Is already a hash
2179 // Do we miss an arry element here?
2180 if (!isConfigEntrySet('file_hash')) {
2182 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
2185 // When the salt is empty build a new one, else use the first x configured characters as the salt
2187 // Build server string for more entropy
2188 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2191 $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');
2194 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2196 // Calculate number for generating the code
2197 $a = time() + getConfig('_ADD') - 1;
2199 // Generate SHA1 sum from modula of number and the prime number
2200 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2201 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2202 $sha1 = scrambleString($sha1);
2203 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2204 //* DEBUG: */ $sha1b = descrambleString($sha1);
2205 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2207 // Generate the password salt string
2208 $salt = substr($sha1, 0, getConfig('salt_length'));
2209 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2212 //* DEBUG: */ outputHtml('salt=' . $salt . '<br />');
2213 $salt = substr($salt, 0, getConfig('salt_length'));
2214 //* DEBUG: */ outputHtml('salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />');
2216 // Sanity check on salt
2217 if (strlen($salt) != getConfig('salt_length')) {
2219 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2223 // Generate final hash (for debug output)
2224 $finalHash = $salt . sha1($salt . $plainText);
2227 //* DEBUG: */ outputHtml('finalHash=' . $finalHash);
2233 // Scramble a string
2234 function scrambleString($str) {
2238 // Final check, in case of failture it will return unscrambled string
2239 if (strlen($str) > 40) {
2240 // The string is to long
2242 } elseif (strlen($str) == 40) {
2244 $scrambleNums = explode(':', getConfig('pass_scramble'));
2246 // Generate new numbers
2247 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2250 // Compare both lengths and abort if different
2251 if (strlen($str) != count($scrambleNums)) return $str;
2253 // Scramble string here
2254 //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2255 for ($idx = 0; $idx < strlen($str); $idx++) {
2256 // Get char on scrambled position
2257 $char = substr($str, $scrambleNums[$idx], 1);
2259 // Add it to final output string
2260 $scrambled .= $char;
2263 // Return scrambled string
2264 //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2268 // De-scramble a string scrambled by scrambleString()
2269 function descrambleString($str) {
2270 // Scramble only 40 chars long strings
2271 if (strlen($str) != 40) return $str;
2273 // Load numbers from config
2274 $scrambleNums = explode(':', getConfig('pass_scramble'));
2277 if (count($scrambleNums) != 40) return $str;
2279 // Begin descrambling
2280 $orig = str_repeat(' ', 40);
2281 //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2282 for ($idx = 0; $idx < 40; $idx++) {
2283 $char = substr($str, $idx, 1);
2284 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2287 // Return scrambled string
2288 //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2292 // Generated a "string" for scrambling
2293 function genScrambleString ($len) {
2294 // Prepare array for the numbers
2295 $scrambleNumbers = array();
2297 // First we need to setup randomized numbers from 0 to 31
2298 for ($idx = 0; $idx < $len; $idx++) {
2300 $rand = mt_rand(0, ($len -1));
2302 // Check for it by creating more numbers
2303 while (array_key_exists($rand, $scrambleNumbers)) {
2304 $rand = mt_rand(0, ($len -1));
2308 $scrambleNumbers[$rand] = $rand;
2311 // So let's create the string for storing it in database
2312 $scrambleString = implode(':', $scrambleNumbers);
2313 return $scrambleString;
2316 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2317 function encodeHashForCookie ($passHash) {
2318 // Return vanilla password hash
2321 // Is a secret key and master salt already initialized?
2322 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
2323 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2324 // Only calculate when the secret key is generated
2325 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getConfig('secret_key')));
2326 if ((strlen($passHash) != 49) || (strlen(getConfig('secret_key')) != 40)) {
2327 // Both keys must have same length so return unencrypted
2328 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getConfig('secret_key')) . '!=40');
2332 $newHash = ''; $start = 9;
2333 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
2334 for ($idx = 0; $idx < 20; $idx++) {
2335 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getConfig('secret_key'))), 2));
2336 $part2 = hexdec(substr(getConfig('secret_key'), $start, 2));
2337 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
2338 $mod = dechex($idx);
2339 if ($part1 > $part2) {
2340 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2341 } elseif ($part2 > $part1) {
2342 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2344 $mod = substr($mod, 0, 2);
2345 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
2346 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
2347 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
2352 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
2353 $ret = generateHash($newHash, getConfig('master_salt'));
2357 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
2361 // Fix "deleted" cookies
2362 function fixDeletedCookies ($cookies) {
2363 // Is this an array with entries?
2364 if ((is_array($cookies)) && (count($cookies) > 0)) {
2365 // Then check all cookies if they are marked as deleted!
2366 foreach ($cookies as $cookieName) {
2367 // Is the cookie set to "deleted"?
2368 if (getSession($cookieName) == 'deleted') {
2369 setSession($cookieName, '');
2375 // Output error messages in a fasioned way and die...
2376 function app_die ($F, $L, $message) {
2377 // Check if Script is already dieing and not let it kill itself another 1000 times
2378 if (!isset($GLOBALS['app_died'])) {
2379 // Make sure, that the script realy realy diese here and now
2380 $GLOBALS['app_died'] = true;
2382 // Set content type as text/html
2383 setContentType('text/html');
2386 loadIncludeOnce('inc/header.php');
2388 // Rewrite message for output
2389 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
2391 // Load the message template
2392 loadTemplate('app_die_message', false, $message);
2395 loadIncludeOnce('inc/footer.php');
2397 // Script tried to kill itself twice
2398 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2402 // Display parsing time and number of SQL queries in footer
2403 function displayParsingTime () {
2404 // Is the timer started?
2405 if (!isset($GLOBALS['startTime'])) {
2411 $endTime = microtime(true);
2413 // "Explode" both times
2414 $start = explode(' ', $GLOBALS['startTime']);
2415 $end = explode(' ', $endTime);
2416 $runTime = $end[0] - $start[0];
2417 if ($runTime < 0) $runTime = '0';
2420 // @TODO This can be easily moved out after the merge from EL branch to this is complete
2422 'run_time' => $runTime,
2423 'sql_time' => translateComma(getConfig('sql_time') * 1000),
2426 // Load the template
2427 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
2430 // Check wether a boolean constant is set
2431 // Taken from user comments in PHP documentation for function constant()
2432 function isBooleanConstantAndTrue ($constName) { // : Boolean
2433 // Failed by default
2437 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2439 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-CACHE!<br />");
2440 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2443 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-RESOLVE!<br />");
2444 if (defined($constName)) {
2446 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-FOUND!<br />");
2447 $res = (constant($constName) === true);
2451 $GLOBALS['cache_array']['const'][$constName] = $res;
2453 //* DEBUG: */ var_dump($res);
2459 // Checks if a given apache module is loaded
2460 function isApacheModuleLoaded ($apacheModule) {
2461 // Check it and return result
2462 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2465 // Get current theme name
2466 function getCurrentTheme () {
2467 // The default theme is 'default'... ;-)
2470 // Do we have ext-theme installed and active?
2471 if (isExtensionActive('theme')) {
2472 // Call inner method
2473 $ret = getActualTheme();
2476 // Return theme value
2480 // Generates an error code from given account status
2481 function generateErrorCodeFromUserStatus ($status='') {
2482 // If no status is provided, use the default, cached
2483 if ((empty($status)) && (isMember())) {
2485 $status = getUserData('status');
2488 // Default error code if unknown account status
2489 $errorCode = getCode('UNKNOWN_STATUS');
2491 // Generate constant name
2492 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2494 // Is the constant there?
2495 if (isCodeSet($codeName)) {
2497 $errorCode = getCode($codeName);
2500 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2503 // Return error code
2507 // Back-ported from the new ship-simu engine. :-)
2508 function debug_get_printable_backtrace () {
2510 $backtrace = "<ol>\n";
2512 // Get and prepare backtrace for output
2513 $backtraceArray = debug_backtrace();
2514 foreach ($backtraceArray as $key => $trace) {
2515 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2516 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2517 if (!isset($trace['args'])) $trace['args'] = array();
2518 $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";
2522 $backtrace .= "</ol>\n";
2524 // Return the backtrace
2528 // A mail-able backtrace
2529 function debug_get_mailable_backtrace () {
2533 // Get and prepare backtrace for output
2534 $backtraceArray = debug_backtrace();
2535 foreach ($backtraceArray as $key => $trace) {
2536 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2537 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2538 if (!isset($trace['args'])) $trace['args'] = array();
2539 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2542 // Return the backtrace
2546 // Output a debug backtrace to the user
2547 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
2548 // Is this already called?
2549 if (isset($GLOBALS[__FUNCTION__])) {
2551 print 'Message:'.$message.'<br />Backtrace:<pre>';
2552 debug_print_backtrace();
2556 // Set this function as called
2557 $GLOBALS[__FUNCTION__] = true;
2562 // Is the optional message set?
2563 if (!empty($message)) {
2565 $debug = sprintf("Note: %s<br />\n",
2569 // @TODO Add a little more infos here
2570 logDebugMessage($F, $L, strip_tags($message));
2574 $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>";
2575 $debug .= debug_get_printable_backtrace();
2576 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2577 $debug .= "Thank you for finding bugs.";
2579 // Send an email? (e.g. not wanted for evaluation errors)
2580 if (($sendEmail === true) && (!isInstallationPhase())) {
2583 'message' => trim($message),
2584 'backtrace' => trim(debug_get_mailable_backtrace())
2587 // Send email to webmaster
2588 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2592 app_die($F, $L, $debug);
2595 // Generates a ***weak*** seed
2596 function generateSeed () {
2597 return microtime(true) * 100000;
2600 // Converts a message code to a human-readable message
2601 function getMessageFromErrorCode ($code) {
2605 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2606 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2607 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2608 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2609 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2610 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2611 case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2612 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2613 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2614 case getCode('ACCOUNT_LOCKED') : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2615 case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2616 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2617 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2618 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2619 case getCode('MODULE_MEM_ONLY') : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestParameter('mod')); break;
2620 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2621 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2622 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2623 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestParameter('blist'), 0); break;
2624 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2625 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2626 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2627 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2628 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2629 case getCode('MORE_RECEIVERS3') : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
2630 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2631 case getCode('NO_MAIL_TYPE') : $message = getMessage('MEMBER_NO_MAIL_TYPE_SELECTED'); break;
2632 case getCode('UNKNOWN_ERROR') : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
2633 case getCode('UNKNOWN_STATUS') : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
2635 case getCode('ERROR_MAILID'):
2636 if (isExtensionActive('mailid', true)) {
2637 $message = getMessage('ERROR_CONFIRMING_MAIL');
2639 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', 'mailid');
2643 case getCode('EXTENSION_PROBLEM'):
2644 if (isGetRequestParameterSet('ext')) {
2645 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
2647 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2651 case getCode('URL_TLOCK'):
2652 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2653 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2654 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
2656 // Load timestamp from last order
2657 list($timestamp) = SQL_FETCHROW($result);
2660 SQL_FREERESULT($result);
2662 // Translate it for templates
2663 $timestamp = generateDateTime($timestamp, 1);
2665 // Calculate hours...
2666 $STD = round(getConfig('url_tlock') / 60 / 60);
2669 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2672 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2674 // Finally contruct the message
2675 // @TODO Rewrite this old lost code to a template
2676 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2677 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2678 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2682 // Missing/invalid code
2683 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2686 logDebugMessage(__FUNCTION__, __LINE__, $message);
2690 // Return the message
2694 // Compile characters which are allowed in URLs
2695 function compileUriCode ($code, $simple = true) {
2696 // Compile constants
2697 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2699 // Compile QUOT and other non-HTML codes
2700 $code = str_replace('{DOT}', '.',
2701 str_replace('{SLASH}', '/',
2702 str_replace('{QUOT}', "'",
2703 str_replace('{DOLLAR}', '$',
2704 str_replace('{OPEN_ANCHOR}', '(',
2705 str_replace('{CLOSE_ANCHOR}', ')',
2706 str_replace('{OPEN_SQR}', '[',
2707 str_replace('{CLOSE_SQR}', ']',
2708 str_replace('{PER}', '%',
2712 // Return compiled code
2716 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2717 function isUrlValidSimple ($url) {
2719 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2721 // Allows http and https
2722 $http = "(http|https)+(:\/\/)";
2724 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2725 // Test double-domains (e.g. .de.vu)
2726 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2728 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2730 $dir = "((/)+([-_\.[:alnum:]])+)*";
2732 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2733 // ... and the string after and including question character
2734 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2735 // Pattern for URLs like http://url/dir/doc.html?var=value
2736 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2737 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2738 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2739 // Pattern for URLs like http://url/dir/?var=value
2740 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2741 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2742 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2743 // Pattern for URLs like http://url/dir/page.ext
2744 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2745 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2746 $pattern['ipdp'] = $http . $ip . $dir . $page;
2747 // Pattern for URLs like http://url/dir
2748 $pattern['d1d'] = $http . $domain1 . $dir;
2749 $pattern['d2d'] = $http . $domain2 . $dir;
2750 $pattern['ipd'] = $http . $ip . $dir;
2751 // Pattern for URLs like http://url/?var=value
2752 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2753 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2754 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2755 // Pattern for URLs like http://url?var=value
2756 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2757 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2758 $pattern['ipg12'] = $http . $ip . $getstring1;
2760 // Test all patterns
2762 foreach ($pattern as $key => $pat) {
2764 if (isDebugRegularExpressionEnabled()) {
2765 // @TODO Are these convertions still required?
2766 $pat = str_replace('.', "\.", $pat);
2767 $pat = str_replace('@', "\@", $pat);
2768 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2771 // Check if expression matches
2772 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
2775 if ($reg === true) break;
2778 // Return true/false
2782 // Wtites data to a config.php-style file
2783 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2784 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2785 // Initialize some variables
2791 // Is the file there and read-/write-able?
2792 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2793 $search = 'CFG: ' . $comment;
2794 $tmp = $FQFN . '.tmp';
2796 // Open the source file
2797 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2799 // Is the resource valid?
2800 if (is_resource($fp)) {
2801 // Open temporary file
2802 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2804 // Is the resource again valid?
2805 if (is_resource($fp_tmp)) {
2806 // Mark temporary file as readable
2807 $GLOBALS['file_readable'][$tmp] = true;
2810 while (!feof($fp)) {
2811 // Read from source file
2812 $line = fgets ($fp, 1024);
2814 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2817 if ($next === $seek) {
2819 $line = $prefix . $DATA . $suffix . "\n";
2825 // Write to temp file
2826 fwrite($fp_tmp, $line);
2832 // Finished writing tmp file
2836 // Close source file
2839 if (($done === true) && ($found === true)) {
2840 // Copy back tmp file and delete tmp :-)
2841 copyFileVerified($tmp, $FQFN, 0644);
2842 return removeFile($tmp);
2843 } elseif ($found === false) {
2844 outputHtml('<strong>CHANGE:</strong> 404!');
2846 outputHtml('<strong>TMP:</strong> UNDONE!');
2850 // File not found, not readable or writeable
2851 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2854 // An error was detected!
2857 // Send notification to admin
2858 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2859 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2861 sendAdminsEmails($subject, $templateName, $content, $userid);
2863 // Send out out-dated way
2864 $message = loadEmailTemplate($templateName, $content, $userid);
2865 sendAdminEmails($subject, $message);
2869 // Debug message logger
2870 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2871 // Is debug mode enabled?
2872 if ((isDebugModeEnabled()) || ($force === true)) {
2874 $message = str_replace("\r", '', str_replace("\n", '', $message));
2876 // Log this message away
2877 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write logfile debug.log!');
2878 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2883 // Handle extra values
2884 function handleExtraValues ($filterFunction, $value, $extraValue) {
2885 // Default is the value itself
2888 // Do we have a special filter function?
2889 if (!empty($filterFunction)) {
2890 // Does the filter function exist?
2891 if (function_exists($filterFunction)) {
2892 // Do we have extra parameters here?
2893 if (!empty($extraValue)) {
2894 // Put both parameters in one new array by default
2895 $args = array($value, $extraValue);
2897 // If we have an array simply use it and pre-extend it with our value
2898 if (is_array($extraValue)) {
2899 // Make the new args array
2900 $args = merge_array(array($value), $extraValue);
2903 // Call the multi-parameter call-back
2904 $ret = call_user_func_array($filterFunction, $args);
2906 // One parameter call
2907 $ret = call_user_func($filterFunction, $value);
2916 // Converts timestamp selections into a timestamp
2917 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2918 // Init test variable
2922 // Get last three chars
2923 $test = substr($id, -3);
2925 // Improved way of checking! :-)
2926 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2927 // Found a multi-selection for timings?
2928 $test = substr($id, 0, -3);
2929 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)) {
2930 // Generate timestamp
2931 $postData[$test] = createTimestampFromSelections($test, $postData);
2932 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2933 $GLOBALS['skip_config'][$test] = true;
2935 // Remove data from array
2936 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2937 unset($postData[$test . '_' . $rem]);
2948 // Reverts the german decimal comma into Computer decimal dot
2949 function convertCommaToDot ($str) {
2950 // Default float is not a float... ;-)
2953 // Which language is selected?
2954 switch (getLanguage()) {
2955 case 'de': // German language
2956 // Remove german thousand dots first
2957 $str = str_replace('.', '', $str);
2959 // Replace german commata with decimal dot and cast it
2960 $float = (float)str_replace(',', '.', $str);
2963 default: // US and so on
2964 // Remove thousand dots first and cast
2965 $float = (float)str_replace(',', '', $str);
2973 // Handle menu-depending failed logins and return the rendered content
2974 function handleLoginFailures ($accessLevel) {
2975 // Default output is empty ;-)
2978 // Is the session data set?
2979 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
2980 // Ignore zero values
2981 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
2982 // Non-guest has login failures found, get both data and prepare it for template
2983 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "accessLevel={$accessLevel}<br />");
2985 'login_failures' => getSession('mailer_' . $accessLevel . '_failures'),
2986 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
2990 $OUT = loadTemplate('login_failures', true, $content);
2993 // Reset session data
2994 setSession('mailer_' . $accessLevel . '_failures', '');
2995 setSession('mailer_' . $accessLevel . '_last_failure', '');
2998 // Return rendered content
3003 function rebuildCache ($cache, $inc = '', $force = false) {
3005 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3007 // Shall I remove the cache file?
3008 if (isCacheInstanceValid()) {
3010 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3012 $GLOBALS['cache_instance']->removeCacheFile($force);
3015 // Include file given?
3018 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3020 // Is the include there?
3021 if (isIncludeReadable($inc)) {
3022 // And rebuild it from scratch
3023 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
3026 // Include not found!
3027 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3033 // Determines the real remote address
3034 function determineRealRemoteAddress () {
3035 // Is a proxy in use?
3036 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3038 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3039 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3040 // Yet, another proxy
3041 $address = $_SERVER['HTTP_CLIENT_IP'];
3043 // The regular address when no proxy was used
3044 $address = $_SERVER['REMOTE_ADDR'];
3047 // This strips out the real address from proxy output
3048 if (strstr($address, ',')) {
3049 $addressArray = explode(',', $address);
3050 $address = $addressArray[0];
3053 // Return the result
3057 // Adds a bonus mail to the queue
3058 // This is a high-level function!
3059 function addNewBonusMail ($data, $mode = '', $output=true) {
3060 // Use mode from data if not set and availble ;-)
3061 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3063 // Generate receiver list
3064 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3067 if (!empty($receiver)) {
3068 // Add bonus mail to queue
3069 addBonusMailToQueue(
3081 // Mail inserted into bonus pool
3082 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3083 } elseif ($output) {
3084 // More entered than can be reached!
3085 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3088 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3092 // Determines referal id and sets it
3093 function determineReferalId () {
3094 // Skip this in non-html-mode and outside ref.php
3095 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3097 // Check if refid is set
3098 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3100 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3101 // The variable user comes from the click-counter script click.php and we only accept this here
3102 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
3103 } elseif (isPostRequestParameterSet('refid')) {
3104 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3105 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
3106 } elseif (isGetRequestParameterSet('refid')) {
3107 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3108 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
3109 } elseif (isGetRequestParameterSet('ref')) {
3110 // Set refid=ref (the referal link uses such variable)
3111 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
3112 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3113 // Set session refid als global
3114 $GLOBALS['refid'] = bigintval(getSession('refid'));
3115 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3116 // Select a random user which has confirmed enougth mails
3117 $GLOBALS['refid'] = determineRandomReferalId();
3118 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (getConfig('def_refid') > 0)) {
3119 // Set default refid as refid in URL
3120 $GLOBALS['refid'] = getConfig('def_refid');
3122 // No default id when sql_patches is not installed or none set
3123 $GLOBALS['refid'] = '0';
3126 // Set cookie when default refid > 0
3127 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3128 // Default is not found
3131 // Do we have nickname or userid set?
3132 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3133 // Nickname in URL, so load the id
3134 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3135 } elseif ($GLOBALS['refid'] > 0) {
3136 // Direct userid entered
3137 $found = fetchUserData($GLOBALS['refid']);
3140 // Is the record valid?
3141 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3142 // No, then reset referal id
3143 $GLOBALS['refid'] = getConfig('def_refid');
3147 setSession('refid', $GLOBALS['refid']);
3150 // Return determined refid
3151 return $GLOBALS['refid'];
3154 // Enables the reset mode and runs it
3155 function doReset () {
3156 // Enable the reset mode
3157 $GLOBALS['reset_enabled'] = true;
3160 runFilterChain('reset');
3163 // Our shutdown-function
3164 function shutdown () {
3165 // Call the filter chain 'shutdown'
3166 runFilterChain('shutdown', null);
3168 // Check if not in installation phase and the link is up
3169 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
3171 SQL_CLOSE(__FUNCTION__, __LINE__);
3172 } elseif (!isInstallationPhase()) {
3174 addFatalMessage(__FUNCTION__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3177 // Stop executing here
3182 function initMemberId () {
3183 $GLOBALS['member_id'] = '0';
3186 // Setter for member id
3187 function setMemberId ($memberid) {
3188 // We should not set member id to zero
3189 if ($memberid == '0') debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
3192 $GLOBALS['member_id'] = bigintval($memberid);
3195 // Getter for member id or returns zero
3196 function getMemberId () {
3197 // Default member id
3200 // Is the member id set?
3201 if (isMemberIdSet()) {
3203 $memberid = $GLOBALS['member_id'];
3210 // Checks ether the member id is set
3211 function isMemberIdSet () {
3212 return (isset($GLOBALS['member_id']));
3215 // Handle message codes from URL
3216 function handleCodeMessage () {
3217 if (isGetRequestParameterSet('code')) {
3218 // Default extension is 'unknown'
3221 // Is extension given?
3222 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
3224 // Convert the 'code' parameter from URL to a human-readable message
3225 $message = getMessageFromErrorCode(getRequestParameter('code'));
3227 // Load message template
3228 loadTemplate('message', false, $message);
3232 // Setter for extra title
3233 function setExtraTitle ($extraTitle) {
3234 $GLOBALS['extra_title'] = $extraTitle;
3237 // Getter for extra title
3238 function getExtraTitle () {
3239 // Is the extra title set?
3240 if (!isExtraTitleSet()) {
3241 // No, then abort here
3242 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
3246 return $GLOBALS['extra_title'];
3249 // Checks if the extra title is set
3250 function isExtraTitleSet () {
3251 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3254 // Generates a 'extension foo inactive' message
3255 function generateExtensionInactiveMessage ($ext_name) {
3256 // Is the extension empty?
3257 if (empty($ext_name)) {
3258 // This should not happen
3259 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3263 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3265 // Is an admin logged in?
3267 // Then output admin message
3268 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3271 // Return prepared message
3275 // Generates a 'extension foo not installed' message
3276 function generateExtensionNotInstalledMessage ($ext_name) {
3277 // Is the extension empty?
3278 if (empty($ext_name)) {
3279 // This should not happen
3280 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3284 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3286 // Is an admin logged in?
3288 // Then output admin message
3289 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3292 // Return prepared message
3296 // Generates a message depending on if the extension is not installed or not
3298 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3302 // Is the extension not installed or just deactivated?
3303 switch (isExtensionInstalled($ext_name)) {
3304 case true; // Deactivated!
3305 $message = generateExtensionInactiveMessage($ext_name);
3308 case false; // Not installed!
3309 $message = generateExtensionNotInstalledMessage($ext_name);
3312 default: // Should not happen!
3313 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3314 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3318 // Return the message
3322 // Reads a directory recursively by default and searches for files not matching
3323 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3324 // a whole directory.
3325 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3326 // Add default entries we should exclude
3327 $excludeArray[] = '.';
3328 $excludeArray[] = '..';
3329 $excludeArray[] = '.svn';
3330 $excludeArray[] = '.htaccess';
3332 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3337 $dirPointer = opendir(getConfig('PATH') . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3340 while ($baseFile = readdir($dirPointer)) {
3341 // Exclude '.', '..' and entries in $excludeArray automatically
3342 if (in_array($baseFile, $excludeArray, true)) {
3344 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3348 // Construct include filename and FQFN
3349 $fileName = $baseDir . $baseFile;
3350 $FQFN = getConfig('PATH') . $fileName;
3352 // Remove double slashes
3353 $FQFN = str_replace('//', '/', $FQFN);
3355 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3356 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3357 // These Lines are only for debugging!!
3358 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3359 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3360 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3366 // Skip also files with non-matching prefix genericly
3367 if (($recursive === true) && (isDirectory($FQFN))) {
3368 // Is a redirectory so read it as well
3369 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3371 // And skip further processing
3373 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3375 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3377 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3378 // Skip wrong suffix as well
3379 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3381 } elseif (!isFileReadable($FQFN)) {
3382 // Not readable so skip it
3383 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3387 // Is the file a PHP script or other?
3388 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3389 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3390 // Is this a valid include file?
3391 if ($extension == '.php') {
3392 // Remove both for extension name
3393 $extName = substr($baseFile, strlen($prefix), -4);
3395 // Is the extension valid and active?
3396 if (isExtensionNameValid($extName)) {
3397 // Then add this file
3398 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3399 $files[] = $fileName;
3401 // Add non-extension files as well
3402 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3403 if ($addBaseDir === true) {
3404 $files[] = $fileName;
3406 $files[] = $baseFile;
3410 // We found .php file but should not search for them, why?
3411 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
3413 } elseif (substr($baseFile, -4, 4) == $extension) {
3414 // Other, generic file found
3415 $files[] = $fileName;
3420 closedir($dirPointer);
3425 // Return array with include files
3426 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3430 // Maps a module name into a database table name
3431 function mapModuleToTable ($moduleName) {
3432 // Map only these, still lame code...
3433 switch ($moduleName) {
3434 // 'index' is the guest's menu
3435 case 'index': $moduleName = 'guest'; break;
3436 // ... and 'login' the member's menu
3437 case 'login': $moduleName = 'member'; break;
3438 // Anything else will not be mapped, silently.
3445 // Add SQL debug data to array for later output
3446 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3447 // Already executed?
3448 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3449 // Then abort here, we don't need to profile a query twice
3453 // Remeber this as profiled (or not, but we don't care here)
3454 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3456 // Do we have cache?
3457 if (!isset($GLOBALS['debug_sql_available'])) {
3458 // Check it and cache it in $GLOBALS
3459 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3462 // Don't execute anything here if we don't need or ext-other is missing
3463 if ($GLOBALS['debug_sql_available'] === false) {
3469 'num_rows' => SQL_NUMROWS($result),
3470 'affected' => SQL_AFFECTEDROWS(),
3471 'sql_str' => $sqlString,
3472 'timing' => $timing,
3473 'file' => basename($F),
3478 $GLOBALS['debug_sqls'][] = $record;
3481 // Initializes the cache instance
3482 function initCacheInstance () {
3483 // Load include for CacheSystem class
3484 loadIncludeOnce('inc/classes/cachesystem.class.php');
3486 // Initialize cache system only when it's needed
3487 $GLOBALS['cache_instance'] = new CacheSystem();
3488 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3489 // Failed to initialize cache sustem
3490 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3494 // Getter for message from array or raw message
3495 function getMessageFromIndexedArray ($message, $pos, $array) {
3496 // Check if the requested message was found in array
3497 if (isset($array[$pos])) {
3498 // ... if yes then use it!
3499 $ret = $array[$pos];
3501 // ... else use default message
3509 // Print code with line numbers
3510 function linenumberCode ($code) {
3511 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3512 $count_lines = count($codeE);
3514 $r = 'Line | Code:<br />';
3515 foreach($codeE as $line => $c) {
3516 $r .= '<div class="line"><span class="linenum">';
3517 if ($count_lines == 1) {
3520 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3525 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3528 return '<div class="code">' . $r . '</div>';
3531 // Convert ';' to ', ' for e.g. receiver list
3532 function convertReceivers ($old) {
3533 return str_replace(';', ', ', $old);
3536 // Determines the right page title
3537 function determinePageTitle () {
3538 // Config and database connection valid?
3539 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3543 // Title decoration enabled?
3544 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3546 // Do we have some extra title?
3547 if (isExtraTitleSet()) {
3549 $TITLE .= getExtraTitle() . ' by ';
3553 $TITLE .= getConfig('MAIN_TITLE');
3555 // Add title of module? (middle decoration will also be added!)
3556 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3557 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3560 // Add title from what file
3562 if (getModule() == 'login') $mode = 'member';
3563 elseif (getModule() == 'index') $mode = 'guest';
3564 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3566 // Add title decorations? (right)
3567 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3569 // Remember title in constant for the template
3570 $pageTitle = $TITLE;
3571 } elseif ((isInstalled()) && (isAdminRegistered())) {
3572 // Installed, admin registered but no ext-sql_patches
3573 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3574 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3575 // Installed but no admin registered
3576 $pageTitle = getMessage('SETUP_OF_MAILER');
3577 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3578 // Installation mode
3579 $pageTitle = getMessage('INSTALLATION_OF_MAILER');
3581 // Configuration not found!
3582 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3584 // Do not add the fatal message in installation mode
3585 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3589 return decodeEntities($pageTitle);
3592 // Checks wethere there is a cache file there. This function is cached.
3593 function isTemplateCached ($template) {
3594 // Do we have cached this result?
3595 if (!isset($GLOBALS['template_cache'][$template])) {
3597 $FQFN = generateCacheFqfn($template);
3600 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3604 return $GLOBALS['template_cache'][$template];
3607 // Flushes non-flushed template cache to disk
3608 function flushTemplateCache ($template, $eval) {
3609 // Is this cache flushed?
3610 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3612 $FQFN = generateCacheFqfn($template);
3615 writeToFile($FQFN, $eval, true);
3619 // Reads a template cache
3620 function readTemplateCache ($template) {
3622 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3624 $FQFN = generateCacheFqfn($template);
3627 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3631 return $GLOBALS['template_eval'][$template];
3634 // Escapes quotes (default is only double-quotes)
3635 function escapeQuotes ($str, $single = false) {
3636 // Should we escape all?
3637 if ($single === true) {
3638 // Escape all (including null)
3639 $str = addslashes($str);
3641 // Escape only double-quotes but prevent double-quoting
3642 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3645 // Return the escaped string
3649 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3650 function escapeJavaScriptQuotes ($str) {
3651 // Replace all double-quotes and secure back-ticks
3652 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3658 // Send out mails depending on the 'mod/modes' combination
3659 // @TODO Lame description for this function
3660 function sendModeMails ($mod, $modes) {
3662 if (fetchUserData(getMemberId())) {
3663 // Extract salt from cookie
3664 $salt = substr(getSession('u_hash'), 0, -40);
3666 // Now let's compare passwords
3667 $hash = encodeHashForCookie(getUserData('password'));
3669 // Does the hash match or should we change it?
3670 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
3672 $content = getUserDataArray();
3675 $content['gender'] = translateGender($content['gender']);
3677 // Clear/init the content variable
3678 $content['message'] = '';
3681 // @TODO Move this in a filter
3684 foreach ($modes as $mode) {
3686 case 'normal': break; // Do not add any special lines
3687 case 'email': // Email was changed!
3688 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestParameter('old_email')."\n";
3691 case 'pass': // Password was changed
3692 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3696 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3697 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3702 if (isExtensionActive('country')) {
3703 // Replace code with description
3704 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
3707 // Merge content with data from POST
3708 $content = merge_array($content, postRequestArray());
3711 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3713 if (getConfig('admin_notify') == 'Y') {
3714 // The admin needs to be notified about a profile change
3715 $message_admin = 'admin_mydata_notify';
3716 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3719 $message_admin = '';
3723 // Set subject lines
3724 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3726 // Output success message
3727 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3730 default: // Unsupported module!
3731 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3732 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
3736 // Passwords mismatch
3737 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
3740 // Could not load profile
3741 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
3744 // Send email to user if required
3745 if ((!empty($sub_mem)) && (!empty($message))) {
3747 sendEmail($content['email'], $sub_mem, $message);
3750 // Send only if no other error has occured
3751 if (empty($content)) {
3752 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3754 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3755 } elseif (getConfig('admin_notify') == 'Y') {
3756 // Cannot send mails to admin!
3757 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3760 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3765 loadTemplate('admin_settings_saved', false, $content);
3768 // Generates a 'selection box' from given array
3769 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
3771 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3772 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3774 // Walk through all options
3775 foreach ($options as $option) {
3776 // Add the <option> entry
3777 if (empty($optionContent)) {
3778 // ... from template
3779 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
3782 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3786 // Finish selection box
3787 $OUT .= '</select>';
3791 'selection_box' => $OUT,
3792 'module' => getModule(),
3796 // Load template and return it
3797 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
3800 // Get a module from filename and access level
3801 function getModuleFromFileName ($file, $accessLevel) {
3802 // Default is 'invalid';
3803 $modCheck = 'invalid';
3805 // @TODO This is still very static, rewrite it somehow
3806 switch ($accessLevel) {
3808 $modCheck = 'admin';
3814 $modCheck = getModule();
3817 default: // Unsupported file name / access level
3818 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3826 // Encodes an URL for adding session id, etc.
3827 function encodeUrl ($url, $outputMode = '0') {
3828 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
3829 if ((strpos($url, session_name()) !== false) || (getOutputMode() == -3)) return $url;
3831 // Do we have a valid session?
3832 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3834 // Determine right seperator
3835 $seperator = '&';
3836 if (strpos($url, '?') === false) {
3839 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3845 if (session_id() != '') {
3846 $url .= $seperator . session_name() . '=' . session_id();
3851 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3853 $url = '{?URL?}/' . $url;
3860 // Simple check for spider
3861 function isSpider () {
3863 $userAgent = strtolower(detectUserAgent(true));
3865 // It should not be empty, if so it is better a spider/bot
3866 if (empty($userAgent)) return true;
3869 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
3872 // Prepares the header for HTML output
3873 function loadHtmlHeader () {
3875 // 1.) pre_page_header (mainly loads the page_header template and includes
3876 // meta description)
3877 runFilterChain('pre_page_header');
3879 // Here can be something be added, but normally one of the two filters
3880 // around this line should do the job for you.
3882 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
3883 // to close the head-tag)
3884 // Include more header data here
3885 runFilterChain('post_page_header');
3888 // Adds page header and footer to output array element
3889 function addPageHeaderFooter () {
3893 // Add them all together. This is maybe to simple
3894 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
3895 // Add page part if set
3896 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
3899 // Transfer $OUT to 'output'
3900 $GLOBALS['output'] = $OUT;
3903 // Generates meta description for current module and 'what' value
3904 function generateMetaDescriptionCode () {
3905 // Only include from guest area and if sql_patches has correct version
3906 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3907 // Construct dynamic description
3908 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
3910 // Output it directly
3911 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
3915 unset($GLOBALS['ref_level']);
3918 // Generates an FQFN for template cache from the given template name
3919 function generateCacheFqfn ($template) {
3921 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
3922 // Generate the FQFN
3923 $GLOBALS['template_cache_fqfn'][$template] = sprintf("%s_compiled/html/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3927 return $GLOBALS['template_cache_fqfn'][$template];
3930 // Function to search for the last modified file
3931 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
3933 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
3934 // Does it match what we are looking for? (We skip a lot files already!)
3935 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
3936 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
3938 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
3939 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
3941 // Walk through all entries
3942 foreach ($ds as $d) {
3943 // Generate proper FQFN
3944 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir . '/' . $d);
3946 // Is it a file and readable?
3947 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
3948 if (isFileReadable($FQFN)) {
3949 // $FQFN is a readable file so extract the requested data from it
3950 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
3951 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
3953 // Is the file more recent?
3954 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
3955 // This file is newer as the file before
3956 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
3957 $last_changed['path_name'] = $FQFN;
3958 $last_changed[$lookFor] = $check;
3962 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
3967 // "Fixes" null or empty string to count of dashes
3968 function fixNullEmptyToDashes ($str, $num) {
3969 // Use str as default
3973 if ((is_null($str)) || (trim($str) == '')) {
3975 $return = str_repeat('-', $num);
3978 // Return final string
3982 // Handles the braces [] of a field (e.g. value of 'name' attribute)
3983 function handleFieldWithBraces ($field) {
3984 // Are there braces [] at the end?
3985 if (substr($field, -2, 2) == '[]') {
3986 // Try to find one and replace it. I do it this way to allow easy
3987 // extending of this code.
3988 foreach (array('admin_list_builder_id_value') as $key) {
3989 // Is the cache entry set?
3990 if (isset($GLOBALS[$key])) {
3992 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
4004 //////////////////////////////////////////////////
4005 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
4006 //////////////////////////////////////////////////
4008 if (!function_exists('html_entity_decode')) {
4009 // Taken from documentation on www.php.net
4010 function html_entity_decode ($string) {
4011 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
4012 $trans_tbl = array_flip($trans_tbl);
4013 return strtr($string, $trans_tbl);
4017 if (!function_exists('http_build_query')) {
4018 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
4019 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
4021 foreach ((array)$data as $k => $v) {
4022 if (is_int($k) && $prefix != null) {
4023 $k = urlencode($prefix . $k);
4026 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
4028 if (is_array($v) || is_object($v)) {
4029 array_push($ret, http_build_query($v, '', $sep, $k));
4031 array_push($ret, $k.'='.urlencode($v));
4035 if (empty($sep)) $sep = ini_get('arg_separator.output');
4037 return implode($sep, $ret);