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 () {
139 // Add page header and footer
140 addPageHeaderFooter();
142 // Do the final compilation
143 $GLOBALS['output'] = doFinalCompilation($GLOBALS['output']);
145 // Extension 'rewrite' installed?
146 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
147 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
151 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
152 // Compress it for HTTP gzip
153 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
156 sendHeader('Content-Encoding: gzip');
157 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
158 // Compress it for HTTP deflate
159 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
162 sendHeader('Content-Encoding: deflate');
166 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
172 // Main compilation loop
173 function doFinalCompilation ($code, $insertComments = true) {
174 // Insert comments? (Only valid with HTML templates, of course)
175 enableTemplateHtml($insertComments);
181 while (((strpos($code, '{--') !== false) || (strpos($code, '{DQUOTE}') !== false) || (strpos($code, '{?') !== false) || (strpos($code, '{%') !== false)) && ($cnt < 4)) {
182 // Init common variables
187 //* DEBUG: */ debugOutput('<pre>'.encodeEntities($code).'</pre>');
188 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($code))) . '";';
189 //* DEBUG: */ if ($insertComments) die('<pre>'.linenumberCode($eval).'</pre>');
191 //* DEBUG: */ die('<pre>'.encodeEntities($newContent).'</pre>');
193 // Was that eval okay?
194 if (empty($newContent)) {
195 // Something went wrong!
196 debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
206 // Return the compiled code
210 // Output the raw HTML code
211 function outputRawCode ($htmlCode) {
212 // Output stripped HTML code to avoid broken JavaScript code, etc.
213 print(str_replace('{BACK}', "\\", $htmlCode));
215 // Flush the output if only getPhpCaching() is not 'on'
216 if (getPhpCaching() != 'on') {
222 // Init fatal message array
223 function initFatalMessages () {
224 $GLOBALS['fatal_messages'] = array();
227 // Getter for whole fatal error messages
228 function getFatalArray () {
229 return $GLOBALS['fatal_messages'];
232 // Add a fatal error message to the queue array
233 function addFatalMessage ($F, $L, $message, $extra = '') {
234 if (is_array($extra)) {
235 // Multiple extras for a message with masks
236 $message = call_user_func_array('sprintf', $extra);
237 } elseif (!empty($extra)) {
238 // $message is text with a mask plus extras to insert into the text
239 $message = sprintf($message, $extra);
242 // Add message to $GLOBALS['fatal_messages']
243 $GLOBALS['fatal_messages'][] = $message;
245 // Log fatal messages away
246 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
249 // Getter for total fatal message count
250 function getTotalFatalErrors () {
254 // Do we have at least the first entry?
255 if (!empty($GLOBALS['fatal_messages'][0])) {
257 $count = count($GLOBALS['fatal_messages']);
264 // Load a template file and return it's content (only it's name; do not use ' or ")
265 function loadTemplate ($template, $return = false, $content = array()) {
266 // @TODO Remove this sanity-check if all is fine
267 if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
269 // @TODO Try to rewrite all $DATA to $content
273 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
274 // Evaluate the cache
275 eval(readTemplateCache($template));
276 } elseif (!isset($GLOBALS['template_eval'][$template])) {
277 // Make all template names lowercase
278 $template = strtolower($template);
282 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
285 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
286 $extraPath = detectExtraTemplatePath($template);;
288 ////////////////////////
289 // Generate file name //
290 ////////////////////////
291 $FQFN = $basePath . $extraPath . $template . '.tpl';
293 // Does the special template exists?
294 if (!isFileReadable($FQFN)) {
295 // Reset to default template
296 $FQFN = $basePath . $template . '.tpl';
299 // Now does the final template exists?
300 if (isFileReadable($FQFN)) {
301 // Count the template load
302 incrementConfigEntry('num_templates');
304 // The local file does exists so we load it. :)
305 $GLOBALS['tpl_content'] = readFromFile($FQFN);
307 // Do we have to compile the code?
309 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false) || (strpos($GLOBALS['tpl_content'], '{%') !== false)) {
310 // Normal HTML output?
311 if (getOutputMode() == '0') {
312 // Add surrounding HTML comments to help finding bugs faster
313 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
315 // Prepare eval() command
316 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
317 } elseif (substr($template, 0, 3) == 'js_') {
318 // JavaScripts don't like entities and timings
319 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
321 // Prepare eval() command, other output doesn't like entities, maybe
322 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
325 // Add surrounding HTML comments to help finding bugs faster
326 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
327 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
330 // Cache the eval() command here
331 $GLOBALS['template_eval'][$template] = $eval;
332 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
333 // Only admins shall see this warning or when installation mode is active
334 $ret = '<div class="para">
335 <span class="guest_failed">{--TEMPLATE_404--}</span>
341 {--TEMPLATE_CONTENT--}
342 <pre>' . print_r($content, true) . '</pre>
344 <pre>' . print_r($DATA, true) . '</pre>
348 $GLOBALS['template_eval'][$template] = '404';
353 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
355 eval($GLOBALS['template_eval'][$template]);
358 // Do we have some content to output or return?
360 // Not empty so let's put it out! ;)
361 if ($return === true) {
362 // Return the HTML code
368 } elseif (isDebugModeEnabled()) {
369 // Warning, empty output!
370 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
374 // Detects the extra template path from given template name
375 function detectExtraTemplatePath ($template) {
380 if (!isset($GLOBALS['extra_path'][$template])) {
381 // Check for admin/guest/member/etc. templates
382 if (substr($template, 0, 6) == 'admin_') {
383 // Admin template found
384 $extraPath = 'admin/';
385 } elseif (substr($template, 0, 6) == 'guest_') {
386 // Guest template found
387 $extraPath = 'guest/';
388 } elseif (substr($template, 0, 7) == 'member_') {
389 // Member template found
390 $extraPath = 'member/';
391 } elseif (substr($template, 0, 7) == 'select_') {
392 // Selection template found
393 $extraPath = 'select/';
394 } elseif (substr($template, 0, 8) == 'install_') {
395 // Installation template found
396 $extraPath = 'install/';
397 } elseif (substr($template, 0, 4) == 'ext_') {
398 // Extension template found
400 } elseif (substr($template, 0, 3) == 'la_') {
401 // 'Logical-area' template found
403 } elseif (substr($template, 0, 3) == 'js_') {
404 // JavaScript template found
406 } elseif (substr($template, 0, 5) == 'menu_') {
407 // Menu template found
408 $extraPath = 'menu/';
410 // Test for extension
411 $test = substr($template, 0, strpos($template, '_'));
413 // Probe for valid extension name
414 if (isExtensionNameValid($test)) {
415 // Set extra path to extension's name
416 $extraPath = $test . '/';
421 $GLOBALS['extra_path'][$template] = $extraPath;
425 return $GLOBALS['extra_path'][$template];
428 // Loads an email template and compiles it
429 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
432 // Make sure all template names are lowercase!
433 $template = strtolower($template);
435 // Is content an array?
436 if (is_array($content)) {
437 // Add expiration to array
438 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
439 // Will never expire!
440 $content['expiration'] = '{--MAIL_WILL_NEVER_EXPIRE--}';
441 } elseif (isConfigEntrySet('auto_purge')) {
442 // Create nice date string
443 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
446 $content['expiration'] = '{--MAIL_NO_CONFIG_AUTO_PURGE--}';
451 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content));
452 if (($userid > 0) && (is_array($content))) {
453 // If nickname extension is installed, fetch nickname as well
454 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
455 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
457 fetchUserData($userid, 'nickname');
459 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
461 fetchUserData($userid);
464 // Merge data if valid
465 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
466 if (isUserDataValid()) {
467 $content = merge_array($content, getUserDataArray());
469 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
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 = '<div class="para">
499 {--TEMPLATE_404--}: ' . $template . '
502 {--TEMPLATE_CONTENT--}
503 <pre>' . print_r($content, true) . '</pre>
505 <pre>' . print_r($DATA, true) . '</pre>
508 // Debug mode not active? Then remove the HTML tags
509 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
511 // No template name supplied!
512 $newContent = '{--NO_TEMPLATE_SUPPLIED--}';
515 // Is there some content?
516 if (empty($newContent)) {
518 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
520 // Add last error if the required function exists
521 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
524 // Remove content and data
532 // Send mail out to an email address
533 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
534 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail},SUBJECT={$subject}<br />");
536 // Compile subject line (for POINTS constant etc.)
537 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
540 if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
541 // Value detected, is the message extension installed?
542 // @TODO Extension 'msg' does not exist
543 if (isExtensionActive('msg')) {
544 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
547 // Does the user exist?
548 if (fetchUserData($toEmail)) {
550 $toEmail = getUserData('email');
553 $toEmail = getConfig('WEBMASTER');
556 } elseif ($toEmail == '0') {
558 $toEmail = getConfig('WEBMASTER');
560 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
562 // Check for PHPMailer or debug-mode
563 if ((!checkPhpMailerUsage()) || (isDebugModeEnabled())) {
564 // Not in PHPMailer-Mode
565 if (empty($mailHeader)) {
566 // Load email header template
567 $mailHeader = loadEmailTemplate('header');
570 $mailHeader .= loadEmailTemplate('header');
574 // Fix HTML parameter (default is no!)
575 if (empty($isHtml)) $isHtml = 'N';
577 // Debug mode enabled?
578 if (isDebugModeEnabled()) {
579 // In debug mode we want to display the mail instead of sending it away so we can debug this part
581 Headers : ' . encodeEntities(utf8_decode(trim($mailHeader))) . '
582 To : ' . encodeEntities(utf8_decode($toEmail)) . '
583 Subject : ' . encodeEntities(utf8_decode($subject)) . '
584 Message : ' . encodeEntities(utf8_decode($message)) . '
587 // This is always fine
589 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
590 // Send mail as HTML away
591 return sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
592 } elseif (!empty($toEmail)) {
594 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
595 } elseif ($isHtml != 'Y') {
597 return sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
600 // Why did we end up here? This should not happen
601 debug_report_bug(__FUNCTION__, __LINE__, 'Ending up: template=' . $template);
604 // Check to use wether legacy mail() command or PHPMailer class
605 // @TODO Rewrite this to an extension 'smtp'
607 function checkPhpMailerUsage() {
608 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
611 // Send out a raw email with PHPMailer class or legacy mail() command
612 function sendRawEmail ($toEmail, $subject, $message, $from) {
613 // Just compile all again, to put out all configs, etc.
614 eval('$toEmail = decodeEntities("' . doFinalCompilation(compileRawCode(escapeQuotes($toEmail)), false) . '");');
615 eval('$subject = decodeEntities("' . doFinalCompilation(compileRawCode(escapeQuotes($subject)), false) . '");');
616 eval('$message = decodeEntities("' . doFinalCompilation(compileRawCode(escapeQuotes($message)), false) . '");');
617 eval('$from = decodeEntities("' . doFinalCompilation(compileRawCode(escapeQuotes($from)) , false) . '");');
619 // Shall we use PHPMailer class or legacy mode?
620 if (checkPhpMailerUsage()) {
621 // Use PHPMailer class with SMTP enabled
622 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
623 loadIncludeOnce('inc/phpmailer/class.smtp.php');
626 $mail = new PHPMailer();
628 // Set charset to UTF-8
629 $mail->CharSet = 'UTF-8';
631 // Path for PHPMailer
632 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
635 $mail->SMTPAuth = true;
636 $mail->Host = getConfig('SMTP_HOSTNAME');
638 $mail->Username = getConfig('SMTP_USER');
639 $mail->Password = getConfig('SMTP_PASSWORD');
641 $mail->From = getConfig('WEBMASTER');
645 $mail->FromName = getConfig('MAIN_TITLE');
646 $mail->Subject = $subject;
647 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
648 $mail->Body = $message;
649 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
650 $mail->WordWrap = 70;
653 $mail->Body = decodeEntities($message);
655 $mail->AddAddress($toEmail, '');
656 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
657 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
658 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
661 // Has an error occured?
662 if (!empty($mail->ErrorInfo)) {
664 logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
673 // Use legacy mail() command
674 return mail($toEmail, $subject, decodeEntities($message), $from);
678 // Generate a password in a specified length or use default password length
679 function generatePassword ($length = '0') {
680 // Auto-fix invalid length of zero
681 if ($length == '0') $length = getConfig('pass_len');
683 // Initialize array with all allowed chars
684 $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,-,+,_,/,.');
686 // Start creating password
688 for ($i = '0'; $i < $length; $i++) {
689 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
692 // When the size is below 40 we can also add additional security by scrambling
693 // it. Otherwise we may corrupt hashes
694 if (strlen($PASS) <= 40) {
695 // Also scramble the password
696 $PASS = scrambleString($PASS);
699 // Return the password
703 // Generates a human-readable timestamp from the Uni* stamp
704 function generateDateTime ($time, $mode = '0') {
705 // Filter out numbers
706 $time = bigintval($time);
708 // If the stamp is zero it mostly didn't "happen"
711 return getMessage('NEVER_HAPPENED');
714 switch (getLanguage()) {
715 case 'de': // German date / time format
717 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
718 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
719 case '2': $ret = date('d.m.Y|H:i', $time); break;
720 case '3': $ret = date('d.m.Y', $time); break;
722 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
727 default: // Default is the US date / time format!
729 case '0': $ret = date('r', $time); break;
730 case '1': $ret = date('Y-m-d - g:i A', $time); break;
731 case '2': $ret = date('y-m-d|H:i', $time); break;
732 case '3': $ret = date('y-m-d', $time); break;
734 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
743 // Translates Y/N to yes/no
744 function translateYesNo ($yn) {
746 $translated = '??? (' . $yn . ')';
748 case 'Y': $translated = '{--YES--}'; break;
749 case 'N': $translated = '{--NO--}'; break;
752 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
760 // Translates the "pool type" into human-readable
761 function translatePoolType ($type) {
762 // Default?type is unknown
763 $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
766 $constName = sprintf("POOL_TYPE_%s", $type);
769 if (isMessageIdValid($constName)) {
771 $translated = getMessage($constName);
774 // Return "translation"
778 // Translates the american decimal dot into a german comma
779 function translateComma ($dotted, $cut = true, $max = '0') {
780 // First, cast all to double, due to PHP changes
781 $dotted = (double) $dotted;
783 // Default is 3 you can change this in admin area "Misc -> Misc Options"
784 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
786 // Use from config is default
787 $maxComma = getConfig('max_comma');
789 // Use from parameter?
790 if ($max > 0) $maxComma = $max;
793 if (($cut === true) && ($max == '0')) {
794 // Test for commata if in cut-mode
795 $com = explode('.', $dotted);
796 if (count($com) < 2) {
797 // Don't display commatas even if there are none... ;-)
803 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
806 switch (getLanguage()) {
807 case 'de': // German language
808 $dotted = number_format($dotted, $maxComma, ',', '.');
811 default: // All others
812 $dotted = number_format($dotted, $maxComma, '.', ',');
816 // Return translated value
820 // Translate Uni*-like gender to human-readable
821 function translateGender ($gender) {
823 $ret = '!' . $gender . '!';
825 // Male/female or company?
827 case 'M': $ret = '{--GENDER_M--}'; break;
828 case 'F': $ret = '{--GENDER_F--}'; break;
829 case 'C': $ret = '{--GENDER_C--}'; break;
831 // Please report bugs on unknown genders
832 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
836 // Return translated gender
840 // "Translates" the user status
841 function translateUserStatus ($status) {
842 // Generate message depending on status
847 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
852 $ret = '{--ACCOUNT_DELETED--}';
856 // Please report all unknown status
857 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
865 // "Translates" 'visible' and 'locked' to a CSS class
866 function translateMenuVisibleLocked ($content, $prefix = '') {
867 // Translate 'visible' and keep an eye on the prefix
868 switch ($content['visible']) {
870 case 'Y': $content['visible_css'] = $prefix . 'menu_visible' ; break;
871 case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break;
873 // Please report this
874 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, true) . '</pre>');
878 // Translate 'locked' and keep an eye on the prefix
879 switch ($content['locked']) {
881 case 'Y': $content['locked_css'] = $prefix . 'menu_locked' ; break;
882 case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break;
884 // Please report this
885 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, true) . '</pre>');
889 // Return the resulting array
893 // "Getter" for menu CSS classes, mainly used in templates
894 function getMenuCssClasses ($data) {
895 // $data needs to be converted into an array
896 $content = explode('|', $data);
898 // Non-existent index 2 will happen in menu blocks
899 if (!isset($content[2])) $content[2] = '';
901 // Re-construct the array: 0=visible,1=locked,2=prefix
902 $content['visible'] = $content[0];
903 $content['locked'] = $content[1];
905 // Call our "translator" function
906 $content = translateMenuVisibleLocked($content, $content[2]);
908 // Return CSS classes
909 return ($content['visible_css'] . ' ' . $content['locked_css']);
912 // Generates an URL for the dereferer
913 function generateDerefererUrl ($URL) {
914 // Don't de-refer our own links!
915 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
916 // De-refer this link
917 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
924 // Generates an URL for the frametester
925 function generateFrametesterUrl ($URL) {
926 // Prepare frametester URL
927 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
928 encodeString(compileUriCode($URL))
931 // Return the new URL
932 return $frametesterUrl;
935 // Count entries from e.g. a selection box
936 function countSelection ($array) {
938 if (!is_array($array)) {
940 debug_report_bug(__FUNCTION__.': No array provided.');
947 foreach ($array as $key => $selected) {
949 if (!empty($selected)) $ret++;
952 // Return counted selections
956 // Generate XHTML code for the CAPTCHA
957 function generateCaptchaCode ($code, $type, $DATA, $userid) {
958 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
961 // Generates a timestamp (some wrapper for mktime())
962 function makeTime ($hours, $minutes, $seconds, $stamp) {
963 // Extract day, month and year from given timestamp
964 $days = date('d', $stamp);
965 $months = date('m', $stamp);
966 $years = date('Y', $stamp);
968 // Create timestamp for wished time which depends on extracted date
979 // Redirects to an URL and if neccessarry extends it with own base URL
980 function redirectToUrl ($URL, $allowSpider = true) {
982 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
984 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
985 $rel = ' rel="external"';
987 // Do we have internal or external URL?
988 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
989 // Own (=internal) URL
993 // Three different ways to debug...
994 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
995 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
996 //* DEBUG: */ die($URL);
998 // Simple probe for bots/spiders from search engines
999 if ((isSpider()) && ($allowSpider === true)) {
1001 setHttpStatus('200 OK');
1003 // Set content-type here to fix a missing array element
1004 setContentType('text/html');
1006 // Output new location link as anchor
1007 outputHtml('<a href="' . $URL . '"' . $rel . '>' . secureString($URL) . '</a>');
1008 } elseif (!headers_sent()) {
1009 // Clear output buffer
1010 clearOutputBuffer();
1012 // Clear own output buffer
1013 $GLOBALS['output'] = '';
1016 setHttpStatus('302 Found');
1018 // Load URL when headers are not sent
1019 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $URL), false));
1021 // Output error message
1022 loadInclude('inc/header.php');
1023 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
1024 loadInclude('inc/footer.php');
1027 // Shut the mailer down here
1031 // Wrapper for redirectToUrl but URL comes from a configuration entry
1032 function redirectToConfiguredUrl ($configEntry) {
1034 redirectToUrl(getConfig($configEntry));
1037 // Compiles the given HTML/mail code
1038 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1039 // Is the code a string?
1040 if (!is_string($code)) {
1041 // Silently return it
1046 $startCompile = microtime(true);
1049 $code = compileRawCode($code, $simple, $constants, $full);
1052 $compiled = microtime(true);
1054 // Add timing if enabled
1055 if (isTemplateHtml()) {
1056 // Add timing, this should be disabled in
1057 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1060 // Return compiled code
1064 // Compiles the code (use compileCode() only for HTML because of the comments)
1065 // @TODO $simple/$constants are deprecated
1066 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1067 // Is the code a string?
1068 if (!is_string($code)) {
1069 // Silently return it
1073 // Init replacement-array with smaller set of security characters
1074 $secChars = $GLOBALS['url_chars'];
1076 // Select full set of chars to replace when we e.g. want to compile URLs
1077 if ($full === true) $secChars = $GLOBALS['security_chars'];
1079 // Compile more through a filter
1080 $code = runFilterChain('compile_code', $code);
1082 // Compile message strings
1083 $code = str_replace('{--', '{%message,', str_replace('--}', '%}', $code));
1085 // Compile QUOT and other non-HTML codes
1086 foreach ($secChars['to'] as $k => $to) {
1087 // Do the reversed thing as in inc/libs/security_functions.php
1088 $code = str_replace($to, $secChars['from'][$k], $code);
1091 // Find $content[bla][blub] entries
1092 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1093 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1095 // Are some matches found?
1096 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1097 // Replace all matches
1098 $matchesFound = array();
1099 foreach ($matches[0] as $key => $match) {
1100 // Fuzzy look has failed by default
1101 $fuzzyFound = false;
1103 // Fuzzy look on match if already found
1104 foreach ($matchesFound as $found => $set) {
1106 $test = substr($found, 0, strlen($match));
1108 // Does this entry exist?
1109 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
1110 if ($test == $match) {
1112 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
1119 if ($fuzzyFound === true) continue;
1121 // Take all string elements
1122 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key.'_' . $matches[4][$key]]))) {
1123 // Replace it in the code
1124 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
1125 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1126 $code = str_replace($match, '".' . $newMatch . '."', $code);
1127 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1128 $matchesFound[$match] = 1;
1129 } elseif (!isset($matchesFound[$match])) {
1130 // Not yet replaced!
1131 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
1132 $code = str_replace($match, '".' . $match . '."', $code);
1133 $matchesFound[$match] = 1;
1142 /************************************************************************
1144 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1145 * $a_sort sortiert: *
1147 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1148 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1149 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1150 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1151 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1153 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1154 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1155 * Sie, dass es doch nicht so schwer ist! :-) *
1157 ************************************************************************/
1158 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1160 while ($primary_key < count($a_sort)) {
1161 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1162 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1164 if ($nums === false) {
1165 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1166 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1167 } elseif ($key != $key2) {
1168 // Sort numbers (E.g.: 9 < 10)
1169 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1170 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1174 // We have found two different values, so let's sort whole array
1175 foreach ($dummy as $sort_key => $sort_val) {
1176 $t = $dummy[$sort_key][$key];
1177 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1178 $dummy[$sort_key][$key2] = $t;
1189 // Write back sorted array
1194 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1197 if ($type == 'yn') {
1198 // This is a yes/no selection only!
1199 if ($id > 0) $prefix .= '[' . $id . ']';
1200 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
1202 // Begin with regular selection box here
1203 if (!empty($prefix)) $prefix .= '_';
1205 if ($id > 0) $type2 .= '[' . $id . ']';
1206 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
1211 for ($idx = 1; $idx < 32; $idx++) {
1212 $OUT .= '<option value="' . $idx . '"';
1213 if ($default == $idx) $OUT .= ' selected="selected"';
1214 $OUT .= '>' . $idx . '</option>';
1218 case 'month': // Month
1219 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
1220 $OUT .= '<option value="' . $idx . '"';
1221 if ($default == $idx) $OUT .= ' selected="selected"';
1222 $OUT .= '>' . $descr . '</option>';
1226 case 'year': // Year
1228 $year = date('Y', time());
1230 // Use configured min age or fixed?
1231 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1233 $startYear = $year - getConfig('min_age');
1236 $startYear = $year - 16;
1239 // Calculate earliest year (100 years old people can still enter Internet???)
1240 $minYear = $year - 100;
1242 // Check if the default value is larger than minimum and bigger than actual year
1243 if (($default > $minYear) && ($default >= $year)) {
1244 for ($idx = $year; $idx < ($year + 11); $idx++) {
1245 $OUT .= '<option value="' . $idx . '"';
1246 if ($default == $idx) $OUT .= ' selected="selected"';
1247 $OUT .= '>' . $idx . '</option>';
1249 } elseif ($default == -1) {
1250 // Current year minus 1
1251 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
1252 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
1255 // Get current year and subtract the configured minimum age
1256 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
1257 // Calculate earliest year depending on extension version
1258 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1259 // Use configured minimum age
1260 $year = date('Y', time()) - getConfig('min_age');
1262 // Use fixed 16 years age
1263 $year = date('Y', time()) - 16;
1266 // Construct year selection list
1267 for ($idx = $minYear; $idx <= $year; $idx++) {
1268 $OUT .= '<option value="' . $idx . '"';
1269 if ($default == $idx) $OUT .= ' selected="selected"';
1270 $OUT .= '>' . $idx . '</option>';
1277 for ($idx = 0; $idx < 60; $idx+=5) {
1278 if (strlen($idx) == 1) $idx = '0' . $idx;
1279 $OUT .= '<option value="' . $idx . '"';
1280 if ($default == $idx) $OUT .= ' selected="selected"';
1281 $OUT .= '>' . $idx . '</option>';
1286 for ($idx = 0; $idx < 24; $idx++) {
1287 if (strlen($idx) == 1) $idx = '0' . $idx;
1288 $OUT .= '<option value="' . $idx . '"';
1289 if ($default == $idx) $OUT .= ' selected="selected"';
1290 $OUT .= '>' . $idx . '</option>';
1295 $OUT .= '<option value="Y"';
1296 if ($default == 'Y') $OUT .= ' selected="selected"';
1297 $OUT .= '>{--YES--}</option><option value="N"';
1298 if ($default != 'Y') $OUT .= ' selected="selected"';
1299 $OUT .= '>{--NO--}</option>';
1302 $OUT .= '</select>';
1307 // Deprecated : $length
1310 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1311 // Build server string
1312 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
1315 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1316 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1317 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1318 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1319 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1321 // Build string from misc data
1322 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1324 // Add more additional data
1325 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1327 // Add referal id, language, theme and userid
1328 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1329 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1330 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1331 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1333 // Calculate number for generating the code
1334 $a = $code + getConfig('_ADD') - 1;
1336 if (isConfigEntrySet('master_salt')) {
1337 // Generate hash with master salt from modula of number with the prime number and other data
1338 $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'));
1340 // Create number from hash
1341 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1343 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1344 $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')));
1346 // Create number from hash
1347 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1350 // At least 10 numbers shall be secure enought!
1351 $len = getConfig('code_length');
1352 if ($len == '0') $len = $length;
1353 if ($len == '0') $len = 10;
1355 // Cut off requested counts of number
1356 $return = substr(str_replace('.', '', $rcode), 0, $len);
1358 // Done building code
1362 // Does only allow numbers
1363 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
1364 // Filter all numbers out
1365 $ret = preg_replace('/[^0123456789]/', '', $num);
1368 if ($castValue === true) $ret = (double)$ret;
1370 // Has the whole value changed?
1371 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
1373 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret=' . $ret . ', num='. $num);
1380 // Insert the code in $img_code into jpeg or PNG image
1381 function generateImageOrCode ($img_code, $headerSent = true) {
1382 // Is the code size oversized or shouldn't we display it?
1383 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1384 // Stop execution of function here because of over-sized code length
1385 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1386 } elseif ($headerSent === false) {
1387 // Return an HTML code here
1388 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
1392 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1395 getConfig('img_type')
1399 if (isFileReadable($img)) {
1400 // Switch image type
1401 switch (getConfig('img_type')) {
1403 // Okay, load image and hide all errors
1404 $image = imagecreatefromjpeg($img);
1408 // Okay, load image and hide all errors
1409 $image = imagecreatefrompng($img);
1413 // Exit function here
1414 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1418 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1419 $text_color = imagecolorallocate($image, 0, 0, 0);
1421 // Insert code into image
1422 imagestring($image, 5, 14, 2, $img_code, $text_color);
1424 // Return to browser
1425 sendHeader('Content-Type: image/' . getConfig('img_type'));
1427 // Output image with matching image factory
1428 switch (getConfig('img_type')) {
1429 case 'jpg': imagejpeg($image); break;
1430 case 'png': imagepng($image); break;
1433 // Remove image from memory
1434 imagedestroy($image);
1436 // Create selection box or array of splitted timestamp
1437 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1438 // Do not continue if ONE_DAY is absend
1439 if (!isConfigEntrySet('ONE_DAY')) {
1440 // And return the timestamp itself or empty array
1441 if ($return_array === true) {
1448 // Calculate 2-seconds timestamp
1449 $stamp = round($timestamp);
1450 //* DEBUG: */ debugOutput('*' . $stamp .'/' . $timestamp . '*');
1452 // Do we have a leap year?
1454 $TEST = date('Y', time()) / 4;
1455 $M1 = date('m', time());
1456 $M2 = date('m', (time() + $timestamp));
1458 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1459 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($M2 > '02')) $SWITCH = getConfig('ONE_DAY');
1461 // First of all years...
1462 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1463 //* DEBUG: */ debugOutput('Y=' . $Y);
1465 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1466 //* DEBUG: */ debugOutput('M=' . $M);
1468 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1469 //* DEBUG: */ debugOutput('W=' . $W);
1471 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1472 //* DEBUG: */ debugOutput('D=' . $D);
1474 $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));
1475 //* DEBUG: */ debugOutput('h=' . $h);
1477 $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));
1478 //* DEBUG: */ debugOutput('m=' . $m);
1479 // And at last seconds...
1480 $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));
1481 //* DEBUG: */ debugOutput('s=' . $s);
1483 // Is seconds zero and time is < 60 seconds?
1484 if (($s == '0') && ($timestamp < 60)) {
1486 $s = round($timestamp);
1490 // Now we convert them in seconds...
1492 if ($return_array) {
1493 // Just put all data in an array for later use
1505 $OUT = '<div align="' . $align . '">';
1506 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1509 if (isInString('Y', $display) || (empty($display))) {
1510 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
1513 if (isInString('M', $display) || (empty($display))) {
1514 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
1517 if (isInString('W', $display) || (empty($display))) {
1518 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
1521 if (isInString('D', $display) || (empty($display))) {
1522 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
1525 if (isInString('h', $display) || (empty($display))) {
1526 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
1529 if (isInString('m', $display) || (empty($display))) {
1530 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
1533 if (isInString('s', $display) || (empty($display))) {
1534 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
1540 if (isInString('Y', $display) || (empty($display))) {
1541 // Generate year selection
1542 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
1543 for ($idx = 0; $idx <= 10; $idx++) {
1544 $OUT .= '<option class="mini_select" value="' . $idx . '"';
1545 if ($idx == $Y) $OUT .= ' selected="selected"';
1546 $OUT .= '>' . $idx . '</option>';
1548 $OUT .= '</select></td>';
1550 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1553 if (isInString('M', $display) || (empty($display))) {
1554 // Generate month selection
1555 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
1556 for ($idx = 0; $idx <= 11; $idx++) {
1557 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1558 if ($idx == $M) $OUT .= ' selected="selected"';
1559 $OUT .= '>' . $idx . '</option>';
1561 $OUT .= '</select></td>';
1563 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1566 if (isInString('W', $display) || (empty($display))) {
1567 // Generate week selection
1568 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
1569 for ($idx = 0; $idx <= 4; $idx++) {
1570 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1571 if ($idx == $W) $OUT .= ' selected="selected"';
1572 $OUT .= '>' . $idx . '</option>';
1574 $OUT .= '</select></td>';
1576 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1579 if (isInString('D', $display) || (empty($display))) {
1580 // Generate day selection
1581 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
1582 for ($idx = 0; $idx <= 31; $idx++) {
1583 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1584 if ($idx == $D) $OUT .= ' selected="selected"';
1585 $OUT .= '>' . $idx . '</option>';
1587 $OUT .= '</select></td>';
1589 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1592 if (isInString('h', $display) || (empty($display))) {
1593 // Generate hour selection
1594 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1595 for ($idx = 0; $idx <= 23; $idx++) {
1596 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1597 if ($idx == $h) $OUT .= ' selected="selected"';
1598 $OUT .= '>' . $idx . '</option>';
1600 $OUT .= '</select></td>';
1602 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1605 if (isInString('m', $display) || (empty($display))) {
1606 // Generate minute selection
1607 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1608 for ($idx = 0; $idx <= 59; $idx++) {
1609 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1610 if ($idx == $m) $OUT .= ' selected="selected"';
1611 $OUT .= '>' . $idx . '</option>';
1613 $OUT .= '</select></td>';
1615 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1618 if (isInString('s', $display) || (empty($display))) {
1619 // Generate second selection
1620 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1621 for ($idx = 0; $idx <= 59; $idx++) {
1622 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1623 if ($idx == $s) $OUT .= ' selected="selected"';
1624 $OUT .= '>' . $idx . '</option>';
1626 $OUT .= '</select></td>';
1628 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1635 // Return generated HTML code
1640 function createTimestampFromSelections ($prefix, $postData) {
1641 // Initial return value
1644 // Do we have a leap year?
1646 $TEST = date('Y', time()) / 4;
1647 $M1 = date('m', time());
1649 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1650 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
1652 // First add years...
1653 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1656 $ret += $postData[$prefix . '_mo'] * 2628000;
1659 $ret += $postData[$prefix . '_we'] * 604800;
1662 $ret += $postData[$prefix . '_da'] * 86400;
1665 $ret += $postData[$prefix . '_ho'] * 3600;
1668 $ret += $postData[$prefix . '_mi'] * 60;
1670 // And at last seconds...
1671 $ret += $postData[$prefix . '_se'];
1673 // Return calculated value
1677 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1678 function createFancyTime ($stamp) {
1679 // Get data array with years/months/weeks/days/...
1680 $data = createTimeSelections($stamp, '', '', '', true);
1682 foreach($data as $k => $v) {
1684 // Value is greater than 0 "eval" data to return string
1685 eval('$ret .= ", ".$v." {--_' . strtoupper($k) . '--}";');
1690 // Do we have something there?
1691 if (strlen($ret) > 0) {
1692 // Remove leading commata and space
1693 $ret = substr($ret, 2);
1696 $ret = '0 {--_SECONDS--}';
1699 // Return fancy time string
1703 // Extract host from script name
1704 function extractHostnameFromUrl (&$script) {
1705 // Use default SERVER_URL by default... ;) So?
1706 $url = getConfig('SERVER_URL');
1708 // Is this URL valid?
1709 if (substr($script, 0, 7) == 'http://') {
1710 // Use the hostname from script URL as new hostname
1711 $url = substr($script, 7);
1712 $extract = explode('/', $url);
1714 // Done extracting the URL :)
1717 // Extract host name
1718 $host = str_replace('http://', '', $url);
1719 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1721 // Generate relative URL
1722 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
1723 if (substr(strtolower($script), 0, 7) == 'http://') {
1724 // But only if http:// is in front!
1725 $script = substr($script, (strlen($url) + 7));
1726 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1728 $script = substr($script, (strlen($url) + 8));
1731 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
1732 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1738 // Send a GET request
1739 function sendGetRequest ($script, $data = array()) {
1740 // Extract host name from script
1741 $host = extractHostnameFromUrl($script);
1744 $body = http_build_query($data, '', '&');
1746 // Do we have a question-mark in the script?
1747 if (strpos($script, '?') === false) {
1748 // No, so first char must be question mark
1749 $body = '?' . $body;
1752 $body = '&' . $body;
1758 // Remove trailed & to make it more conform
1759 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
1761 // Generate GET request header
1762 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1763 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1764 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1765 if (isConfigEntrySet('FULL_VERSION')) {
1766 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1768 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1770 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
1771 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1772 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
1773 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1774 $request .= getConfig('HTTP_EOL');
1776 // Send the raw request
1777 $response = sendRawRequest($host, $request);
1779 // Return the result to the caller function
1783 // Send a POST request
1784 function sendPostRequest ($script, $postData) {
1785 // Is postData an array?
1786 if (!is_array($postData)) {
1788 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1789 return array('', '', '');
1792 // Extract host name from script
1793 $host = extractHostnameFromUrl($script);
1795 // Construct request body
1796 $body = http_build_query($postData, '', '&');
1798 // Generate POST request header
1799 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
1800 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1801 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1802 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1803 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1804 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1805 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1806 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1807 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
1808 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1809 $request .= getConfig('HTTP_EOL');
1814 // Send the raw request
1815 $response = sendRawRequest($host, $request);
1817 // Return the result to the caller function
1821 // Sends a raw request to another host
1822 function sendRawRequest ($host, $request) {
1823 // Init errno and errdesc with 'all fine' values
1824 $errno = '0'; $errdesc = '';
1827 $response = array('', '', '');
1829 // Default is not to use proxy
1832 // Are proxy settins set?
1833 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1839 loadIncludeOnce('inc/classes/resolver.class.php');
1841 // Get resolver instance
1842 $resolver = new HostnameResolver();
1845 //* DEBUG: */ die('SCRIPT=' . $script);
1846 if ($useProxy === true) {
1847 // Resolve hostname into IP address
1848 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
1850 // Connect to host through proxy connection
1851 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1853 // Resolve hostname into IP address
1854 $ip = $resolver->resolveHostname($host);
1856 // Connect to host directly
1857 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
1861 if (!is_resource($fp)) {
1863 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
1865 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
1866 // Cannot set non-blocking mode or timeout
1867 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
1872 if ($useProxy === true) {
1873 // Setup proxy tunnel
1874 $response = setupProxyTunnel($host, $fp);
1876 // If the response is invalid, abort
1877 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
1878 // Invalid response!
1879 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
1885 fwrite($fp, $request);
1888 $start = microtime(true);
1891 while (!feof($fp)) {
1892 // Get info from stream
1893 $info = stream_get_meta_data($fp);
1895 // Is it timed out? 15 seconds is a really patient...
1896 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1898 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1904 // Get line from stream
1905 $line = fgets($fp, 128);
1907 // Ignore empty lines because of non-blocking mode
1909 // uslepp a little to avoid 100% CPU load
1916 // Add it to response
1917 $response[] = trim($line);
1923 // Time request if debug-mode is enabled
1924 if (isDebugModeEnabled()) {
1925 // Add debug message...
1926 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1929 // Skip first empty lines
1931 foreach ($resp as $idx => $line) {
1933 $line = trim($line);
1935 // Is this line empty?
1938 array_shift($response);
1940 // Abort on first non-empty line
1945 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1946 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1948 // Proxy agent found or something went wrong?
1949 if (!isset($response[0])) {
1950 // No response, maybe timeout
1951 $response = array('', '', '');
1952 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1953 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1954 // Proxy header detected, so remove two lines
1955 array_shift($response);
1956 array_shift($response);
1959 // Was the request successfull?
1960 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1961 // Not found / access forbidden
1962 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1963 $response = array('', '', '');
1970 // Sets up a proxy tunnel for given hostname and through resource
1971 function setupProxyTunnel ($host, $resource) {
1973 $response = array('', '', '');
1975 // Generate CONNECT request header
1976 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
1977 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1979 // Use login data to proxy? (username at least!)
1980 if (getConfig('proxy_username') != '') {
1982 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1983 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1986 // Add last new-line
1987 $proxyTunnel .= getConfig('HTTP_EOL');
1988 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1991 fwrite($fp, $proxyTunnel);
1995 // No response received
1999 // Read the first line
2000 $resp = trim(fgets($fp, 10240));
2001 $respArray = explode(' ', $resp);
2002 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
2003 // Invalid response!
2011 // Taken from www.php.net isInStringIgnoreCase() user comments
2012 function isEmailValid ($email) {
2013 // Check first part of email address
2014 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
2017 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
2020 $regex = '@^' . $first . '\@' . $domain . '$@iU';
2022 // Return check result
2023 return preg_match($regex, $email);
2026 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2027 function isUrlValid ($URL, $compile=true) {
2028 // Trim URL a little
2029 $URL = trim(urldecode($URL));
2030 //* DEBUG: */ debugOutput($URL);
2032 // Compile some chars out...
2033 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
2034 //* DEBUG: */ debugOutput($URL);
2036 // Check for the extension filter
2037 if (isExtensionActive('filter')) {
2038 // Use the extension's filter set
2039 return FILTER_VALIDATE_URL($URL, false);
2042 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2043 // https:// in front of the URLs
2044 return isUrlValidSimple($URL);
2047 // Generate a list of administrative links to a given userid
2048 function generateMemberAdminActionLinks ($userid) {
2049 // Make sure userid is a number
2050 if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
2052 // Define all main targets
2053 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2056 $status = getFetchedUserData('userid', $userid, 'status');
2058 // Begin of navigation links
2061 foreach ($targetArray as $tar) {
2062 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
2063 //* DEBUG: */ debugOutput('*' . $tar.'/' . $status.'*');
2064 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2065 // Locked accounts shall be unlocked
2066 $OUT .= 'UNLOCK_USER';
2068 // All other status is fine
2069 $OUT .= strtoupper($tar);
2071 $OUT .= '_TITLE--}">{--ADMIN_';
2072 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2073 // Locked accounts shall be unlocked
2074 $OUT .= 'UNLOCK_USER';
2076 // All other status is fine
2077 $OUT .= strtoupper($tar);
2079 $OUT .= '--}</a></span>|';
2082 // Finish navigation link
2083 $OUT = substr($OUT, 0, -1) . ']';
2089 // Generate an email link
2090 function generateEmailLink ($email, $table = 'admins') {
2091 // Default email link (INSECURE! Spammer can read this by harvester programs)
2092 $EMAIL = 'mailto:' . $email;
2094 // Check for several extensions
2095 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2096 // Create email link for contacting admin in guest area
2097 $EMAIL = generateAdminEmailLink($email);
2098 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
2099 // Create email link for contacting a member within admin area (or later in other areas, too?)
2100 $EMAIL = generateUserEmailLink($email, 'admin');
2101 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2102 // Create email link to contact sponsor within admin area (or like the link above?)
2103 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2106 // Shall I close the link when there is no admin?
2107 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2109 // Return email link
2113 // Generate a hash for extra-security for all passwords
2114 function generateHash ($plainText, $salt = '', $hash = true) {
2116 //* DEBUG: */ debugOutput('plainText=' . $plainText . ',salt=' . $salt . ',hash='.intval($hash));
2118 // Is the required extension 'sql_patches' there and a salt is not given?
2119 // 0123 4 43 3 4 432 2 3 32 2 3 3210
2120 if ((((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')))) {
2121 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2122 if ($hash === true) {
2123 // Is plain password
2124 return md5($plainText);
2126 // Is already a hash
2131 // Do we miss an arry element here?
2132 if (!isConfigEntrySet('file_hash')) {
2134 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
2137 // When the salt is empty build a new one, else use the first x configured characters as the salt
2139 // Build server string for more entropy
2140 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2143 $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');
2146 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2148 // Calculate number for generating the code
2149 $a = time() + getConfig('_ADD') - 1;
2151 // Generate SHA1 sum from modula of number and the prime number
2152 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2153 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2154 $sha1 = scrambleString($sha1);
2155 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2156 //* DEBUG: */ $sha1b = descrambleString($sha1);
2157 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2159 // Generate the password salt string
2160 $salt = substr($sha1, 0, getConfig('salt_length'));
2161 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
2164 //* DEBUG: */ debugOutput('salt=' . $salt);
2165 $salt = substr($salt, 0, getConfig('salt_length'));
2166 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />');
2168 // Sanity check on salt
2169 if (strlen($salt) != getConfig('salt_length')) {
2171 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2175 // Generate final hash (for debug output)
2176 $finalHash = $salt . sha1($salt . $plainText);
2179 //* DEBUG: */ debugOutput('finalHash=' . $finalHash);
2185 // Scramble a string
2186 function scrambleString($str) {
2190 // Final check, in case of failture it will return unscrambled string
2191 if (strlen($str) > 40) {
2192 // The string is to long
2194 } elseif (strlen($str) == 40) {
2196 $scrambleNums = explode(':', getConfig('pass_scramble'));
2198 // Generate new numbers
2199 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2202 // Compare both lengths and abort if different
2203 if (strlen($str) != count($scrambleNums)) return $str;
2205 // Scramble string here
2206 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
2207 for ($idx = 0; $idx < strlen($str); $idx++) {
2208 // Get char on scrambled position
2209 $char = substr($str, $scrambleNums[$idx], 1);
2211 // Add it to final output string
2212 $scrambled .= $char;
2215 // Return scrambled string
2216 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
2220 // De-scramble a string scrambled by scrambleString()
2221 function descrambleString($str) {
2222 // Scramble only 40 chars long strings
2223 if (strlen($str) != 40) return $str;
2225 // Load numbers from config
2226 $scrambleNums = explode(':', getConfig('pass_scramble'));
2229 if (count($scrambleNums) != 40) return $str;
2231 // Begin descrambling
2232 $orig = str_repeat(' ', 40);
2233 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
2234 for ($idx = 0; $idx < 40; $idx++) {
2235 $char = substr($str, $idx, 1);
2236 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2239 // Return scrambled string
2240 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
2244 // Generated a "string" for scrambling
2245 function genScrambleString ($len) {
2246 // Prepare array for the numbers
2247 $scrambleNumbers = array();
2249 // First we need to setup randomized numbers from 0 to 31
2250 for ($idx = 0; $idx < $len; $idx++) {
2252 $rand = mt_rand(0, ($len -1));
2254 // Check for it by creating more numbers
2255 while (array_key_exists($rand, $scrambleNumbers)) {
2256 $rand = mt_rand(0, ($len -1));
2260 $scrambleNumbers[$rand] = $rand;
2263 // So let's create the string for storing it in database
2264 $scrambleString = implode(':', $scrambleNumbers);
2265 return $scrambleString;
2268 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2269 function encodeHashForCookie ($passHash) {
2270 // Return vanilla password hash
2273 // Is a secret key and master salt already initialized?
2274 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
2275 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2276 // Only calculate when the secret key is generated
2277 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getConfig('secret_key')));
2278 if ((strlen($passHash) != 49) || (strlen(getConfig('secret_key')) != 40)) {
2279 // Both keys must have same length so return unencrypted
2280 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getConfig('secret_key')) . '!=40');
2284 $newHash = ''; $start = 9;
2285 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
2286 for ($idx = 0; $idx < 20; $idx++) {
2287 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getConfig('secret_key'))), 2));
2288 $part2 = hexdec(substr(getConfig('secret_key'), $start, 2));
2289 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
2290 $mod = dechex($idx);
2291 if ($part1 > $part2) {
2292 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2293 } elseif ($part2 > $part1) {
2294 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2296 $mod = substr($mod, 0, 2);
2297 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
2298 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
2299 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
2304 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
2305 $ret = generateHash($newHash, getConfig('master_salt'));
2309 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
2313 // Fix "deleted" cookies
2314 function fixDeletedCookies ($cookies) {
2315 // Is this an array with entries?
2316 if ((is_array($cookies)) && (count($cookies) > 0)) {
2317 // Then check all cookies if they are marked as deleted!
2318 foreach ($cookies as $cookieName) {
2319 // Is the cookie set to "deleted"?
2320 if (getSession($cookieName) == 'deleted') {
2321 setSession($cookieName, '');
2327 // Output error messages in a fasioned way and die...
2328 function app_die ($F, $L, $message) {
2329 // Check if Script is already dieing and not let it kill itself another 1000 times
2330 if (!isset($GLOBALS['app_died'])) {
2331 // Make sure, that the script realy realy diese here and now
2332 $GLOBALS['app_died'] = true;
2334 // Set content type as text/html
2335 setContentType('text/html');
2338 loadIncludeOnce('inc/header.php');
2340 // Rewrite message for output
2341 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
2343 // Load the message template
2344 loadTemplate('app_die_message', false, $message);
2347 loadIncludeOnce('inc/footer.php');
2349 // Script tried to kill itself twice
2350 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2354 // Display parsing time and number of SQL queries in footer
2355 function displayParsingTime () {
2356 // Is the timer started?
2357 if (!isset($GLOBALS['startTime'])) {
2363 $endTime = microtime(true);
2365 // "Explode" both times
2366 $start = explode(' ', $GLOBALS['startTime']);
2367 $end = explode(' ', $endTime);
2368 $runTime = $end[0] - $start[0];
2369 if ($runTime < 0) $runTime = '0';
2372 // @TODO This can be easily moved out after the merge from EL branch to this is complete
2374 'run_time' => $runTime,
2375 'sql_time' => translateComma(getConfig('sql_time') * 1000),
2378 // Load the template
2379 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
2382 // Check wether a boolean constant is set
2383 // Taken from user comments in PHP documentation for function constant()
2384 function isBooleanConstantAndTrue ($constName) { // : Boolean
2385 // Failed by default
2389 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2391 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-CACHE!<br />");
2392 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2395 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-RESOLVE!<br />");
2396 if (defined($constName)) {
2398 //* DEBUG: */ debugOutput(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-FOUND!<br />");
2399 $res = (constant($constName) === true);
2403 $GLOBALS['cache_array']['const'][$constName] = $res;
2405 //* DEBUG: */ var_dump($res);
2411 // Checks if a given apache module is loaded
2412 function isApacheModuleLoaded ($apacheModule) {
2413 // Check it and return result
2414 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2417 // Get current theme name
2418 function getCurrentTheme () {
2419 // The default theme is 'default'... ;-)
2422 // Do we have ext-theme installed and active?
2423 if (isExtensionActive('theme')) {
2424 // Call inner method
2425 $ret = getActualTheme();
2428 // Return theme value
2432 // Generates an error code from given account status
2433 function generateErrorCodeFromUserStatus ($status='') {
2434 // If no status is provided, use the default, cached
2435 if ((empty($status)) && (isMember())) {
2437 $status = getUserData('status');
2440 // Default error code if unknown account status
2441 $errorCode = getCode('UNKNOWN_STATUS');
2443 // Generate constant name
2444 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2446 // Is the constant there?
2447 if (isCodeSet($codeName)) {
2449 $errorCode = getCode($codeName);
2452 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2455 // Return error code
2459 // Back-ported from the new ship-simu engine. :-)
2460 function debug_get_printable_backtrace () {
2462 $backtrace = '<ol>';
2464 // Get and prepare backtrace for output
2465 $backtraceArray = debug_backtrace();
2466 foreach ($backtraceArray as $key => $trace) {
2467 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2468 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2469 if (!isset($trace['args'])) $trace['args'] = array();
2470 $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>';
2474 $backtrace .= '</ol>';
2476 // Return the backtrace
2480 // A mail-able backtrace
2481 function debug_get_mailable_backtrace () {
2485 // Get and prepare backtrace for output
2486 $backtraceArray = debug_backtrace();
2487 foreach ($backtraceArray as $key => $trace) {
2488 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2489 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2490 if (!isset($trace['args'])) $trace['args'] = array();
2491 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2494 // Return the backtrace
2498 // Output a debug backtrace to the user
2499 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
2500 // Is this already called?
2501 if (isset($GLOBALS[__FUNCTION__])) {
2503 print 'Message:'.$message.'<br />Backtrace:<pre>';
2504 debug_print_backtrace();
2508 // Set this function as called
2509 $GLOBALS[__FUNCTION__] = true;
2514 // Is the optional message set?
2515 if (!empty($message)) {
2517 $debug = sprintf("Note: %s<br />\n",
2521 // @TODO Add a little more infos here
2522 logDebugMessage($F, $L, strip_tags($message));
2526 $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>';
2527 $debug .= debug_get_printable_backtrace();
2529 $debug .= '<div>Request-URI: ' . getRequestUri() . '</div>';
2530 $debug .= '<div>Thank you for finding bugs.</div>';
2532 // Send an email? (e.g. not wanted for evaluation errors)
2533 if (($sendEmail === true) && (!isInstallationPhase())) {
2536 'message' => trim($message),
2537 'backtrace' => trim(debug_get_mailable_backtrace())
2540 // Send email to webmaster
2541 sendAdminNotification('{--DEBUG_REPORT_BUG_SUBJECT--}', 'admin_report_bug', $content);
2545 app_die($F, $L, $debug);
2548 // Generates a ***weak*** seed
2549 function generateSeed () {
2550 return microtime(true) * 100000;
2553 // Converts a message code to a human-readable message
2554 function getMessageFromErrorCode ($code) {
2558 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
2559 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2560 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
2561 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
2562 case getCode('USER_404') : $message = '{--USER_404--}'; break;
2563 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
2564 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
2565 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
2566 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
2567 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
2568 case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
2569 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
2570 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
2571 case getCode('LOGIN_FAILED') : $message = '{--LOGIN_FAILED_GENERAL--}'; break;
2572 case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
2573 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
2574 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
2575 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
2576 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestParameter('blist'), 0); break;
2577 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
2578 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
2579 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
2580 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
2581 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
2582 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
2583 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
2584 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
2585 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
2586 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
2588 case getCode('ERROR_MAILID'):
2589 if (isExtensionActive('mailid', true)) {
2590 $message = '{--ERROR_CONFIRMING_MAIL--}';
2592 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', 'mailid');
2596 case getCode('EXTENSION_PROBLEM'):
2597 if (isGetRequestParameterSet('ext')) {
2598 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
2600 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
2604 case getCode('URL_TLOCK'):
2605 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2606 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2607 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
2609 // Load timestamp from last order
2610 list($timestamp) = SQL_FETCHROW($result);
2613 SQL_FREERESULT($result);
2615 // Translate it for templates
2616 $timestamp = generateDateTime($timestamp, 1);
2618 // Calculate hours...
2619 $STD = round(getConfig('url_tlock') / 60 / 60);
2622 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2625 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2627 // Finally contruct the message
2628 // @TODO Rewrite this old lost code to a template
2629 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2630 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2631 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2635 // Missing/invalid code
2636 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2639 logDebugMessage(__FUNCTION__, __LINE__, $message);
2643 // Return the message
2647 // Compile characters which are allowed in URLs
2648 function compileUriCode ($code, $simple = true) {
2649 // Compile constants
2650 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2652 // Compile QUOT and other non-HTML codes
2653 $code = str_replace('{DOT}', '.',
2654 str_replace('{SLASH}', '/',
2655 str_replace('{QUOT}', "'",
2656 str_replace('{DOLLAR}', '$',
2657 str_replace('{OPEN_ANCHOR}', '(',
2658 str_replace('{CLOSE_ANCHOR}', ')',
2659 str_replace('{OPEN_SQR}', '[',
2660 str_replace('{CLOSE_SQR}', ']',
2661 str_replace('{PER}', '%',
2665 // Return compiled code
2669 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2670 function isUrlValidSimple ($url) {
2672 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2674 // Allows http and https
2675 $http = "(http|https)+(:\/\/)";
2677 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2678 // Test double-domains (e.g. .de.vu)
2679 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2681 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2683 $dir = "((/)+([-_\.[:alnum:]])+)*";
2685 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2686 // ... and the string after and including question character
2687 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2688 // Pattern for URLs like http://url/dir/doc.html?var=value
2689 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2690 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2691 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2692 // Pattern for URLs like http://url/dir/?var=value
2693 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2694 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2695 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2696 // Pattern for URLs like http://url/dir/page.ext
2697 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2698 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2699 $pattern['ipdp'] = $http . $ip . $dir . $page;
2700 // Pattern for URLs like http://url/dir
2701 $pattern['d1d'] = $http . $domain1 . $dir;
2702 $pattern['d2d'] = $http . $domain2 . $dir;
2703 $pattern['ipd'] = $http . $ip . $dir;
2704 // Pattern for URLs like http://url/?var=value
2705 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2706 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2707 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2708 // Pattern for URLs like http://url?var=value
2709 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2710 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2711 $pattern['ipg12'] = $http . $ip . $getstring1;
2713 // Test all patterns
2715 foreach ($pattern as $key => $pat) {
2717 if (isDebugRegularExpressionEnabled()) {
2718 // @TODO Are these convertions still required?
2719 $pat = str_replace('.', "\.", $pat);
2720 $pat = str_replace('@', "\@", $pat);
2721 //* DEBUG: */ debugOutput($key."= " . $pat);
2724 // Check if expression matches
2725 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
2728 if ($reg === true) break;
2731 // Return true/false
2735 // Wtites data to a config.php-style file
2736 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2737 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2738 // Initialize some variables
2744 // Is the file there and read-/write-able?
2745 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2746 $search = 'CFG: ' . $comment;
2747 $tmp = $FQFN . '.tmp';
2749 // Open the source file
2750 $fp = fopen($FQFN, 'r') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
2752 // Is the resource valid?
2753 if (is_resource($fp)) {
2754 // Open temporary file
2755 $fp_tmp = fopen($tmp, 'w') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
2757 // Is the resource again valid?
2758 if (is_resource($fp_tmp)) {
2759 // Mark temporary file as readable
2760 $GLOBALS['file_readable'][$tmp] = true;
2763 while (!feof($fp)) {
2764 // Read from source file
2765 $line = fgets ($fp, 1024);
2767 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2770 if ($next === $seek) {
2772 $line = $prefix . $DATA . $suffix . "\n";
2778 // Write to temp file
2779 fwrite($fp_tmp, $line);
2785 // Finished writing tmp file
2789 // Close source file
2792 if (($done === true) && ($found === true)) {
2793 // Copy back tmp file and delete tmp :-)
2794 copyFileVerified($tmp, $FQFN, 0644);
2795 return removeFile($tmp);
2796 } elseif ($found === false) {
2797 outputHtml('<strong>CHANGE:</strong> 404!');
2799 outputHtml('<strong>TMP:</strong> UNDONE!');
2803 // File not found, not readable or writeable
2804 debug_report_bug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
2807 // An error was detected!
2810 // Send notification to admin
2811 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2812 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2814 sendAdminsEmails($subject, $templateName, $content, $userid);
2816 // Send out out-dated way
2817 $message = loadEmailTemplate($templateName, $content, $userid);
2818 sendAdminEmails($subject, $message);
2822 // Debug message logger
2823 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2824 // Is debug mode enabled?
2825 if ((isDebugModeEnabled()) || ($force === true)) {
2827 $message = str_replace("\r", '', str_replace("\n", '', $message));
2829 // Log this message away
2830 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write logfile debug.log!');
2831 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2836 // Handle extra values
2837 function handleExtraValues ($filterFunction, $value, $extraValue) {
2838 // Default is the value itself
2841 // Do we have a special filter function?
2842 if (!empty($filterFunction)) {
2843 // Does the filter function exist?
2844 if (function_exists($filterFunction)) {
2845 // Do we have extra parameters here?
2846 if (!empty($extraValue)) {
2847 // Put both parameters in one new array by default
2848 $args = array($value, $extraValue);
2850 // If we have an array simply use it and pre-extend it with our value
2851 if (is_array($extraValue)) {
2852 // Make the new args array
2853 $args = merge_array(array($value), $extraValue);
2856 // Call the multi-parameter call-back
2857 $ret = call_user_func_array($filterFunction, $args);
2859 // One parameter call
2860 $ret = call_user_func($filterFunction, $value);
2869 // Converts timestamp selections into a timestamp
2870 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2871 // Init test variable
2875 // Get last three chars
2876 $test = substr($id, -3);
2878 // Improved way of checking! :-)
2879 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2880 // Found a multi-selection for timings?
2881 $test = substr($id, 0, -3);
2882 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)) {
2883 // Generate timestamp
2884 $postData[$test] = createTimestampFromSelections($test, $postData);
2885 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2886 $GLOBALS['skip_config'][$test] = true;
2888 // Remove data from array
2889 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2890 unset($postData[$test . '_' . $rem]);
2901 // Reverts the german decimal comma into Computer decimal dot
2902 function convertCommaToDot ($str) {
2903 // Default float is not a float... ;-)
2906 // Which language is selected?
2907 switch (getLanguage()) {
2908 case 'de': // German language
2909 // Remove german thousand dots first
2910 $str = str_replace('.', '', $str);
2912 // Replace german commata with decimal dot and cast it
2913 $float = (float)str_replace(',', '.', $str);
2916 default: // US and so on
2917 // Remove thousand dots first and cast
2918 $float = (float)str_replace(',', '', $str);
2926 // Handle menu-depending failed logins and return the rendered content
2927 function handleLoginFailures ($accessLevel) {
2928 // Default output is empty ;-)
2931 // Is the session data set?
2932 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
2933 // Ignore zero values
2934 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
2935 // Non-guest has login failures found, get both data and prepare it for template
2936 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "accessLevel={$accessLevel}<br />");
2938 'login_failures' => getSession('mailer_' . $accessLevel . '_failures'),
2939 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
2943 $OUT = loadTemplate('login_failures', true, $content);
2946 // Reset session data
2947 setSession('mailer_' . $accessLevel . '_failures', '');
2948 setSession('mailer_' . $accessLevel . '_last_failure', '');
2951 // Return rendered content
2956 function rebuildCache ($cache, $inc = '', $force = false) {
2958 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
2960 // Shall I remove the cache file?
2961 if (isCacheInstanceValid()) {
2963 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2965 $GLOBALS['cache_instance']->removeCacheFile($force);
2968 // Include file given?
2971 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
2973 // Is the include there?
2974 if (isIncludeReadable($inc)) {
2975 // And rebuild it from scratch
2976 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
2979 // Include not found!
2980 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2986 // Determines the real remote address
2987 function determineRealRemoteAddress () {
2988 // Is a proxy in use?
2989 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2991 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
2992 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
2993 // Yet, another proxy
2994 $address = $_SERVER['HTTP_CLIENT_IP'];
2996 // The regular address when no proxy was used
2997 $address = $_SERVER['REMOTE_ADDR'];
3000 // This strips out the real address from proxy output
3001 if (strstr($address, ',')) {
3002 $addressArray = explode(',', $address);
3003 $address = $addressArray[0];
3006 // Return the result
3010 // Adds a bonus mail to the queue
3011 // This is a high-level function!
3012 function addNewBonusMail ($data, $mode = '', $output=true) {
3013 // Use mode from data if not set and availble ;-)
3014 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3016 // Generate receiver list
3017 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3020 if (!empty($receiver)) {
3021 // Add bonus mail to queue
3022 addBonusMailToQueue(
3034 // Mail inserted into bonus pool
3035 if ($output === true) {
3036 loadTemplate('admin_settings_saved', false, '{--ADMIN_BONUS_SEND--}');
3038 } elseif ($output === true) {
3039 // More entered than can be reached!
3040 loadTemplate('admin_settings_saved', false, '{--ADMIN_MORE_SELECTED--}');
3043 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
3047 // Determines referal id and sets it
3048 function determineReferalId () {
3049 // Skip this in non-html-mode and outside ref.php
3050 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3052 // Check if refid is set
3053 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3055 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3056 // The variable user comes from the click-counter script click.php and we only accept this here
3057 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
3058 } elseif (isPostRequestParameterSet('refid')) {
3059 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3060 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
3061 } elseif (isGetRequestParameterSet('refid')) {
3062 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3063 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
3064 } elseif (isGetRequestParameterSet('ref')) {
3065 // Set refid=ref (the referal link uses such variable)
3066 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
3067 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3068 // Set session refid als global
3069 $GLOBALS['refid'] = bigintval(getSession('refid'));
3070 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3071 // Select a random user which has confirmed enougth mails
3072 $GLOBALS['refid'] = determineRandomReferalId();
3073 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (getConfig('def_refid') > 0)) {
3074 // Set default refid as refid in URL
3075 $GLOBALS['refid'] = getConfig('def_refid');
3077 // No default id when sql_patches is not installed or none set
3078 $GLOBALS['refid'] = '0';
3081 // Set cookie when default refid > 0
3082 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3083 // Default is not found
3086 // Do we have nickname or userid set?
3087 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3088 // Nickname in URL, so load the id
3089 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3090 } elseif ($GLOBALS['refid'] > 0) {
3091 // Direct userid entered
3092 $found = fetchUserData($GLOBALS['refid']);
3095 // Is the record valid?
3096 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3097 // No, then reset referal id
3098 $GLOBALS['refid'] = getConfig('def_refid');
3102 setSession('refid', $GLOBALS['refid']);
3105 // Return determined refid
3106 return $GLOBALS['refid'];
3109 // Enables the reset mode and runs it
3110 function doReset () {
3111 // Enable the reset mode
3112 $GLOBALS['reset_enabled'] = true;
3115 runFilterChain('reset');
3118 // Our shutdown-function
3119 function shutdown () {
3120 // Call the filter chain 'shutdown'
3121 runFilterChain('shutdown', null);
3123 // Check if not in installation phase and the link is up
3124 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
3126 SQL_CLOSE(__FUNCTION__, __LINE__);
3127 } elseif (!isInstallationPhase()) {
3129 addFatalMessage(__FUNCTION__, __LINE__, '{--NO_DB_LINK_SHUTDOWN--}');
3132 // Stop executing here
3137 function initMemberId () {
3138 $GLOBALS['member_id'] = '0';
3141 // Setter for member id
3142 function setMemberId ($memberid) {
3143 // We should not set member id to zero
3144 if ($memberid == '0') debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
3147 $GLOBALS['member_id'] = bigintval($memberid);
3150 // Getter for member id or returns zero
3151 function getMemberId () {
3152 // Default member id
3155 // Is the member id set?
3156 if (isMemberIdSet()) {
3158 $memberid = $GLOBALS['member_id'];
3165 // Checks ether the member id is set
3166 function isMemberIdSet () {
3167 return (isset($GLOBALS['member_id']));
3170 // Handle message codes from URL
3171 function handleCodeMessage () {
3172 if (isGetRequestParameterSet('code')) {
3173 // Default extension is 'unknown'
3176 // Is extension given?
3177 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
3179 // Convert the 'code' parameter from URL to a human-readable message
3180 $message = getMessageFromErrorCode(getRequestParameter('code'));
3182 // Load message template
3183 loadTemplate('message', false, $message);
3187 // Setter for extra title
3188 function setExtraTitle ($extraTitle) {
3189 $GLOBALS['extra_title'] = $extraTitle;
3192 // Getter for extra title
3193 function getExtraTitle () {
3194 // Is the extra title set?
3195 if (!isExtraTitleSet()) {
3196 // No, then abort here
3197 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
3201 return $GLOBALS['extra_title'];
3204 // Checks if the extra title is set
3205 function isExtraTitleSet () {
3206 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3209 // Generates a 'extension foo inactive' message
3210 function generateExtensionInactiveMessage ($ext_name) {
3211 // Is the extension empty?
3212 if (empty($ext_name)) {
3213 // This should not happen
3214 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
3218 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3220 // Is an admin logged in?
3222 // Then output admin message
3223 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3226 // Return prepared message
3230 // Generates a 'extension foo not installed' message
3231 function generateExtensionNotInstalledMessage ($ext_name) {
3232 // Is the extension empty?
3233 if (empty($ext_name)) {
3234 // This should not happen
3235 debug_report_bug(__FUNCTION__, __LINE__, 'Parameter ext is empty. This should not happen.');
3239 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3241 // Is an admin logged in?
3243 // Then output admin message
3244 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3247 // Return prepared message
3251 // Generates a message depending on if the extension is not installed or not
3253 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3257 // Is the extension not installed or just deactivated?
3258 switch (isExtensionInstalled($ext_name)) {
3259 case true; // Deactivated!
3260 $message = generateExtensionInactiveMessage($ext_name);
3263 case false; // Not installed!
3264 $message = generateExtensionNotInstalledMessage($ext_name);
3267 default: // Should not happen!
3268 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3269 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3273 // Return the message
3277 // Reads a directory recursively by default and searches for files not matching
3278 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3279 // a whole directory.
3280 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3281 // Add default entries we should exclude
3282 $excludeArray[] = '.';
3283 $excludeArray[] = '..';
3284 $excludeArray[] = '.svn';
3285 $excludeArray[] = '.htaccess';
3287 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3292 $dirPointer = opendir(getConfig('PATH') . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3295 while ($baseFile = readdir($dirPointer)) {
3296 // Exclude '.', '..' and entries in $excludeArray automatically
3297 if (in_array($baseFile, $excludeArray, true)) {
3299 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
3303 // Construct include filename and FQFN
3304 $fileName = $baseDir . $baseFile;
3305 $FQFN = getConfig('PATH') . $fileName;
3307 // Remove double slashes
3308 $FQFN = str_replace('//', '/', $FQFN);
3310 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3311 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3312 // These Lines are only for debugging!!
3313 //* DEBUG: */ debugOutput('baseDir:' . $baseDir);
3314 //* DEBUG: */ debugOutput('baseFile:' . $baseFile);
3315 //* DEBUG: */ debugOutput('FQFN:' . $FQFN);
3321 // Skip also files with non-matching prefix genericly
3322 if (($recursive === true) && (isDirectory($FQFN))) {
3323 // Is a redirectory so read it as well
3324 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3326 // And skip further processing
3328 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3330 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3332 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3333 // Skip wrong suffix as well
3334 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3336 } elseif (!isFileReadable($FQFN)) {
3337 // Not readable so skip it
3338 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3342 // Is the file a PHP script or other?
3343 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3344 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3345 // Is this a valid include file?
3346 if ($extension == '.php') {
3347 // Remove both for extension name
3348 $extName = substr($baseFile, strlen($prefix), -4);
3350 // Is the extension valid and active?
3351 if (isExtensionNameValid($extName)) {
3352 // Then add this file
3353 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3354 $files[] = $fileName;
3356 // Add non-extension files as well
3357 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3358 if ($addBaseDir === true) {
3359 $files[] = $fileName;
3361 $files[] = $baseFile;
3365 // We found .php file but should not search for them, why?
3366 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
3368 } elseif (substr($baseFile, -4, 4) == $extension) {
3369 // Other, generic file found
3370 $files[] = $fileName;
3375 closedir($dirPointer);
3380 // Return array with include files
3381 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3385 // Maps a module name into a database table name
3386 function mapModuleToTable ($moduleName) {
3387 // Map only these, still lame code...
3388 switch ($moduleName) {
3389 // 'index' is the guest's menu
3390 case 'index': $moduleName = 'guest'; break;
3391 // ... and 'login' the member's menu
3392 case 'login': $moduleName = 'member'; break;
3393 // Anything else will not be mapped, silently.
3400 // Add SQL debug data to array for later output
3401 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3402 // Already executed?
3403 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3404 // Then abort here, we don't need to profile a query twice
3408 // Remeber this as profiled (or not, but we don't care here)
3409 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3411 // Do we have cache?
3412 if (!isset($GLOBALS['debug_sql_available'])) {
3413 // Check it and cache it in $GLOBALS
3414 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3417 // Don't execute anything here if we don't need or ext-other is missing
3418 if ($GLOBALS['debug_sql_available'] === false) {
3424 'num_rows' => SQL_NUMROWS($result),
3425 'affected' => SQL_AFFECTEDROWS(),
3426 'sql_str' => $sqlString,
3427 'timing' => $timing,
3428 'file' => basename($F),
3433 $GLOBALS['debug_sqls'][] = $record;
3436 // Initializes the cache instance
3437 function initCacheInstance () {
3438 // Load include for CacheSystem class
3439 loadIncludeOnce('inc/classes/cachesystem.class.php');
3441 // Initialize cache system only when it's needed
3442 $GLOBALS['cache_instance'] = new CacheSystem();
3443 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3444 // Failed to initialize cache sustem
3445 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_CANNOT_INITIALIZE--}');
3449 // Getter for message from array or raw message
3450 function getMessageFromIndexedArray ($message, $pos, $array) {
3451 // Check if the requested message was found in array
3452 if (isset($array[$pos])) {
3453 // ... if yes then use it!
3454 $ret = $array[$pos];
3456 // ... else use default message
3464 // Print code with line numbers
3465 function linenumberCode ($code) {
3466 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3467 $count_lines = count($codeE);
3469 $r = 'Line | Code:<br />';
3470 foreach($codeE as $line => $c) {
3471 $r .= '<div class="line"><span class="linenum">';
3472 if ($count_lines == 1) {
3475 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3480 $r .= '<span class="linetext">' . encodeEntities($c) . '</span></div>';
3483 return '<div class="code">' . $r . '</div>';
3486 // Convert ';' to ', ' for e.g. receiver list
3487 function convertReceivers ($old) {
3488 return str_replace(';', ', ', $old);
3491 // Determines the right page title
3492 function determinePageTitle () {
3493 // Config and database connection valid?
3494 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3498 // Title decoration enabled?
3499 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3501 // Do we have some extra title?
3502 if (isExtraTitleSet()) {
3504 $TITLE .= getExtraTitle() . ' by ';
3508 $TITLE .= getConfig('MAIN_TITLE');
3510 // Add title of module? (middle decoration will also be added!)
3511 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3512 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3515 // Add title from what file
3517 if (getModule() == 'login') $mode = 'member';
3518 elseif (getModule() == 'index') $mode = 'guest';
3519 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3521 // Add title decorations? (right)
3522 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3524 // Remember title in constant for the template
3525 $pageTitle = $TITLE;
3526 } elseif ((isInstalled()) && (isAdminRegistered())) {
3527 // Installed, admin registered but no ext-sql_patches
3528 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3529 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3530 // Installed but no admin registered
3531 $pageTitle = '{--SETUP_OF_MAILER--}';
3532 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3533 // Installation mode
3534 $pageTitle = '{--INSTALLATION_OF_MAILER--}';
3536 // Configuration not found!
3537 $pageTitle = '{--NO_CONFIG_FOUND_TITLE--}';
3539 // Do not add the fatal message in installation mode
3540 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, '{--NO_CONFIG_FOUND--}');
3544 return decodeEntities($pageTitle);
3547 // Checks wethere there is a cache file there. This function is cached.
3548 function isTemplateCached ($template) {
3549 // Do we have cached this result?
3550 if (!isset($GLOBALS['template_cache'][$template])) {
3552 $FQFN = generateCacheFqfn($template);
3555 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3559 return $GLOBALS['template_cache'][$template];
3562 // Flushes non-flushed template cache to disk
3563 function flushTemplateCache ($template, $eval) {
3564 // Is this cache flushed?
3565 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3567 $FQFN = generateCacheFqfn($template);
3570 writeToFile($FQFN, $eval, true);
3574 // Reads a template cache
3575 function readTemplateCache ($template) {
3577 if ((isDebuggingTemplateCache()) || (!isTemplateCached($template))) {
3578 // This should not happen
3579 debug_report_bug('Wether debugging of template cache is enabled or template ' . $template . ' is not cached while expected.');
3583 if (!isset($GLOBALS['template_eval'][$template])) {
3585 $FQFN = generateCacheFqfn($template);
3588 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3592 return $GLOBALS['template_eval'][$template];
3595 // Escapes quotes (default is only double-quotes)
3596 function escapeQuotes ($str, $single = false) {
3597 // Should we escape all?
3598 if ($single === true) {
3599 // Escape all (including null)
3600 $str = addslashes($str);
3602 // Escape only double-quotes but prevent double-quoting
3603 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3606 // Return the escaped string
3610 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3611 function escapeJavaScriptQuotes ($str) {
3612 // Replace all double-quotes and secure back-ticks
3613 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3619 // Send out mails depending on the 'mod/modes' combination
3620 // @TODO Lame description for this function
3621 function sendModeMails ($mod, $modes) {
3623 if (fetchUserData(getMemberId())) {
3624 // Extract salt from cookie
3625 $salt = substr(getSession('u_hash'), 0, -40);
3627 // Now let's compare passwords
3628 $hash = encodeHashForCookie(getUserData('password'));
3630 // Does the hash match or should we change it?
3631 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
3633 $content = getUserDataArray();
3635 // Clear/init the content variable
3636 $content['message'] = '';
3639 // @TODO Move this in a filter
3642 foreach ($modes as $mode) {
3644 case 'normal': break; // Do not add any special lines
3645 case 'email': // Email was changed!
3646 $content['message'] = '{--MEMBER_CHANGED_EMAIL--}' . ': ' . postRequestParameter('old_email') . "\n";
3649 case 'pass': // Password was changed
3650 $content['message'] = '{--MEMBER_CHANGED_PASS--}' . "\n";
3654 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3655 $content['message'] = '{--MEMBER_UNKNOWN_MODE--}' . ': ' . $mode . "\n\n";
3660 if (isExtensionActive('country')) {
3661 // Replace code with description
3662 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
3665 // Merge content with data from POST
3666 $content = merge_array($content, postRequestArray());
3669 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3671 if (getConfig('admin_notify') == 'Y') {
3672 // The admin needs to be notified about a profile change
3673 $message_admin = 'admin_mydata_notify';
3674 $sub_adm = '{--ADMIN_CHANGED_DATA--}';
3677 $message_admin = '';
3681 // Set subject lines
3682 $sub_mem = '{--MEMBER_CHANGED_DATA--}';
3684 // Output success message
3685 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3688 default: // Unsupported module!
3689 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3690 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
3694 // Passwords mismatch
3695 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
3698 // Could not load profile
3699 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
3702 // Send email to user if required
3703 if ((!empty($sub_mem)) && (!empty($message))) {
3705 sendEmail($content['email'], $sub_mem, $message);
3708 // Send only if no other error has occured
3709 if (empty($content)) {
3710 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3712 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3713 } elseif (getConfig('admin_notify') == 'Y') {
3714 // Cannot send mails to admin!
3715 $content = '{--CANNOT_SEND_ADMIN_MAILS--}';
3718 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3723 loadTemplate('admin_settings_saved', false, $content);
3726 // Generates a 'selection box' from given array
3727 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
3729 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3730 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3732 // Walk through all options
3733 foreach ($options as $option) {
3734 // Add the <option> entry
3735 if (empty($optionContent)) {
3736 // ... from template
3737 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
3740 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3744 // Finish selection box
3745 $OUT .= '</select>';
3749 'selection_box' => $OUT,
3750 'module' => getModule(),
3754 // Load template and return it
3755 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
3758 // Get a module from filename and access level
3759 function getModuleFromFileName ($file, $accessLevel) {
3760 // Default is 'invalid';
3761 $modCheck = 'invalid';
3763 // @TODO This is still very static, rewrite it somehow
3764 switch ($accessLevel) {
3766 $modCheck = 'admin';
3772 $modCheck = getModule();
3775 default: // Unsupported file name / access level
3776 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3784 // Encodes an URL for adding session id, etc.
3785 function encodeUrl ($url, $outputMode = '0') {
3786 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
3787 if ((strpos($url, session_name()) !== false) || (getOutputMode() == -3)) return $url;
3789 // Do we have a valid session?
3790 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3792 // Determine right seperator
3793 $seperator = '&';
3794 if (strpos($url, '?') === false) {
3797 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3803 if (session_id() != '') {
3804 $url .= $seperator . session_name() . '=' . session_id();
3809 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3811 $url = '{?URL?}/' . $url;
3818 // Simple check for spider
3819 function isSpider () {
3821 $userAgent = strtolower(detectUserAgent(true));
3823 // It should not be empty, if so it is better a spider/bot
3824 if (empty($userAgent)) return true;
3827 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
3830 // Prepares the header for HTML output
3831 function loadHtmlHeader () {
3833 // 1.) pre_page_header (mainly loads the page_header template and includes
3834 // meta description)
3835 runFilterChain('pre_page_header');
3837 // Here can be something be added, but normally one of the two filters
3838 // around this line should do the job for you.
3840 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
3841 // to close the head-tag)
3842 // Include more header data here
3843 runFilterChain('post_page_header');
3846 // Adds page header and footer to output array element
3847 function addPageHeaderFooter () {
3851 // Add them all together. This is maybe to simple
3852 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
3853 // Add page part if set
3854 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
3857 // Transfer $OUT to 'output'
3858 $GLOBALS['output'] = $OUT;
3861 // Generates meta description for current module and 'what' value
3862 function generateMetaDescriptionCode () {
3863 // Only include from guest area and if sql_patches has correct version
3864 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3865 // Construct dynamic description
3866 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
3868 // Output it directly
3869 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
3873 unset($GLOBALS['ref_level']);
3876 // Generates an FQFN for template cache from the given template name
3877 function generateCacheFqfn ($template, $mode = 'html') {
3879 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
3880 // Generate the FQFN
3881 $GLOBALS['template_cache_fqfn'][$template] = sprintf(
3882 "%s_compiled/%s/%s.tpl.cache",
3883 getConfig('CACHE_PATH'),
3890 return $GLOBALS['template_cache_fqfn'][$template];
3893 // Function to search for the last modified file
3894 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
3896 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
3897 // Does it match what we are looking for? (We skip a lot files already!)
3898 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
3899 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
3901 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
3902 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
3904 // Walk through all entries
3905 foreach ($ds as $d) {
3906 // Generate proper FQFN
3907 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir . '/' . $d);
3909 // Is it a file and readable?
3910 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
3911 if (isFileReadable($FQFN)) {
3912 // $FQFN is a readable file so extract the requested data from it
3913 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
3914 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
3916 // Is the file more recent?
3917 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
3918 // This file is newer as the file before
3919 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
3920 $last_changed['path_name'] = $FQFN;
3921 $last_changed[$lookFor] = $check;
3925 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
3930 // "Fixes" null or empty string to count of dashes
3931 function fixNullEmptyToDashes ($str, $num) {
3932 // Use str as default
3936 if ((is_null($str)) || (trim($str) == '')) {
3938 $return = str_repeat('-', $num);
3941 // Return final string
3945 // Handles the braces [] of a field (e.g. value of 'name' attribute)
3946 function handleFieldWithBraces ($field) {
3947 // Are there braces [] at the end?
3948 if (substr($field, -2, 2) == '[]') {
3949 // Try to find one and replace it. I do it this way to allow easy
3950 // extending of this code.
3951 foreach (array('admin_list_builder_id_value') as $key) {
3952 // Is the cache entry set?
3953 if (isset($GLOBALS[$key])) {
3955 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
3967 //////////////////////////////////////////////////
3968 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3969 //////////////////////////////////////////////////
3971 if (!function_exists('html_entity_decode')) {
3972 // Taken from documentation on www.php.net
3973 function html_entity_decode ($string) {
3974 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3975 $trans_tbl = array_flip($trans_tbl);
3976 return strtr($string, $trans_tbl);
3980 if (!function_exists('http_build_query')) {
3981 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
3982 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
3984 foreach ((array)$data as $k => $v) {
3985 if (is_int($k) && $prefix != null) {
3986 $k = urlencode($prefix . $k);
3989 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
3991 if (is_array($v) || is_object($v)) {
3992 array_push($ret, http_build_query($v, '', $sep, $k));
3994 array_push($ret, $k.'='.urlencode($v));
3998 if (empty($sep)) $sep = ini_get('arg_separator.output');
4000 return implode($sep, $ret);