2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/25/2003 *
4 * =================== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
46 function outputHtml ($htmlCode, $newLine = true) {
48 if (!isset($GLOBALS['output'])) $GLOBALS['output'] = '';
51 $username = getMessage('USERNAME_UNKNOWN');
52 if (isset($GLOBALS['username'])) $username = getUsername();
54 // Do we have HTML-Code here?
55 if (!empty($htmlCode)) {
56 // Yes, so we handle it as you have configured
57 switch (getConfig('OUTPUT_MODE')) {
59 // That's why you don't need any \n at the end of your HTML code... :-)
60 if (getPhpCaching() == 'on') {
61 // Output into PHP's internal buffer
62 outputRawCode($htmlCode);
64 // That's why you don't need any \n at the end of your HTML code... :-)
65 if ($newLine === true) print("\n");
67 // Render mode for old or lame servers...
68 $GLOBALS['output'] .= $htmlCode;
70 // That's why you don't need any \n at the end of your HTML code... :-)
71 if ($newLine === true) $GLOBALS['output'] .= "\n";
76 // If we are switching from render to direct output rendered code
77 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
79 // The same as above... ^
80 outputRawCode($htmlCode);
81 if ($newLine === true) print("\n");
85 // Huh, something goes wrong or maybe you have edited config.php ???
86 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
89 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
90 // Output cached HTML code
91 $GLOBALS['output'] = ob_get_contents();
93 // Clear output buffer for later output if output is found
94 if (!empty($GLOBALS['output'])) {
98 // Extension 'rewrite' installed?
99 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
100 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
103 // Send all HTTP headers
106 // Compile and run finished rendered HTML code
107 compileFinalOutput();
109 // Output code here, DO NOT REMOVE! ;-)
110 outputRawCode($GLOBALS['output']);
111 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
112 // Rewrite links when rewrite extension is active
113 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
114 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
117 // Send all HTTP headers
120 // Compile and run finished rendered HTML code
121 compileFinalOutput();
123 // Output code here, DO NOT REMOVE! ;-)
124 outputRawCode($GLOBALS['output']);
126 // And flush all headers
131 // Sends out all headers required for HTTP/1.1 reply
132 function sendHttpHeaders () {
134 $now = gmdate('D, d M Y H:i:s') . ' GMT';
137 sendHeader('HTTP/1.1 200');
139 // General headers for no caching
140 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
141 sendHeader('Last-Modified: ' . $now);
142 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
143 sendHeader('Pragma: no-cache'); // HTTP/1.0
144 sendHeader('Connection: Close');
145 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
146 sendHeader('Content-Language: ' . getLanguage());
149 // Compiles the final output
150 function compileFinalOutput () {
154 // Add page header and footer
155 addPageHeaderFooter();
158 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
159 // Init common variables
164 $eval = "\$newContent = \"".compileCode(escapeQuotes($GLOBALS['output']))."\";";
167 // Was that eval okay?
168 if (empty($newContent)) {
169 // Something went wrong!
170 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
172 $GLOBALS['output'] = $newContent;
179 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
180 // Compress it for HTTP gzip
181 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
184 sendHeader('Content-Encoding: gzip');
185 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
186 // Compress it for HTTP deflate
187 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
190 sendHeader('Content-Encoding: deflate');
194 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
200 // Output the raw HTML code
201 function outputRawCode ($htmlCode) {
202 // Output stripped HTML code to avoid broken JavaScript code, etc.
203 print(str_replace('{BACK}', "\\", $htmlCode));
205 // Flush the output if only getPhpCaching() is not 'on'
206 if (getPhpCaching() != 'on') {
212 // Init fatal message array
213 function initFatalMessages () {
214 $GLOBALS['fatal_messages'] = array();
217 // Getter for whole fatal error messages
218 function getFatalArray () {
219 return $GLOBALS['fatal_messages'];
222 // Add a fatal error message to the queue array
223 function addFatalMessage ($F, $L, $message, $extra = '') {
224 if (is_array($extra)) {
225 // Multiple extras for a message with masks
226 $message = call_user_func_array('sprintf', $extra);
227 } elseif (!empty($extra)) {
228 // $message is text with a mask plus extras to insert into the text
229 $message = sprintf($message, $extra);
232 // Add message to $GLOBALS['fatal_messages']
233 $GLOBALS['fatal_messages'][] = $message;
235 // Log fatal messages away
236 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
239 // Getter for total fatal message count
240 function getTotalFatalErrors () {
244 // Do we have at least the first entry?
245 if (!empty($GLOBALS['fatal_messages'][0])) {
247 $count = count($GLOBALS['fatal_messages']);
254 // Load a template file and return it's content (only it's name; do not use ' or ")
255 function loadTemplate ($template, $return = false, $content = array()) {
256 // @TODO Remove this sanity-check if all is fine
257 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
259 // @TODO Try to rewrite all $DATA to $content
263 if (isTemplateCached($template)) {
264 // Evaluate the cache
265 eval(readTemplateCache($template));
266 } elseif (!isset($GLOBALS['template_eval'][$template])) {
267 // Add more variables which you want to use in your template files
268 $username = getUsername();
270 // Make all template names lowercase
271 $template = strtolower($template);
275 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
278 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
279 $extraPath = detectExtraTemplatePath($template);;
281 ////////////////////////
282 // Generate file name //
283 ////////////////////////
284 $FQFN = $basePath . $extraPath . $template . '.tpl';
286 // Does the special template exists?
287 if (!isFileReadable($FQFN)) {
288 // Reset to default template
289 $FQFN = $basePath . $template . '.tpl';
292 // Now does the final template exists?
293 if (isFileReadable($FQFN)) {
294 // Count the template load
295 incrementConfigEntry('num_templates');
297 // The local file does exists so we load it. :)
298 $GLOBALS['tpl_content'] = readFromFile($FQFN);
300 // Do we have to compile the code?
302 if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false) || (strpos($GLOBALS['tpl_content'], '{%') !== false)) {
303 // Normal HTML output?
304 if (getOutputMode() == '0') {
305 // Add surrounding HTML comments to help finding bugs faster
306 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
308 // Prepare eval() command
309 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
310 } elseif (substr($template, 0, 3) == 'js_') {
311 // JavaScripts don't like entities and timings
312 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
314 // Prepare eval() command, other output doesn't like entities, maybe
315 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
318 // Add surrounding HTML comments to help finding bugs faster
319 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
320 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
323 // Cache the eval() command here
324 $GLOBALS['template_eval'][$template] = $eval;
327 eval($GLOBALS['template_eval'][$template]);
328 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
329 // Only admins shall see this warning or when installation mode is active
330 $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
331 (' . $template . ')<br />
333 {--TEMPLATE_CONTENT--}
334 <pre>' . print_r($content, true) . '</pre>
336 <pre>' . print_r($DATA, true) . '</pre>
340 $GLOBALS['template_eval'][$template] = '404';
344 eval($GLOBALS['template_eval'][$template]);
347 // Do we have some content to output or return?
349 // Not empty so let's put it out! ;)
350 if ($return === true) {
351 // Return the HTML code
357 } elseif (isDebugModeEnabled()) {
358 // Warning, empty output!
359 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
363 // Detects the extra template path from given template name
364 function detectExtraTemplatePath ($template) {
369 if (!isset($GLOBALS['extra_path'][$template])) {
370 // Check for admin/guest/member/etc. templates
371 if (substr($template, 0, 6) == 'admin_') {
372 // Admin template found
373 $extraPath = 'admin/';
374 } elseif (substr($template, 0, 6) == 'guest_') {
375 // Guest template found
376 $extraPath = 'guest/';
377 } elseif (substr($template, 0, 7) == 'member_') {
378 // Member template found
379 $extraPath = 'member/';
380 } elseif (substr($template, 0, 7) == 'select_') {
381 // Selection template found
382 $extraPath = 'select/';
383 } elseif (substr($template, 0, 8) == 'install_') {
384 // Installation template found
385 $extraPath = 'install/';
386 } elseif (substr($template, 0, 4) == 'ext_') {
387 // Extension template found
389 } elseif (substr($template, 0, 3) == 'la_') {
390 // 'Logical-area' template found
392 } elseif (substr($template, 0, 3) == 'js_') {
393 // JavaScript template found
395 } elseif (substr($template, 0, 5) == 'menu_') {
396 // Menu template found
397 $extraPath = 'menu/';
399 // Test for extension
400 $test = substr($template, 0, strpos($template, '_'));
402 // Probe for valid extension name
403 if (isExtensionNameValid($test)) {
404 // Set extra path to extension's name
405 $extraPath = $test . '/';
410 $GLOBALS['extra_path'][$template] = $extraPath;
414 return $GLOBALS['extra_path'][$template];
417 // Loads an email template and compiles it
418 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
421 // Make sure all template names are lowercase!
422 $template = strtolower($template);
424 // Default 'nickname' if extension is not installed
427 // Neutral email address is default
428 $email = getConfig('WEBMASTER');
430 // Is content an array?
431 if (is_array($content)) {
432 // Add expiration to array
433 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
434 // Will never expire!
435 $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
436 } elseif (isConfigEntrySet('auto_purge')) {
437 // Create nice date string
438 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
441 $content['expiration'] = getMessage('MAIL_NO_CONFIG_AUTO_PURGE');
446 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content).'<br />');
447 if (($userid > 0) && (is_array($content))) {
448 // If nickname extension is installed, fetch nickname as well
449 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
450 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
452 fetchUserData($userid, 'nickname');
454 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
456 fetchUserData($userid);
459 // Merge data if valid
460 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
461 if (isUserDataValid()) {
462 $content = merge_array($content, getUserDataArray());
464 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
467 // Translate M to male or F to female if present
468 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
470 // Overwrite email from data if present
471 if (isset($content['email'])) $email = $content['email'];
473 // Store email for some functions in global $DATA array
474 // @TODO Do only use $content, not $DATA or raw variables
475 $DATA['email'] = $email;
478 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
481 $extraPath = detectExtraTemplatePath($template);
483 // Generate full FQFN
484 $FQFN = $basePath . $extraPath . $template . '.tpl';
486 // Does the special template exists?
487 if (!isFileReadable($FQFN)) {
488 // Reset to default template
489 $FQFN = $basePath . $template . '.tpl';
492 // Now does the final template exists?
494 if (isFileReadable($FQFN)) {
495 // The local file does exists so we load it. :)
496 $GLOBALS['tpl_content'] = readFromFile($FQFN);
499 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
500 eval($GLOBALS['tpl_content']);
501 } elseif (!empty($template)) {
502 // Template file not found!
503 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
504 {--TEMPLATE_CONTENT--}
505 <pre>' . print_r($content, true) . '</pre>
507 <pre>' . print_r($DATA, true) . '</pre>
510 // Debug mode not active? Then remove the HTML tags
511 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
513 // No template name supplied!
514 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
517 // Is there some content?
518 if (empty($newContent)) {
520 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
522 // Add last error if the required function exists
523 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
526 // Remove content and data
534 // Send mail out to an email address
535 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
536 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail},SUBJECT={$subject}<br />");
538 // Compile subject line (for POINTS constant etc.)
539 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
542 if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
543 // Value detected, is the message extension installed?
544 // @TODO Extension 'msg' does not exist
545 if (isExtensionActive('msg')) {
546 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
549 // Does the user exist?
550 if (fetchUserData($toEmail)) {
552 $toEmail = getUserData('email');
555 $toEmail = getConfig('WEBMASTER');
558 } elseif ($toEmail == '0') {
560 $toEmail = getConfig('WEBMASTER');
562 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
564 // Check for PHPMailer or debug-mode
565 if (!checkPhpMailerUsage()) {
566 // Not in PHPMailer-Mode
567 if (empty($mailHeader)) {
568 // Load email header template
569 $mailHeader = loadEmailTemplate('header');
572 $mailHeader .= loadEmailTemplate('header');
574 } elseif (isDebugModeEnabled()) {
575 if (empty($mailHeader)) {
576 // Load email header template
577 $mailHeader = loadEmailTemplate('header');
580 $mailHeader .= loadEmailTemplate('header');
585 eval('$toEmail = "' . compileRawCode(escapeQuotes($toEmail)) . '";');
588 eval('$message = "' . str_replace('$', '$', compileRawCode(escapeQuotes($message))) . '";');
590 // Fix HTML parameter (default is no!)
591 if (empty($isHtml)) $isHtml = 'N';
592 if (isDebugModeEnabled()) {
593 // In debug mode we want to display the mail instead of sending it away so we can debug this part
595 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
596 To : ' . htmlentities(utf8_decode($toEmail)) . '
597 Subject : ' . htmlentities(utf8_decode($subject)) . '
598 Message : ' . htmlentities(utf8_decode($message)) . '
600 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
601 // Send mail as HTML away
602 return sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
603 } elseif (!empty($toEmail)) {
605 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
606 } elseif ($isHtml != 'Y') {
608 return sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
612 // Check to use wether legacy mail() command or PHPMailer class
613 // @TODO Rewrite this to an extension 'smtp'
615 function checkPhpMailerUsage() {
616 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
619 // Send out a raw email with PHPMailer class or legacy mail() command
620 function sendRawEmail ($toEmail, $subject, $message, $from) {
621 // Just compile all again, to put out all configs, etc.
622 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
623 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
624 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
625 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
627 // Shall we use PHPMailer class or legacy mode?
628 if (checkPhpMailerUsage()) {
629 // Use PHPMailer class with SMTP enabled
630 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
631 loadIncludeOnce('inc/phpmailer/class.smtp.php');
634 $mail = new PHPMailer();
636 // Set charset to UTF-8
637 $mail->CharSet = 'UTF-8';
639 // Path for PHPMailer
640 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
643 $mail->SMTPAuth = true;
644 $mail->Host = getConfig('SMTP_HOSTNAME');
646 $mail->Username = getConfig('SMTP_USER');
647 $mail->Password = getConfig('SMTP_PASSWORD');
649 $mail->From = getConfig('WEBMASTER');
653 $mail->FromName = getConfig('MAIN_TITLE');
654 $mail->Subject = $subject;
655 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
656 $mail->Body = $message;
657 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
658 $mail->WordWrap = 70;
661 $mail->Body = decodeEntities($message);
663 $mail->AddAddress($toEmail, '');
664 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
665 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
666 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
669 // Has an error occured?
670 if (!empty($mail->ErrorInfo)) {
672 logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
681 // Use legacy mail() command
682 return mail($toEmail, $subject, decodeEntities($message), $from);
686 // Generate a password in a specified length or use default password length
687 function generatePassword ($length = '0') {
688 // Auto-fix invalid length of zero
689 if ($length == '0') $length = getConfig('pass_len');
691 // Initialize array with all allowed chars
692 $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,-,+,_,/,.');
694 // Start creating password
696 for ($i = '0'; $i < $length; $i++) {
697 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
700 // When the size is below 40 we can also add additional security by scrambling
701 // it. Otherwise we may corrupt hashes
702 if (strlen($PASS) <= 40) {
703 // Also scramble the password
704 $PASS = scrambleString($PASS);
707 // Return the password
711 // Generates a human-readable timestamp from the Uni* stamp
712 function generateDateTime ($time, $mode = '0') {
713 // Filter out numbers
714 $time = bigintval($time);
716 // If the stamp is zero it mostly didn't "happen"
719 return getMessage('NEVER_HAPPENED');
722 switch (getLanguage()) {
723 case 'de': // German date / time format
725 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
726 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
727 case '2': $ret = date('d.m.Y|H:i', $time); break;
728 case '3': $ret = date('d.m.Y', $time); break;
730 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
735 default: // Default is the US date / time format!
737 case '0': $ret = date('r', $time); break;
738 case '1': $ret = date('Y-m-d - g:i A', $time); break;
739 case '2': $ret = date('y-m-d|H:i', $time); break;
740 case '3': $ret = date('y-m-d', $time); break;
742 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
751 // Translates Y/N to yes/no
752 function translateYesNo ($yn) {
754 $translated = '??? (' . $yn . ')';
756 case 'Y': $translated = getMessage('YES'); break;
757 case 'N': $translated = getMessage('NO'); break;
760 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
768 // Translates the "pool type" into human-readable
769 function translatePoolType ($type) {
770 // Default?type is unknown
771 $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
774 $constName = sprintf("POOL_TYPE_%s", $type);
777 if (isMessageIdValid($constName)) {
779 $translated = getMessage($constName);
782 // Return "translation"
786 // Translates the american decimal dot into a german comma
787 function translateComma ($dotted, $cut = true, $max = '0') {
788 // Default is 3 you can change this in admin area "Misc -> Misc Options"
789 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
791 // Use from config is default
792 $maxComma = getConfig('max_comma');
794 // Use from parameter?
795 if ($max > 0) $maxComma = $max;
798 if (($cut === true) && ($max == '0')) {
799 // Test for commata if in cut-mode
800 $com = explode('.', $dotted);
801 if (count($com) < 2) {
802 // Don't display commatas even if there are none... ;-)
808 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
811 switch (getLanguage()) {
812 case 'de': // German language
813 $dotted = number_format($dotted, $maxComma, ',', '.');
816 default: // All others
817 $dotted = number_format($dotted, $maxComma, '.', ',');
821 // Return translated value
825 // Translate Uni*-like gender to human-readable
826 function translateGender ($gender) {
828 $ret = '!' . $gender . '!';
830 // Male/female or company?
832 case 'M': $ret = getMessage('GENDER_M'); break;
833 case 'F': $ret = getMessage('GENDER_F'); break;
834 case 'C': $ret = getMessage('GENDER_C'); break;
836 // Please report bugs on unknown genders
837 debug_report_bug(sprintf("Unknown gender %s detected.", $gender));
841 // Return translated gender
845 // "Translates" the user status
846 function translateUserStatus ($status) {
847 // Generate message depending on status
852 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
857 $ret = getMessage('ACCOUNT_DELETED');
861 // Please report all unknown status
862 debug_report_bug(sprintf("Unknown status %s detected.", $status));
870 // Generates an URL for the dereferer
871 function generateDerefererUrl ($URL) {
872 // Don't de-refer our own links!
873 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
874 // De-refer this link
875 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
882 // Generates an URL for the frametester
883 function generateFrametesterUrl ($URL) {
884 // Prepare frametester URL
885 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
886 encodeString(compileUriCode($URL))
889 // Return the new URL
890 return $frametesterUrl;
893 // Count entries from e.g. a selection box
894 function countSelection ($array) {
896 if (!is_array($array)) {
898 debug_report_bug(__FUNCTION__.': No array provided.');
905 foreach ($array as $key => $selected) {
907 if (!empty($selected)) $ret++;
910 // Return counted selections
914 // Generate XHTML code for the CAPTCHA
915 function generateCaptchaCode ($code, $type, $DATA, $userid) {
916 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
919 // Generates a timestamp (some wrapper for mktime())
920 function makeTime ($hours, $minutes, $seconds, $stamp) {
921 // Extract day, month and year from given timestamp
922 $days = date('d', $stamp);
923 $months = date('m', $stamp);
924 $years = date('Y', $stamp);
926 // Create timestamp for wished time which depends on extracted date
937 // Redirects to an URL and if neccessarry extends it with own base URL
938 function redirectToUrl ($URL, $allowSpider = true) {
940 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
942 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
943 $rel = ' rel="external"';
945 // Do we have internal or external URL?
946 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
947 // Own (=internal) URL
951 // Three different ways to debug...
952 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
953 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
954 //* DEBUG: */ die($URL);
956 // Simple probe for bots/spiders from search engines
957 if ((isSpider()) && ($allowSpider === true)) {
958 // Secure the URL against bad things such als HTML insertions and so on...
959 $URL = secureString($URL);
961 // Set content-type here to fix a missing array element
962 setContentType('text/html');
964 // Output new location link as anchor
965 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
966 } elseif (!headers_sent()) {
967 // Clear own output buffer
968 $GLOBALS['output'] = '';
970 // Load URL when headers are not sent
971 sendHeader('Location: '.str_replace('&', '&', $URL));
973 // Output error message
974 loadInclude('inc/header.php');
975 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
976 loadInclude('inc/footer.php');
979 // Shut the mailer down here
983 // Wrapper for redirectToUrl but URL comes from a configuration entry
984 function redirectToConfiguredUrl ($configEntry) {
986 $URL = getConfig($configEntry);
991 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
998 // Compiles the given HTML/mail code
999 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1000 // Is the code a string?
1001 if (!is_string($code)) {
1002 // Silently return it
1007 $startCompile = microtime(true);
1010 $code = compileRawCode($code, $simple, $constants, $full);
1013 $compiled = microtime(true);
1016 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1018 // Return compiled code
1022 // Compiles the code (use compileCode() only for HTML because of the comments)
1023 // @TODO $simple is deprecated
1024 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1025 // Is the code a string?
1026 if (!is_string($code)) {
1027 // Silently return it
1031 // Init replacement-array with smaller set of security characters
1032 $secChars = $GLOBALS['url_chars'];
1034 // Select full set of chars to replace when we e.g. want to compile URLs
1035 if ($full === true) $secChars = $GLOBALS['security_chars'];
1037 // Compile more through a filter
1038 $code = runFilterChain('compile_code', $code);
1040 // Compile constants
1041 if ($constants === true) {
1042 // BEFORE 0.2.1 : Language and data constants
1043 // WITH 0.2.1+ : Only language constants
1044 $code = str_replace('{--', "\" . getMessage('", str_replace('--}', "') . \"", $code));
1046 // BEFORE 0.2.1 : Not used
1047 // WITH 0.2.1+ : Data constants
1048 $code = str_replace('{!', "\" . constant('", str_replace('!}', "') . \"", $code));
1051 // Compile QUOT and other non-HTML codes
1052 foreach ($secChars['to'] as $k => $to) {
1053 // Do the reversed thing as in inc/libs/security_functions.php
1054 $code = str_replace($to, $secChars['from'][$k], $code);
1057 // Find $content[bla][blub] entries
1058 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1059 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1061 // Are some matches found?
1062 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1063 // Replace all matches
1064 $matchesFound = array();
1065 foreach ($matches[0] as $key => $match) {
1066 // Fuzzy look has failed by default
1067 $fuzzyFound = false;
1069 // Fuzzy look on match if already found
1070 foreach ($matchesFound as $found => $set) {
1072 $test = substr($found, 0, strlen($match));
1074 // Does this entry exist?
1075 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
1076 if ($test == $match) {
1078 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
1085 if ($fuzzyFound === true) continue;
1087 // Take all string elements
1088 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1089 // Replace it in the code
1090 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
1091 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1092 $code = str_replace($match, '".' . $newMatch . '."', $code);
1093 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1094 $matchesFound[$match] = 1;
1095 } elseif (!isset($matchesFound[$match])) {
1096 // Not yet replaced!
1097 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
1098 $code = str_replace($match, '".' . $match . '."', $code);
1099 $matchesFound[$match] = 1;
1108 /************************************************************************
1110 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1111 * $a_sort sortiert: *
1113 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1114 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1115 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1116 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1117 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1119 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1120 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1121 * Sie, dass es doch nicht so schwer ist! :-) *
1123 ************************************************************************/
1124 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1126 while ($primary_key < count($a_sort)) {
1127 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1128 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1130 if ($nums === false) {
1131 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1132 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1133 } elseif ($key != $key2) {
1134 // Sort numbers (E.g.: 9 < 10)
1135 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1136 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1140 // We have found two different values, so let's sort whole array
1141 foreach ($dummy as $sort_key => $sort_val) {
1142 $t = $dummy[$sort_key][$key];
1143 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1144 $dummy[$sort_key][$key2] = $t;
1155 // Write back sorted array
1160 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1163 if ($type == 'yn') {
1164 // This is a yes/no selection only!
1165 if ($id > 0) $prefix .= "[" . $id."]";
1166 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1168 // Begin with regular selection box here
1169 if (!empty($prefix)) $prefix .= "_";
1171 if ($id > 0) $type2 .= "[" . $id."]";
1172 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1177 for ($idx = 1; $idx < 32; $idx++) {
1178 $OUT .= "<option value=\"" . $idx."\"";
1179 if ($default == $idx) $OUT .= ' selected="selected"';
1180 $OUT .= ">" . $idx."</option>\n";
1184 case 'month': // Month
1185 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1186 $OUT .= "<option value=\"" . $month."\"";
1187 if ($default == $month) $OUT .= ' selected="selected"';
1188 $OUT .= ">" . $descr."</option>\n";
1192 case 'year': // Year
1194 $year = date('Y', time());
1196 // Use configured min age or fixed?
1197 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1199 $startYear = $year - getConfig('min_age');
1202 $startYear = $year - 16;
1205 // Calculate earliest year (100 years old people can still enter Internet???)
1206 $minYear = $year - 100;
1208 // Check if the default value is larger than minimum and bigger than actual year
1209 if (($default > $minYear) && ($default >= $year)) {
1210 for ($idx = $year; $idx < ($year + 11); $idx++) {
1211 $OUT .= "<option value=\"" . $idx."\"";
1212 if ($default == $idx) $OUT .= ' selected="selected"';
1213 $OUT .= ">" . $idx."</option>\n";
1215 } elseif ($default == -1) {
1216 // Current year minus 1
1217 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1219 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1222 // Get current year and subtract the configured minimum age
1223 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1224 // Calculate earliest year depending on extension version
1225 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1226 // Use configured minimum age
1227 $year = date('Y', time()) - getConfig('min_age');
1229 // Use fixed 16 years age
1230 $year = date('Y', time()) - 16;
1233 // Construct year selection list
1234 for ($idx = $minYear; $idx <= $year; $idx++) {
1235 $OUT .= "<option value=\"" . $idx."\"";
1236 if ($default == $idx) $OUT .= ' selected="selected"';
1237 $OUT .= ">" . $idx."</option>\n";
1244 for ($idx = '0'; $idx < 60; $idx+=5) {
1245 if (strlen($idx) == 1) $idx = '0' . $idx;
1246 $OUT .= "<option value=\"" . $idx."\"";
1247 if ($default == $idx) $OUT .= ' selected="selected"';
1248 $OUT .= ">" . $idx."</option>\n";
1253 for ($idx = '0'; $idx < 24; $idx++) {
1254 if (strlen($idx) == 1) $idx = '0' . $idx;
1255 $OUT .= "<option value=\"" . $idx."\"";
1256 if ($default == $idx) $OUT .= ' selected="selected"';
1257 $OUT .= ">" . $idx."</option>\n";
1262 $OUT .= "<option value=\"Y\"";
1263 if ($default == 'Y') $OUT .= ' selected="selected"';
1264 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1265 if ($default != 'Y') $OUT .= ' selected="selected"';
1266 $OUT .= ">{--NO--}</option>\n";
1269 $OUT .= " </select>\n";
1274 // Deprecated : $length
1277 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1278 // Build server string
1279 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
1282 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1283 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1284 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1285 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1286 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1288 // Build string from misc data
1289 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1291 // Add more additional data
1292 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1294 // Add referal id, language, theme and userid
1295 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1296 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1297 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1298 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1300 // Calculate number for generating the code
1301 $a = $code + getConfig('_ADD') - 1;
1303 if (isConfigEntrySet('master_salt')) {
1304 // Generate hash with master salt from modula of number with the prime number and other data
1305 $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'));
1307 // Create number from hash
1308 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1310 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1311 $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')));
1313 // Create number from hash
1314 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1317 // At least 10 numbers shall be secure enought!
1318 $len = getConfig('code_length');
1319 if ($len == '0') $len = $length;
1320 if ($len == '0') $len = 10;
1322 // Cut off requested counts of number
1323 $return = substr(str_replace('.', '', $rcode), 0, $len);
1325 // Done building code
1329 // Does only allow numbers
1330 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
1331 // Filter all numbers out
1332 $ret = preg_replace('/[^0123456789]/', '', $num);
1335 if ($castValue === true) $ret = (double)$ret;
1337 // Has the whole value changed?
1338 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
1340 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1347 // Insert the code in $img_code into jpeg or PNG image
1348 function generateImageOrCode ($img_code, $headerSent = true) {
1349 // Is the code size oversized or shouldn't we display it?
1350 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1351 // Stop execution of function here because of over-sized code length
1352 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1353 } elseif ($headerSent === false) {
1354 // Return an HTML code here
1355 return "<img src=\"{%url=img.php?code=" . $img_code."%}\" alt=\"Image\" />\n";
1359 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1362 getConfig('img_type')
1366 if (isFileReadable($img)) {
1367 // Switch image type
1368 switch (getConfig('img_type'))
1371 // Okay, load image and hide all errors
1372 $image = imagecreatefromjpeg($img);
1376 // Okay, load image and hide all errors
1377 $image = imagecreatefrompng($img);
1381 // Exit function here
1382 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1386 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1387 $text_color = imagecolorallocate($image, 0, 0, 0);
1389 // Insert code into image
1390 imagestring($image, 5, 14, 2, $img_code, $text_color);
1392 // Return to browser
1393 sendHeader('Content-Type: image/' . getConfig('img_type'));
1395 // Output image with matching image factory
1396 switch (getConfig('img_type')) {
1397 case 'jpg': imagejpeg($image); break;
1398 case 'png': imagepng($image); break;
1401 // Remove image from memory
1402 imagedestroy($image);
1404 // Create selection box or array of splitted timestamp
1405 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1406 // Do not continue if ONE_DAY is absend
1407 if (!isConfigEntrySet('ONE_DAY')) {
1408 // And return the timestamp itself or empty array
1409 if ($return_array === true) {
1416 // Calculate 2-seconds timestamp
1417 $stamp = round($timestamp);
1418 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1420 // Do we have a leap year?
1422 $TEST = date('Y', time()) / 4;
1423 $M1 = date('m', time());
1424 $M2 = date('m', (time() + $timestamp));
1426 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1427 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1429 // First of all years...
1430 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1431 //* DEBUG: */ print("Y={$Y}<br />");
1433 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1434 //* DEBUG: */ print("M={$M}<br />");
1436 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1437 //* DEBUG: */ print("W={$W}<br />");
1439 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1440 //* DEBUG: */ print("D={$D}<br />");
1442 $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));
1443 //* DEBUG: */ print("h={$h}<br />");
1445 $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));
1446 //* DEBUG: */ print("m={$m}<br />");
1447 // And at last seconds...
1448 $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));
1449 //* DEBUG: */ print("s={$s}<br />");
1451 // Is seconds zero and time is < 60 seconds?
1452 if (($s == '0') && ($timestamp < 60)) {
1454 $s = round($timestamp);
1458 // Now we convert them in seconds...
1460 if ($return_array) {
1461 // Just put all data in an array for later use
1473 $OUT = "<div align=\"" . $align."\">\n";
1474 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"timebox_table dashed\">\n";
1477 if (isInString('Y', $display) || (empty($display))) {
1478 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1481 if (isInString('M', $display) || (empty($display))) {
1482 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1485 if (isInString('W', $display) || (empty($display))) {
1486 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1489 if (isInString('D', $display) || (empty($display))) {
1490 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1493 if (isInString('h', $display) || (empty($display))) {
1494 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1497 if (isInString('m', $display) || (empty($display))) {
1498 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1501 if (isInString('s', $display) || (empty($display))) {
1502 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1508 if (isInString('Y', $display) || (empty($display))) {
1509 // Generate year selection
1510 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ye\" size=\"1\">\n";
1511 for ($idx = '0'; $idx <= 10; $idx++) {
1512 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1513 if ($idx == $Y) $OUT .= ' selected="selected"';
1514 $OUT .= ">" . $idx."</option>\n";
1516 $OUT .= " </select></td>\n";
1518 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1521 if (isInString('M', $display) || (empty($display))) {
1522 // Generate month selection
1523 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mo\" size=\"1\">\n";
1524 for ($idx = '0'; $idx <= 11; $idx++)
1526 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1527 if ($idx == $M) $OUT .= ' selected="selected"';
1528 $OUT .= ">" . $idx."</option>\n";
1530 $OUT .= " </select></td>\n";
1532 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1535 if (isInString('W', $display) || (empty($display))) {
1536 // Generate week selection
1537 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_we\" size=\"1\">\n";
1538 for ($idx = '0'; $idx <= 4; $idx++) {
1539 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1540 if ($idx == $W) $OUT .= ' selected="selected"';
1541 $OUT .= ">" . $idx."</option>\n";
1543 $OUT .= " </select></td>\n";
1545 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1548 if (isInString('D', $display) || (empty($display))) {
1549 // Generate day selection
1550 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_da\" size=\"1\">\n";
1551 for ($idx = '0'; $idx <= 31; $idx++) {
1552 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1553 if ($idx == $D) $OUT .= ' selected="selected"';
1554 $OUT .= ">" . $idx."</option>\n";
1556 $OUT .= " </select></td>\n";
1558 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1561 if (isInString('h', $display) || (empty($display))) {
1562 // Generate hour selection
1563 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ho\" size=\"1\">\n";
1564 for ($idx = '0'; $idx <= 23; $idx++) {
1565 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1566 if ($idx == $h) $OUT .= ' selected="selected"';
1567 $OUT .= ">" . $idx."</option>\n";
1569 $OUT .= " </select></td>\n";
1571 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1574 if (isInString('m', $display) || (empty($display))) {
1575 // Generate minute selection
1576 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mi\" size=\"1\">\n";
1577 for ($idx = '0'; $idx <= 59; $idx++) {
1578 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1579 if ($idx == $m) $OUT .= ' selected="selected"';
1580 $OUT .= ">" . $idx."</option>\n";
1582 $OUT .= " </select></td>\n";
1584 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1587 if (isInString('s', $display) || (empty($display))) {
1588 // Generate second selection
1589 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_se\" size=\"1\">\n";
1590 for ($idx = '0'; $idx <= 59; $idx++) {
1591 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1592 if ($idx == $s) $OUT .= ' selected="selected"';
1593 $OUT .= ">" . $idx."</option>\n";
1595 $OUT .= " </select></td>\n";
1597 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1600 $OUT .= "</table>\n";
1602 // Return generated HTML code
1608 function createTimestampFromSelections ($prefix, $postData) {
1609 // Initial return value
1612 // Do we have a leap year?
1614 $TEST = date('Y', time()) / 4;
1615 $M1 = date('m', time());
1616 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1617 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
1618 // First add years...
1619 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1621 $ret += $postData[$prefix . '_mo'] * 2628000;
1623 $ret += $postData[$prefix . '_we'] * 604800;
1625 $ret += $postData[$prefix . '_da'] * 86400;
1627 $ret += $postData[$prefix . '_ho'] * 3600;
1629 $ret += $postData[$prefix . '_mi'] * 60;
1630 // And at last seconds...
1631 $ret += $postData[$prefix . '_se'];
1632 // Return calculated value
1636 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1637 function createFancyTime ($stamp) {
1638 // Get data array with years/months/weeks/days/...
1639 $data = createTimeSelections($stamp, '', '', '', true);
1641 foreach($data as $k => $v) {
1643 // Value is greater than 0 "eval" data to return string
1644 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1649 // Do we have something there?
1650 if (strlen($ret) > 0) {
1651 // Remove leading commata and space
1652 $ret = substr($ret, 2);
1655 $ret = "0 {--_SECONDS--}";
1658 // Return fancy time string
1662 // Generates a navigation row for listing emails
1663 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1665 if ($show_form === false) {
1670 for ($page = 1; $page <= $PAGES; $page++) {
1671 // Is the page currently selected or shall we generate a link to it?
1672 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1673 // Is currently selected, so only highlight it
1674 $NAV .= '<strong>-';
1676 // Open anchor tag and add base URL
1677 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1679 // Add userid when we shall show all mails from a single member
1680 if ((isGetRequestParameterSet('userid')) && (bigintval(getRequestParameter('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestParameter('userid'));
1682 // Close open anchor tag
1686 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1687 // Is currently selected, so only highlight it
1688 $NAV .= '-</strong>';
1694 // Add seperator if we have not yet reached total pages
1695 if ($page < $PAGES) $NAV .= ' | ';
1698 // Define constants only once
1699 $content['nav'] = $NAV;
1700 $content['span'] = $colspan;
1701 $content['top'] = $TOP;
1703 // Load navigation template
1704 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1706 if ($return === true) {
1707 // Return generated HTML-Code
1715 // Extract host from script name
1716 function extractHostnameFromUrl (&$script) {
1717 // Use default SERVER_URL by default... ;) So?
1718 $url = getConfig('SERVER_URL');
1720 // Is this URL valid?
1721 if (substr($script, 0, 7) == 'http://') {
1722 // Use the hostname from script URL as new hostname
1723 $url = substr($script, 7);
1724 $extract = explode('/', $url);
1726 // Done extracting the URL :)
1729 // Extract host name
1730 $host = str_replace('http://', '', $url);
1731 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1733 // Generate relative URL
1734 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1735 if (substr(strtolower($script), 0, 7) == 'http://') {
1736 // But only if http:// is in front!
1737 $script = substr($script, (strlen($url) + 7));
1738 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1740 $script = substr($script, (strlen($url) + 8));
1743 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1744 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1750 // Send a GET request
1751 function sendGetRequest ($script, $data = array()) {
1752 // Extract host name from script
1753 $host = extractHostnameFromUrl($script);
1756 $body = http_build_query($data, '', '&');
1758 // Do we have a question-mark in the script?
1759 if (strpos($script, '?') === false) {
1760 // No, so first char must be question mark
1761 $body = '?' . $body;
1764 $body = '&' . $body;
1770 // Remove trailed & to make it more conform
1771 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
1773 // Generate GET request header
1774 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1775 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1776 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1777 if (isConfigEntrySet('FULL_VERSION')) {
1778 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1780 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1782 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1783 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1784 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1785 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1786 $request .= 'Content-Length: 0' . getConfig('HTTP_EOL');
1787 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1788 $request .= getConfig('HTTP_EOL');
1790 // Send the raw request
1791 $response = sendRawRequest($host, $request);
1793 // Return the result to the caller function
1797 // Send a POST request
1798 function sendPostRequest ($script, $postData) {
1799 // Is postData an array?
1800 if (!is_array($postData)) {
1802 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1803 return array('', '', '');
1806 // Extract host name from script
1807 $host = extractHostnameFromUrl($script);
1809 // Construct request body
1810 $body = http_build_query($postData, '', '&');
1812 // Generate POST request header
1813 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1814 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1815 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1816 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1817 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1818 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1819 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1820 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1821 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
1822 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1823 $request .= getConfig('HTTP_EOL');
1828 // Send the raw request
1829 $response = sendRawRequest($host, $request);
1831 // Return the result to the caller function
1835 // Sends a raw request to another host
1836 function sendRawRequest ($host, $request) {
1837 // Init errno and errdesc with 'all fine' values
1838 $errno = '0'; $errdesc = '';
1841 $response = array('', '', '');
1843 // Default is not to use proxy
1846 // Are proxy settins set?
1847 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1853 loadIncludeOnce('inc/classes/resolver.class.php');
1855 // Get resolver instance
1856 $resolver = new HostnameResolver();
1859 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1860 if ($useProxy === true) {
1861 // Resolve hostname into IP address
1862 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
1864 // Connect to host through proxy connection
1865 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1867 // Resolve hostname into IP address
1868 $ip = $resolver->resolveHostname($host);
1870 // Connect to host directly
1871 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
1875 if (!is_resource($fp)) {
1877 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
1879 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
1880 // Cannot set non-blocking mode or timeout
1881 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
1886 if ($useProxy === true) {
1887 // Setup proxy tunnel
1888 $response = setupProxyTunnel($host, $fp);
1890 // If the response is invalid, abort
1891 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
1892 // Invalid response!
1893 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
1899 fwrite($fp, $request);
1902 $start = microtime(true);
1905 while (!feof($fp)) {
1906 // Get info from stream
1907 $info = stream_get_meta_data($fp);
1909 // Is it timed out? 15 seconds is a really patient...
1910 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1912 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1918 // Get line from stream
1919 $line = fgets($fp, 128);
1921 // Ignore empty lines because of non-blocking mode
1923 // uslepp a little to avoid 100% CPU load
1930 // Add it to response
1931 $response[] = trim($line);
1937 // Time request if debug-mode is enabled
1938 if (isDebugModeEnabled()) {
1939 // Add debug message...
1940 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1943 // Skip first empty lines
1945 foreach ($resp as $idx => $line) {
1947 $line = trim($line);
1949 // Is this line empty?
1952 array_shift($response);
1954 // Abort on first non-empty line
1959 //* DEBUG: */ print('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1960 //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1962 // Proxy agent found or something went wrong?
1963 if (!isset($response[0])) {
1964 // No response, maybe timeout
1965 $response = array('', '', '');
1966 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1967 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1968 // Proxy header detected, so remove two lines
1969 array_shift($response);
1970 array_shift($response);
1973 // Was the request successfull?
1974 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1975 // Not found / access forbidden
1976 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1977 $response = array('', '', '');
1984 // Sets up a proxy tunnel for given hostname and through resource
1985 function setupProxyTunnel ($host, $resource) {
1987 $response = array('', '', '');
1989 // Generate CONNECT request header
1990 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.1' . getConfig('HTTP_EOL');
1991 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1993 // Use login data to proxy? (username at least!)
1994 if (getConfig('proxy_username') != '') {
1996 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
1997 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
2000 // Add last new-line
2001 $proxyTunnel .= getConfig('HTTP_EOL');
2002 //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
2005 fwrite($fp, $proxyTunnel);
2009 // No response received
2013 // Read the first line
2014 $resp = trim(fgets($fp, 10240));
2015 $respArray = explode(' ', $resp);
2016 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
2017 // Invalid response!
2025 // Taken from www.php.net isInStringIgnoreCase() user comments
2026 function isEmailValid ($email) {
2027 // Check first part of email address
2028 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
2031 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
2034 $regex = '@^' . $first . '\@' . $domain . '$@iU';
2036 // Return check result
2037 return preg_match($regex, $email);
2040 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2041 function isUrlValid ($URL, $compile=true) {
2042 // Trim URL a little
2043 $URL = trim(urldecode($URL));
2044 //* DEBUG: */ outputHtml($URL.'<br />');
2046 // Compile some chars out...
2047 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
2048 //* DEBUG: */ outputHtml($URL.'<br />');
2050 // Check for the extension filter
2051 if (isExtensionActive('filter')) {
2052 // Use the extension's filter set
2053 return FILTER_VALIDATE_URL($URL, false);
2056 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2057 // https:// in front of the URLs
2058 return isUrlValidSimple($URL);
2061 // Generate a list of administrative links to a given userid
2062 function generateMemberAdminActionLinks ($userid, $status = '') {
2063 // Make sure userid is a number
2064 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
2066 // Define all main targets
2067 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2069 // Begin of navigation links
2072 foreach ($targetArray as $tar) {
2073 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
2074 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
2075 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2076 // Locked accounts shall be unlocked
2077 $OUT .= 'UNLOCK_USER';
2079 // All other status is fine
2080 $OUT .= strtoupper($tar);
2082 $OUT .= '_TITLE--}">{--ADMIN_';
2083 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2084 // Locked accounts shall be unlocked
2085 $OUT .= 'UNLOCK_USER';
2087 // All other status is fine
2088 $OUT .= strtoupper($tar);
2090 $OUT .= '--}</a></span> | ';
2093 // Finish navigation link
2094 $OUT = substr($OUT, 0, -7) . ']';
2100 // Generate an email link
2101 function generateEmailLink ($email, $table = 'admins') {
2102 // Default email link (INSECURE! Spammer can read this by harvester programs)
2103 $EMAIL = 'mailto:' . $email;
2105 // Check for several extensions
2106 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2107 // Create email link for contacting admin in guest area
2108 $EMAIL = generateAdminEmailLink($email);
2109 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2110 // Create email link for contacting a member within admin area (or later in other areas, too?)
2111 $EMAIL = generateUserEmailLink($email, 'admin');
2112 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2113 // Create email link to contact sponsor within admin area (or like the link above?)
2114 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2117 // Shall I close the link when there is no admin?
2118 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2120 // Return email link
2124 // Generate a hash for extra-security for all passwords
2125 function generateHash ($plainText, $salt = '', $hash = true) {
2127 //* DEBUG: */ outputHtml('plainText=' . $plainText . ',salt=' . $salt . ',hash='.intval($hash).'<br />');
2129 // Is the required extension 'sql_patches' there and a salt is not given?
2130 // 0123 4 43 3 4 432 2 3 32 2 3 3210
2131 if ((((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')))) {
2132 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2133 if ($hash === true) {
2134 // Is plain password
2135 return md5($plainText);
2137 // Is already a hash
2142 // Do we miss an arry element here?
2143 if (!isConfigEntrySet('file_hash')) {
2145 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2148 // When the salt is empty build a new one, else use the first x configured characters as the salt
2150 // Build server string for more entropy
2151 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2154 $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');
2157 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2159 // Calculate number for generating the code
2160 $a = time() + getConfig('_ADD') - 1;
2162 // Generate SHA1 sum from modula of number and the prime number
2163 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2164 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2165 $sha1 = scrambleString($sha1);
2166 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2167 //* DEBUG: */ $sha1b = descrambleString($sha1);
2168 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2170 // Generate the password salt string
2171 $salt = substr($sha1, 0, getConfig('salt_length'));
2172 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2175 //* DEBUG: */ outputHtml('salt=' . $salt . '<br />');
2176 $salt = substr($salt, 0, getConfig('salt_length'));
2177 //* DEBUG: */ outputHtml('salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />');
2179 // Sanity check on salt
2180 if (strlen($salt) != getConfig('salt_length')) {
2182 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2186 // Generate final hash (for debug output)
2187 $finalHash = $salt . sha1($salt . $plainText);
2190 //* DEBUG: */ outputHtml('finalHash=' . $finalHash);
2196 // Scramble a string
2197 function scrambleString($str) {
2201 // Final check, in case of failture it will return unscrambled string
2202 if (strlen($str) > 40) {
2203 // The string is to long
2205 } elseif (strlen($str) == 40) {
2207 $scrambleNums = explode(':', getConfig('pass_scramble'));
2209 // Generate new numbers
2210 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2213 // Compare both lengths and abort if different
2214 if (strlen($str) != count($scrambleNums)) return $str;
2216 // Scramble string here
2217 //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2218 for ($idx = '0'; $idx < strlen($str); $idx++) {
2219 // Get char on scrambled position
2220 $char = substr($str, $scrambleNums[$idx], 1);
2222 // Add it to final output string
2223 $scrambled .= $char;
2226 // Return scrambled string
2227 //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2231 // De-scramble a string scrambled by scrambleString()
2232 function descrambleString($str) {
2233 // Scramble only 40 chars long strings
2234 if (strlen($str) != 40) return $str;
2236 // Load numbers from config
2237 $scrambleNums = explode(':', getConfig('pass_scramble'));
2240 if (count($scrambleNums) != 40) return $str;
2242 // Begin descrambling
2243 $orig = str_repeat(' ', 40);
2244 //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2245 for ($idx = '0'; $idx < 40; $idx++) {
2246 $char = substr($str, $idx, 1);
2247 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2250 // Return scrambled string
2251 //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2255 // Generated a "string" for scrambling
2256 function genScrambleString ($len) {
2257 // Prepare array for the numbers
2258 $scrambleNumbers = array();
2260 // First we need to setup randomized numbers from 0 to 31
2261 for ($idx = '0'; $idx < $len; $idx++) {
2263 $rand = mt_rand(0, ($len -1));
2265 // Check for it by creating more numbers
2266 while (array_key_exists($rand, $scrambleNumbers)) {
2267 $rand = mt_rand(0, ($len -1));
2271 $scrambleNumbers[$rand] = $rand;
2274 // So let's create the string for storing it in database
2275 $scrambleString = implode(':', $scrambleNumbers);
2276 return $scrambleString;
2279 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2280 function encodeHashForCookie ($passHash) {
2281 // Return vanilla password hash
2284 // Is a secret key and master salt already initialized?
2285 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
2286 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2287 // Only calculate when the secret key is generated
2288 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getConfig('secret_key')));
2289 if ((strlen($passHash) != 49) || (strlen(getConfig('secret_key')) != 40)) {
2290 // Both keys must have same length so return unencrypted
2291 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getConfig('secret_key')) . '!=40');
2295 $newHash = ''; $start = 9;
2296 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
2297 for ($idx = 0; $idx < 20; $idx++) {
2298 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getConfig('secret_key'))), 2));
2299 $part2 = hexdec(substr(getConfig('secret_key'), $start, 2));
2300 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
2301 $mod = dechex($idx);
2302 if ($part1 > $part2) {
2303 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2304 } elseif ($part2 > $part1) {
2305 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2307 $mod = substr($mod, 0, 2);
2308 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
2309 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
2310 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
2315 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
2316 $ret = generateHash($newHash, getConfig('master_salt'));
2320 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
2324 // Fix "deleted" cookies
2325 function fixDeletedCookies ($cookies) {
2326 // Is this an array with entries?
2327 if ((is_array($cookies)) && (count($cookies) > 0)) {
2328 // Then check all cookies if they are marked as deleted!
2329 foreach ($cookies as $cookieName) {
2330 // Is the cookie set to "deleted"?
2331 if (getSession($cookieName) == 'deleted') {
2332 setSession($cookieName, '');
2338 // Output error messages in a fasioned way and die...
2339 function app_die ($F, $L, $message) {
2340 // Check if Script is already dieing and not let it kill itself another 1000 times
2341 if (!isset($GLOBALS['app_died'])) {
2342 // Make sure, that the script realy realy diese here and now
2343 $GLOBALS['app_died'] = true;
2345 // Set content type as text/html
2346 setContentType('text/html');
2349 loadIncludeOnce('inc/header.php');
2351 // Rewrite message for output
2352 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2354 // Better log this message away
2355 if ($F != 'debug_report_bug') logDebugMessage($F, $L, $message);
2357 // Load the message template
2358 loadTemplate('app_die_message', false, $message);
2361 loadIncludeOnce('inc/footer.php');
2363 // Script tried to kill itself twice
2364 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2368 // Display parsing time and number of SQL queries in footer
2369 function displayParsingTime() {
2370 // Is the timer started?
2371 if (!isset($GLOBALS['startTime'])) {
2377 $endTime = microtime(true);
2379 // "Explode" both times
2380 $start = explode(' ', $GLOBALS['startTime']);
2381 $end = explode(' ', $endTime);
2382 $runTime = $end[0] - $start[0];
2383 if ($runTime < 0) $runTime = '0';
2387 'runtime' => translateComma($runTime),
2388 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2391 // Load the template
2392 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
2395 // Check wether a boolean constant is set
2396 // Taken from user comments in PHP documentation for function constant()
2397 function isBooleanConstantAndTrue ($constName) { // : Boolean
2398 // Failed by default
2402 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2404 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-CACHE!<br />");
2405 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2408 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-RESOLVE!<br />");
2409 if (defined($constName)) {
2411 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-FOUND!<br />");
2412 $res = (constant($constName) === true);
2416 $GLOBALS['cache_array']['const'][$constName] = $res;
2418 //* DEBUG: */ var_dump($res);
2424 // Checks if a given apache module is loaded
2425 function isApacheModuleLoaded ($apacheModule) {
2426 // Check it and return result
2427 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2430 // Get current theme name
2431 function getCurrentTheme () {
2432 // The default theme is 'default'... ;-)
2435 // Do we have ext-theme installed and active?
2436 if (isExtensionActive('theme')) {
2437 // Call inner method
2438 $ret = getActualTheme();
2441 // Return theme value
2445 // Generates an error code from given account status
2446 function generateErrorCodeFromUserStatus ($status='') {
2447 // If no status is provided, use the default, cached
2448 if ((empty($status)) && (isMember())) {
2450 $status = getUserData('status');
2453 // Default error code if unknown account status
2454 $errorCode = getCode('UNKNOWN_STATUS');
2456 // Generate constant name
2457 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2459 // Is the constant there?
2460 if (isCodeSet($codeName)) {
2462 $errorCode = getCode($codeName);
2465 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2468 // Return error code
2472 // Back-ported from the new ship-simu engine. :-)
2473 function debug_get_printable_backtrace () {
2475 $backtrace = "<ol>\n";
2477 // Get and prepare backtrace for output
2478 $backtraceArray = debug_backtrace();
2479 foreach ($backtraceArray as $key => $trace) {
2480 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2481 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2482 if (!isset($trace['args'])) $trace['args'] = array();
2483 $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:" . $trace['line'].", <span class=\"backtrace_function\">" . $trace['function'].'('.count($trace['args']).")</span></li>\n";
2487 $backtrace .= "</ol>\n";
2489 // Return the backtrace
2493 // A mail-able backtrace
2494 function debug_get_mailable_backtrace () {
2498 // Get and prepare backtrace for output
2499 $backtraceArray = debug_backtrace();
2500 foreach ($backtraceArray as $key => $trace) {
2501 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2502 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2503 if (!isset($trace['args'])) $trace['args'] = array();
2504 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2507 // Return the backtrace
2511 // Output a debug backtrace to the user
2512 function debug_report_bug ($message = '', $sendEmail = true) {
2513 // Is this already called?
2514 if (isset($GLOBALS[__FUNCTION__])) {
2516 print 'Message:'.$message.'<br />Backtrace:<pre>';
2517 debug_print_backtrace();
2521 // Set this function as called
2522 $GLOBALS[__FUNCTION__] = true;
2527 // Is the optional message set?
2528 if (!empty($message)) {
2530 $debug = sprintf("Note: %s<br />\n",
2534 // @TODO Add a little more infos here
2535 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2539 $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>";
2540 $debug .= debug_get_printable_backtrace();
2541 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2542 $debug .= "Thank you for finding bugs.";
2544 // Send an email? (e.g. not wanted for evaluation errors)
2545 if (($sendEmail === true) && (!isInstallationPhase())) {
2548 'message' => trim($message),
2549 'backtrace' => trim(debug_get_mailable_backtrace())
2552 // Send email to webmaster
2553 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2557 app_die(__FUNCTION__, __LINE__, $debug);
2560 // Generates a ***weak*** seed
2561 function generateSeed () {
2562 return microtime(true) * 100000;
2565 // Converts a message code to a human-readable message
2566 function getMessageFromErrorCode ($code) {
2570 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2571 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2572 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2573 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2574 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2575 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2576 case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2577 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2578 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2579 case getCode('ACCOUNT_LOCKED') : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2580 case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2581 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2582 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2583 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2584 case getCode('MODULE_MEM_ONLY') : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestParameter('mod')); break;
2585 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2586 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2587 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2588 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestParameter('blist'), 0); break;
2589 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2590 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2591 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2592 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2593 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2594 case getCode('MORE_RECEIVERS3') : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
2595 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2596 case getCode('NO_MAIL_TYPE') : $message = getMessage('MEMBER_NO_MAIL_TYPE_SELECTED'); break;
2597 case getCode('UNKNOWN_ERROR') : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
2598 case getCode('UNKNOWN_STATUS') : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
2600 case getCode('ERROR_MAILID'):
2601 if (isExtensionActive('mailid', true)) {
2602 $message = getMessage('ERROR_CONFIRMING_MAIL');
2604 $message = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'mailid');
2608 case getCode('EXTENSION_PROBLEM'):
2609 if (isGetRequestParameterSet('ext')) {
2610 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
2612 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2616 case getCode('URL_TLOCK'):
2617 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2618 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2619 array(bigintval(getRequestParameter('id'))), __FILE__, __LINE__);
2621 // Load timestamp from last order
2622 list($timestamp) = SQL_FETCHROW($result);
2625 SQL_FREERESULT($result);
2627 // Translate it for templates
2628 $timestamp = generateDateTime($timestamp, 1);
2630 // Calculate hours...
2631 $STD = round(getConfig('url_tlock') / 60 / 60);
2634 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2637 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2639 // Finally contruct the message
2640 // @TODO Rewrite this old lost code to a template
2641 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2642 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2643 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2647 // Missing/invalid code
2648 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2651 logDebugMessage(__FUNCTION__, __LINE__, $message);
2655 // Return the message
2659 // Compile characters which are allowed in URLs
2660 function compileUriCode ($code, $simple = true) {
2661 // Compile constants
2662 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2664 // Compile QUOT and other non-HTML codes
2665 $code = str_replace('{DOT}', '.',
2666 str_replace('{SLASH}', '/',
2667 str_replace('{QUOT}', "'",
2668 str_replace('{DOLLAR}', '$',
2669 str_replace('{OPEN_ANCHOR}', '(',
2670 str_replace('{CLOSE_ANCHOR}', ')',
2671 str_replace('{OPEN_SQR}', '[',
2672 str_replace('{CLOSE_SQR}', ']',
2673 str_replace('{PER}', '%',
2677 // Return compiled code
2681 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2682 function isUrlValidSimple ($url) {
2684 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2686 // Allows http and https
2687 $http = "(http|https)+(:\/\/)";
2689 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2690 // Test double-domains (e.g. .de.vu)
2691 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2693 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2695 $dir = "((/)+([-_\.[:alnum:]])+)*";
2697 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2698 // ... and the string after and including question character
2699 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2700 // Pattern for URLs like http://url/dir/doc.html?var=value
2701 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2702 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2703 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2704 // Pattern for URLs like http://url/dir/?var=value
2705 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2706 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2707 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2708 // Pattern for URLs like http://url/dir/page.ext
2709 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2710 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2711 $pattern['ipdp'] = $http . $ip . $dir . $page;
2712 // Pattern for URLs like http://url/dir
2713 $pattern['d1d'] = $http . $domain1 . $dir;
2714 $pattern['d2d'] = $http . $domain2 . $dir;
2715 $pattern['ipd'] = $http . $ip . $dir;
2716 // Pattern for URLs like http://url/?var=value
2717 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2718 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2719 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2720 // Pattern for URLs like http://url?var=value
2721 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2722 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2723 $pattern['ipg12'] = $http . $ip . $getstring1;
2724 // Test all patterns
2726 foreach ($pattern as $key => $pat) {
2728 if (isDebugRegExpressionEnabled()) {
2729 // @TODO Are these convertions still required?
2730 $pat = str_replace('.', "\.", $pat);
2731 $pat = str_replace('@', "\@", $pat);
2732 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2735 // Check if expression matches
2736 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2739 if ($reg === true) break;
2742 // Return true/false
2746 // Wtites data to a config.php-style file
2747 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2748 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2749 // Initialize some variables
2755 // Is the file there and read-/write-able?
2756 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2757 $search = 'CFG: ' . $comment;
2758 $tmp = $FQFN . '.tmp';
2760 // Open the source file
2761 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2763 // Is the resource valid?
2764 if (is_resource($fp)) {
2765 // Open temporary file
2766 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2768 // Is the resource again valid?
2769 if (is_resource($fp_tmp)) {
2770 // Mark temporary file as readable
2771 $GLOBALS['file_readable'][$tmp] = true;
2774 while (!feof($fp)) {
2775 // Read from source file
2776 $line = fgets ($fp, 1024);
2778 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2781 if ($next === $seek) {
2783 $line = $prefix . $DATA . $suffix . "\n";
2789 // Write to temp file
2790 fwrite($fp_tmp, $line);
2796 // Finished writing tmp file
2800 // Close source file
2803 if (($done === true) && ($found === true)) {
2804 // Copy back tmp file and delete tmp :-)
2805 copyFileVerified($tmp, $FQFN, 0644);
2806 return removeFile($tmp);
2807 } elseif ($found === false) {
2808 outputHtml('<strong>CHANGE:</strong> 404!');
2810 outputHtml('<strong>TMP:</strong> UNDONE!');
2814 // File not found, not readable or writeable
2815 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2818 // An error was detected!
2821 // Send notification to admin
2822 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2823 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2825 sendAdminsEmails($subject, $templateName, $content, $userid);
2827 // Send out out-dated way
2828 $message = loadEmailTemplate($templateName, $content, $userid);
2829 sendAdminEmails($subject, $message);
2833 // Debug message logger
2834 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2835 // Is debug mode enabled?
2836 if ((isDebugModeEnabled()) || ($force === true)) {
2838 $message = str_replace("\r", '', str_replace("\n", '', $message));
2840 // Log this message away, we better don't call app_die() here to prevent an endless loop
2841 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2842 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2847 // Handle extra values
2848 function handleExtraValues ($filterFunction, $value, $extraValue) {
2849 // Default is the value itself
2852 // Do we have a special filter function?
2853 if (!empty($filterFunction)) {
2854 // Does the filter function exist?
2855 if (function_exists($filterFunction)) {
2856 // Do we have extra parameters here?
2857 if (!empty($extraValue)) {
2858 // Put both parameters in one new array by default
2859 $args = array($value, $extraValue);
2861 // If we have an array simply use it and pre-extend it with our value
2862 if (is_array($extraValue)) {
2863 // Make the new args array
2864 $args = merge_array(array($value), $extraValue);
2867 // Call the multi-parameter call-back
2868 $ret = call_user_func_array($filterFunction, $args);
2870 // One parameter call
2871 $ret = call_user_func($filterFunction, $value);
2880 // Converts timestamp selections into a timestamp
2881 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2882 // Init test variable
2886 // Get last three chars
2887 $test = substr($id, -3);
2889 // Improved way of checking! :-)
2890 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2891 // Found a multi-selection for timings?
2892 $test = substr($id, 0, -3);
2893 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)) {
2894 // Generate timestamp
2895 $postData[$test] = createTimestampFromSelections($test, $postData);
2896 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2897 $GLOBALS['skip_config'][$test] = true;
2899 // Remove data from array
2900 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2901 unset($postData[$test . '_' . $rem]);
2912 // Reverts the german decimal comma into Computer decimal dot
2913 function convertCommaToDot ($str) {
2914 // Default float is not a float... ;-)
2917 // Which language is selected?
2918 switch (getLanguage()) {
2919 case 'de': // German language
2920 // Remove german thousand dots first
2921 $str = str_replace('.', '', $str);
2923 // Replace german commata with decimal dot and cast it
2924 $float = (float)str_replace(',', '.', $str);
2927 default: // US and so on
2928 // Remove thousand dots first and cast
2929 $float = (float)str_replace(',', '', $str);
2937 // Handle menu-depending failed logins and return the rendered content
2938 function handleLoginFailures ($accessLevel) {
2939 // Default output is empty ;-)
2942 // Is the session data set?
2943 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
2944 // Ignore zero values
2945 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
2946 // Non-guest has login failures found, get both data and prepare it for template
2947 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "accessLevel={$accessLevel}<br />");
2949 'login_failures' => getSession('mailer_' . $accessLevel . '_failures'),
2950 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
2954 $OUT = loadTemplate('login_failures', true, $content);
2957 // Reset session data
2958 setSession('mailer_' . $accessLevel . '_failures', '');
2959 setSession('mailer_' . $accessLevel . '_last_failure', '');
2962 // Return rendered content
2967 function rebuildCache ($cache, $inc = '', $force = false) {
2969 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
2971 // Shall I remove the cache file?
2972 if (isCacheInstanceValid()) {
2974 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2976 $GLOBALS['cache_instance']->removeCacheFile($force);
2979 // Include file given?
2982 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
2984 // Is the include there?
2985 if (isIncludeReadable($inc)) {
2986 // And rebuild it from scratch
2987 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
2990 // Include not found!
2991 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2997 // Determines the real remote address
2998 function determineRealRemoteAddress () {
2999 // Is a proxy in use?
3000 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3002 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3003 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3004 // Yet, another proxy
3005 $address = $_SERVER['HTTP_CLIENT_IP'];
3007 // The regular address when no proxy was used
3008 $address = $_SERVER['REMOTE_ADDR'];
3011 // This strips out the real address from proxy output
3012 if (strstr($address, ',')) {
3013 $addressArray = explode(',', $address);
3014 $address = $addressArray[0];
3017 // Return the result
3021 // Adds a bonus mail to the queue
3022 // This is a high-level function!
3023 function addNewBonusMail ($data, $mode = '', $output=true) {
3024 // Use mode from data if not set and availble ;-)
3025 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3027 // Generate receiver list
3028 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3031 if (!empty($receiver)) {
3032 // Add bonus mail to queue
3033 addBonusMailToQueue(
3045 // Mail inserted into bonus pool
3046 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3047 } elseif ($output) {
3048 // More entered than can be reached!
3049 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3052 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3056 // Determines referal id and sets it
3057 function determineReferalId () {
3058 // Skip this in non-html-mode and outside ref.php
3059 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3061 // Check if refid is set
3062 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3064 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3065 // The variable user comes from the click-counter script click.php and we only accept this here
3066 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
3067 } elseif (isPostRequestParameterSet('refid')) {
3068 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3069 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
3070 } elseif (isGetRequestParameterSet('refid')) {
3071 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3072 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
3073 } elseif (isGetRequestParameterSet('ref')) {
3074 // Set refid=ref (the referal link uses such variable)
3075 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
3076 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3077 // Set session refid als global
3078 $GLOBALS['refid'] = bigintval(getSession('refid'));
3079 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3080 // Select a random user which has confirmed enougth mails
3081 $GLOBALS['refid'] = determineRandomReferalId();
3082 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3083 // Set default refid as refid in URL
3084 $GLOBALS['refid'] = getConfig('def_refid');
3086 // No default id when sql_patches is not installed or none set
3087 $GLOBALS['refid'] = '0';
3090 // Set cookie when default refid > 0
3091 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3092 // Default is not found
3095 // Do we have nickname or userid set?
3096 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3097 // Nickname in URL, so load the id
3098 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3099 } elseif ($GLOBALS['refid'] > 0) {
3100 // Direct userid entered
3101 $found = fetchUserData($GLOBALS['refid']);
3104 // Is the record valid?
3105 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3106 // No, then reset referal id
3107 $GLOBALS['refid'] = getConfig('def_refid');
3111 setSession('refid', $GLOBALS['refid']);
3114 // Return determined refid
3115 return $GLOBALS['refid'];
3118 // Enables the reset mode and runs it
3119 function doReset () {
3120 // Enable the reset mode
3121 $GLOBALS['reset_enabled'] = true;
3124 runFilterChain('reset');
3127 // Our shutdown-function
3128 function shutdown () {
3129 // Call the filter chain 'shutdown'
3130 runFilterChain('shutdown', null);
3132 // Check if not in installation phase and the link is up
3133 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
3135 SQL_CLOSE(__FILE__, __LINE__);
3136 } elseif (!isInstallationPhase()) {
3138 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3141 // Stop executing here
3146 function initMemberId () {
3147 $GLOBALS['member_id'] = '0';
3150 // Setter for member id
3151 function setMemberId ($memberid) {
3152 // We should not set member id to zero
3153 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3156 $GLOBALS['member_id'] = bigintval($memberid);
3159 // Getter for member id or returns zero
3160 function getMemberId () {
3161 // Default member id
3164 // Is the member id set?
3165 if (isMemberIdSet()) {
3167 $memberid = $GLOBALS['member_id'];
3174 // Checks ether the member id is set
3175 function isMemberIdSet () {
3176 return (isset($GLOBALS['member_id']));
3179 // Handle message codes from URL
3180 function handleCodeMessage () {
3181 if (isGetRequestParameterSet('code')) {
3182 // Default extension is 'unknown'
3185 // Is extension given?
3186 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
3188 // Convert the 'code' parameter from URL to a human-readable message
3189 $message = getMessageFromErrorCode(getRequestParameter('code'));
3191 // Load message template
3192 loadTemplate('message', false, $message);
3196 // Setter for extra title
3197 function setExtraTitle ($extraTitle) {
3198 $GLOBALS['extra_title'] = $extraTitle;
3201 // Getter for extra title
3202 function getExtraTitle () {
3203 // Is the extra title set?
3204 if (!isExtraTitleSet()) {
3205 // No, then abort here
3206 debug_report_bug('extra_title is not set!');
3210 return $GLOBALS['extra_title'];
3213 // Checks if the extra title is set
3214 function isExtraTitleSet () {
3215 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3218 // Generates a 'extension foo inactive' message
3219 function generateExtensionInactiveMessage ($ext_name) {
3220 // Is the extension empty?
3221 if (empty($ext_name)) {
3222 // This should not happen
3223 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3227 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3229 // Is an admin logged in?
3231 // Then output admin message
3232 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3235 // Return prepared message
3239 // Generates a 'extension foo not installed' message
3240 function generateExtensionNotInstalledMessage ($ext_name) {
3241 // Is the extension empty?
3242 if (empty($ext_name)) {
3243 // This should not happen
3244 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3248 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3250 // Is an admin logged in?
3252 // Then output admin message
3253 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3256 // Return prepared message
3260 // Generates a message depending on if the extension is not installed or not
3262 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3266 // Is the extension not installed or just deactivated?
3267 switch (isExtensionInstalled($ext_name)) {
3268 case true; // Deactivated!
3269 $message = generateExtensionInactiveMessage($ext_name);
3272 case false; // Not installed!
3273 $message = generateExtensionNotInstalledMessage($ext_name);
3276 default: // Should not happen!
3277 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3278 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3282 // Return the message
3286 // Reads a directory recursively by default and searches for files not matching
3287 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3288 // a whole directory.
3289 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3290 // Add default entries we should exclude
3291 $excludeArray[] = '.';
3292 $excludeArray[] = '..';
3293 $excludeArray[] = '.svn';
3294 $excludeArray[] = '.htaccess';
3296 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3301 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3304 while ($baseFile = readdir($dirPointer)) {
3305 // Exclude '.', '..' and entries in $excludeArray automatically
3306 if (in_array($baseFile, $excludeArray, true)) {
3308 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3312 // Construct include filename and FQFN
3313 $fileName = $baseDir . $baseFile;
3314 $FQFN = getConfig('PATH') . $fileName;
3316 // Remove double slashes
3317 $FQFN = str_replace('//', '/', $FQFN);
3319 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3320 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3321 // These Lines are only for debugging!!
3322 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3323 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3324 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3330 // Skip also files with non-matching prefix genericly
3331 if (($recursive === true) && (isDirectory($FQFN))) {
3332 // Is a redirectory so read it as well
3333 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3335 // And skip further processing
3337 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3339 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3341 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3342 // Skip wrong suffix as well
3343 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3345 } elseif (!isFileReadable($FQFN)) {
3346 // Not readable so skip it
3347 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3351 // Is the file a PHP script or other?
3352 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3353 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3354 // Is this a valid include file?
3355 if ($extension == '.php') {
3356 // Remove both for extension name
3357 $extName = substr($baseFile, strlen($prefix), -4);
3359 // Is the extension valid and active?
3360 if (isExtensionNameValid($extName)) {
3361 // Then add this file
3362 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3363 $files[] = $fileName;
3365 // Add non-extension files as well
3366 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3367 if ($addBaseDir === true) {
3368 $files[] = $fileName;
3370 $files[] = $baseFile;
3374 // We found .php file but should not search for them, why?
3375 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3377 } elseif (substr($baseFile, -4, 4) == $extension) {
3378 // Other, generic file found
3379 $files[] = $fileName;
3384 closedir($dirPointer);
3389 // Return array with include files
3390 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3394 // Maps a module name into a database table name
3395 function mapModuleToTable ($moduleName) {
3396 // Map only these, still lame code...
3397 switch ($moduleName) {
3398 // 'index' is the guest's menu
3399 case 'index': $moduleName = 'guest'; break;
3400 // ... and 'login' the member's menu
3401 case 'login': $moduleName = 'member'; break;
3402 // Anything else will not be mapped, silently.
3409 // Add SQL debug data to array for later output
3410 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3411 // Already executed?
3412 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3413 // Then abort here, we don't need to profile a query twice
3417 // Remeber this as profiled (or not, but we don't care here)
3418 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3420 // Do we have cache?
3421 if (!isset($GLOBALS['debug_sql_available'])) {
3422 // Check it and cache it in $GLOBALS
3423 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3426 // Don't execute anything here if we don't need or ext-other is missing
3427 if ($GLOBALS['debug_sql_available'] === false) {
3433 'num_rows' => SQL_NUMROWS($result),
3434 'affected' => SQL_AFFECTEDROWS(),
3435 'sql_str' => $sqlString,
3436 'timing' => $timing,
3437 'file' => basename($F),
3442 $GLOBALS['debug_sqls'][] = $record;
3445 // Initializes the cache instance
3446 function initCacheInstance () {
3447 // Load include for CacheSystem class
3448 loadIncludeOnce('inc/classes/cachesystem.class.php');
3450 // Initialize cache system only when it's needed
3451 $GLOBALS['cache_instance'] = new CacheSystem();
3452 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3453 // Failed to initialize cache sustem
3454 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3458 // Getter for message from array or raw message
3459 function getMessageFromIndexedArray ($message, $pos, $array) {
3460 // Check if the requested message was found in array
3461 if (isset($array[$pos])) {
3462 // ... if yes then use it!
3463 $ret = $array[$pos];
3465 // ... else use default message
3473 // Print code with line numbers
3474 function linenumberCode ($code) {
3475 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3476 $count_lines = count($codeE);
3478 $r = 'Line | Code:<br />';
3479 foreach($codeE as $line => $c) {
3480 $r .= '<div class="line"><span class="linenum">';
3481 if ($count_lines == 1) {
3484 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3489 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3492 return '<div class="code">' . $r . '</div>';
3495 // Convert ';' to ', ' for e.g. receiver list
3496 function convertReceivers ($old) {
3497 return str_replace(';', ', ', $old);
3500 // Determines the right page title
3501 function determinePageTitle () {
3502 // Config and database connection valid?
3503 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3507 // Title decoration enabled?
3508 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3510 // Do we have some extra title?
3511 if (isExtraTitleSet()) {
3513 $TITLE .= getExtraTitle() . ' by ';
3517 $TITLE .= getConfig('MAIN_TITLE');
3519 // Add title of module? (middle decoration will also be added!)
3520 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3521 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3524 // Add title from what file
3526 if (getModule() == 'login') $mode = 'member';
3527 elseif (getModule() == 'index') $mode = 'guest';
3528 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3530 // Add title decorations? (right)
3531 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3533 // Remember title in constant for the template
3534 $pageTitle = $TITLE;
3535 } elseif ((isInstalled()) && (isAdminRegistered())) {
3536 // Installed, admin registered but no ext-sql_patches
3537 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3538 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3539 // Installed but no admin registered
3540 $pageTitle = getMessage('SETUP_OF_MXCHANGE');
3541 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3542 // Installation mode
3543 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3545 // Configuration not found!
3546 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3548 // Do not add the fatal message in installation mode
3549 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3553 return decodeEntities($pageTitle);
3556 // Checks wethere there is a cache file there. This function is cached.
3557 function isTemplateCached ($template) {
3558 // Do we have cached this result?
3559 if (!isset($GLOBALS['template_cache'][$template])) {
3561 $FQFN = generateCacheFqfn($template);
3564 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3568 return $GLOBALS['template_cache'][$template];
3571 // Flushes non-flushed template cache to disk
3572 function flushTemplateCache ($template, $eval) {
3573 // Is this cache flushed?
3574 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3576 $FQFN = generateCacheFqfn($template);
3578 // Replace username with a call
3579 $eval = str_replace('$username', '".getUsername()."', $eval);
3582 writeToFile($FQFN, $eval, true);
3586 // Reads a template cache
3587 function readTemplateCache ($template) {
3589 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3591 $FQFN = generateCacheFqfn($template);
3594 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3598 return $GLOBALS['template_eval'][$template];
3601 // Escapes quotes (default is only double-quotes)
3602 function escapeQuotes ($str, $single = false) {
3603 // Should we escape all?
3604 if ($single === true) {
3605 // Escape all (including null)
3606 $str = addslashes($str);
3608 // Escape only double-quotes but prevent double-quoting
3609 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3612 // Return the escaped string
3616 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3617 function escapeJavaScriptQuotes ($str) {
3618 // Replace all double-quotes and secure back-ticks
3619 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3625 // Send out mails depending on the 'mod/modes' combination
3626 // @TODO Lame description for this function
3627 function sendModeMails ($mod, $modes) {
3629 if (fetchUserData(getMemberId())) {
3630 // Extract salt from cookie
3631 $salt = substr(getSession('u_hash'), 0, -40);
3633 // Now let's compare passwords
3634 $hash = encodeHashForCookie(getUserData('password'));
3636 // Does the hash match or should we change it?
3637 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
3639 $content = getUserDataArray();
3642 $content['gender'] = translateGender($content['gender']);
3644 // Clear/init the content variable
3645 $content['message'] = '';
3648 // @TODO Move this in a filter
3651 foreach ($modes as $mode) {
3653 case 'normal': break; // Do not add any special lines
3654 case 'email': // Email was changed!
3655 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestParameter('old_email')."\n";
3658 case 'pass': // Password was changed
3659 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3663 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3664 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3669 if (isExtensionActive('country')) {
3670 // Replace code with description
3671 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
3674 // Merge content with data from POST
3675 $content = merge_array($content, postRequestArray());
3678 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3680 if (getConfig('admin_notify') == 'Y') {
3681 // The admin needs to be notified about a profile change
3682 $message_admin = 'admin_mydata_notify';
3683 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3686 $message_admin = '';
3690 // Set subject lines
3691 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3693 // Output success message
3694 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3697 default: // Unsupported module!
3698 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3699 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
3703 // Passwords mismatch
3704 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
3707 // Could not load profile
3708 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
3711 // Send email to user if required
3712 if ((!empty($sub_mem)) && (!empty($message))) {
3714 sendEmail($content['email'], $sub_mem, $message);
3717 // Send only if no other error has occured
3718 if (empty($content)) {
3719 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3721 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3722 } elseif (getConfig('admin_notify') == 'Y') {
3723 // Cannot send mails to admin!
3724 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3727 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3732 loadTemplate('admin_settings_saved', false, $content);
3735 // Generates a 'selection box' from given array
3736 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent='') {
3738 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3739 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3741 // Walk through all options
3742 foreach ($options as $option) {
3743 // Add the <option> entry
3744 if (empty($optionContent)) {
3745 // ... from template
3746 $OUT .= loadTemplate('select_' . $name . '_option', true, $option);
3749 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3753 // Finish selection box
3754 $OUT .= '</select>';
3758 'selection_box' => $OUT,
3759 'module' => getModule(),
3763 // Load template and return it
3764 return loadTemplate('select_' . $name . '_box', true, $content);
3767 // Get a module from filename and access level
3768 function getModuleFromFileName ($file, $accessLevel) {
3769 // Default is 'invalid';
3770 $modCheck = 'invalid';
3772 // @TODO This is still very static, rewrite it somehow
3773 switch ($accessLevel) {
3775 $modCheck = 'admin';
3781 $modCheck = getModule();
3784 default: // Unsupported file name / access level
3785 debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3793 // Encodes an URL for adding session id, etc.
3794 function encodeUrl ($url, $outputMode = '0') {
3795 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
3796 if ((strpos($url, session_name()) !== false) || (getOutputMode() == -3)) return $url;
3798 // Do we have a valid session?
3799 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3801 // Determine right seperator
3802 $seperator = '&';
3803 if (strpos($url, '?') === false) {
3806 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3812 if (session_id() != '') {
3813 $url .= $seperator . session_name() . '=' . session_id();
3818 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3820 $url = '{?URL?}/' . $url;
3827 // Simple check for spider
3828 function isSpider () {
3830 $userAgent = strtolower(detectUserAgent(true));
3832 // It should not be empty, if so it is better a spider/bot
3833 if (empty($userAgent)) return true;
3836 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
3839 // Prepares the header for HTML output
3840 function loadHtmlHeader () {
3842 // 1.) pre_page_header (mainly loads the page_header template and includes
3843 // meta description)
3844 runFilterChain('pre_page_header');
3846 // Here can be something be added, but normally one of the two filters
3847 // around this line should do the job for you.
3849 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
3850 // to close the head-tag)
3851 // Include more header data here
3852 runFilterChain('post_page_header');
3855 // Adds page header and footer to output array element
3856 function addPageHeaderFooter () {
3860 // Add them all together. This is maybe to simple
3861 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
3862 // Add page part if set
3863 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
3866 // Transfer $OUT to 'output'
3867 $GLOBALS['output'] = $OUT;
3870 // Generates meta description for current module and 'what' value
3871 function generateMetaDescriptionCode () {
3872 // Only include from guest area
3873 if (getModule() == 'index') {
3874 // Construct dynamic description
3875 $DESCR = '{?MAIN_TITLE?} '.trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
3877 // Output it directly
3878 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
3882 unset($GLOBALS['ref_level']);
3885 // Generates an FQFN for template cache from the given template name
3886 function generateCacheFqfn ($template) {
3888 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
3889 // Generate the FQFN
3890 $GLOBALS['template_cache_fqfn'][$template] = sprintf("%s_compiled/html/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3894 return $GLOBALS['template_cache_fqfn'][$template];
3897 // Function to search for the last modified file
3898 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
3900 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
3901 // Does it match what we are looking for? (We skip a lot files already!)
3902 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
3903 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
3905 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
3906 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
3908 // Walk through all entries
3909 foreach ($ds as $d) {
3910 // Generate proper FQFN
3911 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir . '/' . $d);
3913 // Is it a file and readable?
3914 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
3915 if (isFileReadable($FQFN)) {
3916 // $FQFN is a readable file so extract the requested data from it
3917 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
3918 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
3920 // Is the file more recent?
3921 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
3922 // This file is newer as the file before
3923 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
3924 $last_changed['path_name'] = $FQFN;
3925 $last_changed[$lookFor] = $check;
3929 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
3934 // "Fixes" null or empty string to count of dashes
3935 function fixNullEmptyToDashes ($str, $num) {
3936 // Use str as default
3940 if ((is_null($str)) || (trim($str) == '')) {
3942 $return = str_repeat('-', $num);
3945 // Return final string
3949 //////////////////////////////////////////////////
3950 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3951 //////////////////////////////////////////////////
3953 if (!function_exists('html_entity_decode')) {
3954 // Taken from documentation on www.php.net
3955 function html_entity_decode ($string) {
3956 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3957 $trans_tbl = array_flip($trans_tbl);
3958 return strtr($string, $trans_tbl);
3962 if (!function_exists('http_build_query')) {
3963 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
3964 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
3966 foreach ((array)$data as $k => $v) {
3967 if (is_int($k) && $prefix != null) {
3968 $k = urlencode($prefix . $k);
3971 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
3973 if (is_array($v) || is_object($v)) {
3974 array_push($ret, http_build_query($v, '', $sep, $k));
3976 array_push($ret, $k.'='.urlencode($v));
3980 if (empty($sep)) $sep = ini_get('arg_separator.output');
3982 return implode($sep, $ret);