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 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
44 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
45 function outputHtml ($htmlCode, $newLine = true) {
47 if (!isset($GLOBALS['output'])) $GLOBALS['output'] = '';
50 $username = getMessage('USERNAME_UNKNOWN');
51 if (isset($GLOBALS['username'])) $username = getUsername();
53 // Do we have HTML-Code here?
54 if (!empty($htmlCode)) {
55 // Yes, so we handle it as you have configured
56 switch (getConfig('OUTPUT_MODE')) {
58 // That's why you don't need any \n at the end of your HTML code... :-)
59 if (getPhpCaching() == 'on') {
60 // Output into PHP's internal buffer
61 outputRawCode($htmlCode);
63 // That's why you don't need any \n at the end of your HTML code... :-)
64 if ($newLine === true) print("\n");
66 // Render mode for old or lame servers...
67 $GLOBALS['output'] .= $htmlCode;
69 // That's why you don't need any \n at the end of your HTML code... :-)
70 if ($newLine === true) $GLOBALS['output'] .= "\n";
75 // If we are switching from render to direct output rendered code
76 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
78 // The same as above... ^
79 outputRawCode($htmlCode);
80 if ($newLine === true) print("\n");
84 // Huh, something goes wrong or maybe you have edited config.php ???
85 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
88 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
89 // Output cached HTML code
90 $GLOBALS['output'] = ob_get_contents();
92 // Clear output buffer for later output if output is found
93 if (!empty($GLOBALS['output'])) {
97 // Extension 'rewrite' installed?
98 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
99 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
102 // Send all HTTP headers
105 // Compile and run finished rendered HTML code
106 compileFinalOutput();
108 // Output code here, DO NOT REMOVE! ;-)
109 outputRawCode($GLOBALS['output']);
110 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
111 // Rewrite links when rewrite extension is active
112 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
113 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
116 // Send all HTTP headers
119 // Compile and run finished rendered HTML code
120 compileFinalOutput();
122 // Output code here, DO NOT REMOVE! ;-)
123 outputRawCode($GLOBALS['output']);
125 // And flush all headers
130 // Sends out all headers required for HTTP/1.1 reply
131 function sendHttpHeaders () {
133 $now = gmdate('D, d M Y H:i:s') . ' GMT';
136 sendHeader('HTTP/1.1 200');
138 // General headers for no caching
139 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
140 sendHeader('Last-Modified: ' . $now);
141 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
142 sendHeader('Pragma: no-cache'); // HTTP/1.0
143 sendHeader('Connection: Close');
144 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
145 sendHeader('Content-Language: ' . getLanguage());
148 // Compiles the final output
149 function compileFinalOutput () {
153 // Add page header and footer
154 addPageHeaderFooter();
157 while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
158 // Init common variables
163 $eval = "\$newContent = \"".compileCode(escapeQuotes($GLOBALS['output']))."\";";
166 // Was that eval okay?
167 if (empty($newContent)) {
168 // Something went wrong!
169 debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
171 $GLOBALS['output'] = $newContent;
178 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
179 // Compress it for HTTP gzip
180 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
183 sendHeader('Content-Encoding: gzip');
184 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
185 // Compress it for HTTP deflate
186 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
189 sendHeader('Content-Encoding: deflate');
193 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
199 // Output the raw HTML code
200 function outputRawCode ($htmlCode) {
201 // Output stripped HTML code to avoid broken JavaScript code, etc.
202 print(str_replace('{BACK}', "\\", $htmlCode));
204 // Flush the output if only getPhpCaching() is not 'on'
205 if (getPhpCaching() != 'on') {
211 // Init fatal message array
212 function initFatalMessages () {
213 $GLOBALS['fatal_messages'] = array();
216 // Getter for whole fatal error messages
217 function getFatalArray () {
218 return $GLOBALS['fatal_messages'];
221 // Add a fatal error message to the queue array
222 function addFatalMessage ($F, $L, $message, $extra = '') {
223 if (is_array($extra)) {
224 // Multiple extras for a message with masks
225 $message = call_user_func_array('sprintf', $extra);
226 } elseif (!empty($extra)) {
227 // $message is text with a mask plus extras to insert into the text
228 $message = sprintf($message, $extra);
231 // Add message to $GLOBALS['fatal_messages']
232 $GLOBALS['fatal_messages'][] = $message;
234 // Log fatal messages away
235 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
238 // Getter for total fatal message count
239 function getTotalFatalErrors () {
243 // Do we have at least the first entry?
244 if (!empty($GLOBALS['fatal_messages'][0])) {
246 $count = count($GLOBALS['fatal_messages']);
253 // Load a template file and return it's content (only it's name; do not use ' or ")
254 function loadTemplate ($template, $return = false, $content = array()) {
255 // @TODO Remove this sanity-check if all is fine
256 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
258 // @TODO Try to rewrite all $DATA to $content
262 if (isTemplateCached($template)) {
263 // Evaluate the cache
264 eval(readTemplateCache($template));
265 } elseif (!isset($GLOBALS['template_eval'][$template])) {
266 // Add more variables which you want to use in your template files
267 $username = getUsername();
269 // Make all template names lowercase
270 $template = strtolower($template);
274 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
277 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
278 $extraPath = detectExtraTemplatePath($template);;
280 ////////////////////////
281 // Generate file name //
282 ////////////////////////
283 $FQFN = $basePath . $extraPath . $template . '.tpl';
285 // Does the special template exists?
286 if (!isFileReadable($FQFN)) {
287 // Reset to default template
288 $FQFN = $basePath . $template . '.tpl';
291 // Now does the final template exists?
292 if (isFileReadable($FQFN)) {
293 // Count the template load
294 incrementConfigEntry('num_templates');
296 // The local file does exists so we load it. :)
297 $GLOBALS['tpl_content'] = readFromFile($FQFN);
299 // Do we have to compile the code?
301 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)) {
302 // Normal HTML output?
303 if (getOutputMode() == '0') {
304 // Add surrounding HTML comments to help finding bugs faster
305 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
307 // Prepare eval() command
308 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
309 } elseif (substr($template, 0, 3) == 'js_') {
310 // JavaScripts don't like entities and timings
311 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
313 // Prepare eval() command, other output doesn't like entities, maybe
314 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
317 // Add surrounding HTML comments to help finding bugs faster
318 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
319 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
322 // Cache the eval() command here
323 $GLOBALS['template_eval'][$template] = $eval;
326 eval($GLOBALS['template_eval'][$template]);
327 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
328 // Only admins shall see this warning or when installation mode is active
329 $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
330 (' . $template . ')<br />
332 {--TEMPLATE_CONTENT--}
333 <pre>' . print_r($content, true) . '</pre>
335 <pre>' . print_r($DATA, true) . '</pre>
339 $GLOBALS['template_eval'][$template] = '404';
343 eval($GLOBALS['template_eval'][$template]);
346 // Do we have some content to output or return?
348 // Not empty so let's put it out! ;)
349 if ($return === true) {
350 // Return the HTML code
356 } elseif (isDebugModeEnabled()) {
357 // Warning, empty output!
358 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
362 // Detects the extra template path from given template name
363 function detectExtraTemplatePath ($template) {
368 if (!isset($GLOBALS['extra_path'][$template])) {
369 // Check for admin/guest/member/etc. templates
370 if (substr($template, 0, 6) == 'admin_') {
371 // Admin template found
372 $extraPath = 'admin/';
373 } elseif (substr($template, 0, 6) == 'guest_') {
374 // Guest template found
375 $extraPath = 'guest/';
376 } elseif (substr($template, 0, 7) == 'member_') {
377 // Member template found
378 $extraPath = 'member/';
379 } elseif (substr($template, 0, 7) == 'select_') {
380 // Selection template found
381 $extraPath = 'select/';
382 } elseif (substr($template, 0, 8) == 'install_') {
383 // Installation template found
384 $extraPath = 'install/';
385 } elseif (substr($template, 0, 4) == 'ext_') {
386 // Extension template found
388 } elseif (substr($template, 0, 3) == 'la_') {
389 // 'Logical-area' template found
391 } elseif (substr($template, 0, 3) == 'js_') {
392 // JavaScript template found
394 } elseif (substr($template, 0, 5) == 'menu_') {
395 // Menu template found
396 $extraPath = 'menu/';
398 // Test for extension
399 $test = substr($template, 0, strpos($template, '_'));
401 // Probe for valid extension name
402 if (isExtensionNameValid($test)) {
403 // Set extra path to extension's name
404 $extraPath = $test . '/';
409 $GLOBALS['extra_path'][$template] = $extraPath;
413 return $GLOBALS['extra_path'][$template];
416 // Loads an email template and compiles it
417 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
420 // Make sure all template names are lowercase!
421 $template = strtolower($template);
423 // Default 'nickname' if extension is not installed
426 // Neutral email address is default
427 $email = getConfig('WEBMASTER');
429 // Is content an array?
430 if (is_array($content)) {
431 // Add expiration to array
432 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
433 // Will never expire!
434 $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
435 } elseif (isConfigEntrySet('auto_purge')) {
436 // Create nice date string
437 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
440 $content['expiration'] = getMessage('MAIL_NO_CONFIG_AUTO_PURGE');
445 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$userid},template={$template},content[]=".gettype($content).'<br />');
446 if (($userid > 0) && (is_array($content))) {
447 // If nickname extension is installed, fetch nickname as well
448 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
449 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
451 fetchUserData($userid, 'nickname');
453 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
455 fetchUserData($userid);
458 // Merge data if valid
459 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
460 if (isUserDataValid()) {
461 $content = merge_array($content, getUserDataArray());
463 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
466 // Translate M to male or F to female if present
467 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
469 // Overwrite email from data if present
470 if (isset($content['email'])) $email = $content['email'];
472 // Store email for some functions in global data array
473 // @TODO Do only use $content, not $DATA or raw variables
474 $DATA['email'] = $email;
477 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
480 $extraPath = detectExtraTemplatePath($template);
482 // Generate full FQFN
483 $FQFN = $basePath . $extraPath . $template . '.tpl';
485 // Does the special template exists?
486 if (!isFileReadable($FQFN)) {
487 // Reset to default template
488 $FQFN = $basePath . $template . '.tpl';
491 // Now does the final template exists?
493 if (isFileReadable($FQFN)) {
494 // The local file does exists so we load it. :)
495 $GLOBALS['tpl_content'] = readFromFile($FQFN);
498 $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileRawCode(escapeQuotes($GLOBALS['tpl_content']))."\");";
499 eval($GLOBALS['tpl_content']);
500 } elseif (!empty($template)) {
501 // Template file not found!
502 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
503 {--TEMPLATE_CONTENT--}
504 <pre>' . print_r($content, true) . '</pre>
506 <pre>' . print_r($DATA, true) . '</pre>
509 // Debug mode not active? Then remove the HTML tags
510 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
512 // No template name supplied!
513 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
516 // Is there some content?
517 if (empty($newContent)) {
519 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
521 // Add last error if the required function exists
522 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
525 // Remove content and data
533 // Send mail out to an email address
534 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
535 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
537 // Compile subject line (for POINTS constant etc.)
538 eval("\$subject = decodeEntities(\"".compileRawCode(escapeQuotes($subject))."\");");
541 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
542 // Value detected, is the message extension installed?
543 // @TODO Extension 'msg' does not exist
544 if (isExtensionActive('msg')) {
545 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
548 // Does the user exist?
549 if (fetchUserData($toEmail)) {
551 $toEmail = getUserData('email');
554 $toEmail = getConfig('WEBMASTER');
557 } elseif ($toEmail == '0') {
559 $toEmail = getConfig('WEBMASTER');
561 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
563 // Check for PHPMailer or debug-mode
564 if (!checkPhpMailerUsage()) {
565 // Not in PHPMailer-Mode
566 if (empty($mailHeader)) {
567 // Load email header template
568 $mailHeader = loadEmailTemplate('header');
571 $mailHeader .= loadEmailTemplate('header');
573 } elseif (isDebugModeEnabled()) {
574 if (empty($mailHeader)) {
575 // Load email header template
576 $mailHeader = loadEmailTemplate('header');
579 $mailHeader .= loadEmailTemplate('header');
584 eval("\$toEmail = \"".compileRawCode(escapeQuotes($toEmail))."\";");
587 eval("\$message = \"".str_replace('$', '$', compileRawCode(escapeQuotes($message)))."\";");
589 // Fix HTML parameter (default is no!)
590 if (empty($isHtml)) $isHtml = 'N';
591 if (isDebugModeEnabled()) {
592 // In debug mode we want to display the mail instead of sending it away so we can debug this part
594 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
595 To : ' . htmlentities(utf8_decode($toEmail)) . '
596 Subject : ' . htmlentities(utf8_decode($subject)) . '
597 Message : ' . htmlentities(utf8_decode($message)) . '
599 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
600 // Send mail as HTML away
601 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
602 } elseif (!empty($toEmail)) {
604 sendRawEmail($toEmail, $subject, $message, $mailHeader);
605 } elseif ($isHtml != 'Y') {
607 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
611 // Check to use wether legacy mail() command or PHPMailer class
612 // @TODO Rewrite this to an extension 'smtp'
614 function checkPhpMailerUsage() {
615 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
618 // Send out a raw email with PHPMailer class or legacy mail() command
619 function sendRawEmail ($toEmail, $subject, $message, $from) {
620 // Just compile all again, to put out all configs, etc.
621 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
622 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
623 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
624 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
626 // Shall we use PHPMailer class or legacy mode?
627 if (checkPhpMailerUsage()) {
628 // Use PHPMailer class with SMTP enabled
629 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
630 loadIncludeOnce('inc/phpmailer/class.smtp.php');
633 $mail = new PHPMailer();
635 // Set charset to UTF-8
636 $mail->CharSet('UTF-8');
638 // Path for PHPMailer
639 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
642 $mail->SMTPAuth = true;
643 $mail->Host = getConfig('SMTP_HOSTNAME');
645 $mail->Username = getConfig('SMTP_USER');
646 $mail->Password = getConfig('SMTP_PASSWORD');
648 $mail->From = getConfig('WEBMASTER');
652 $mail->FromName = getConfig('MAIN_TITLE');
653 $mail->Subject = $subject;
654 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
655 $mail->Body = $message;
656 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
657 $mail->WordWrap = 70;
660 $mail->Body = decodeEntities($message);
662 $mail->AddAddress($toEmail, '');
663 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
664 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
665 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
668 // Use legacy mail() command
669 mail($toEmail, $subject, decodeEntities($message), $from);
673 // Generate a password in a specified length or use default password length
674 function generatePassword ($length = '0') {
675 // Auto-fix invalid length of zero
676 if ($length == '0') $length = getConfig('pass_len');
678 // Initialize array with all allowed chars
679 $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,-,+,_,/,.');
681 // Start creating password
683 for ($i = '0'; $i < $length; $i++) {
684 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
687 // When the size is below 40 we can also add additional security by scrambling
688 // it. Otherwise we may corrupt hashes
689 if (strlen($PASS) <= 40) {
690 // Also scramble the password
691 $PASS = scrambleString($PASS);
694 // Return the password
698 // Generates a human-readable timestamp from the Uni* stamp
699 function generateDateTime ($time, $mode = '0') {
700 // Filter out numbers
701 $time = bigintval($time);
703 // If the stamp is zero it mostly didn't "happen"
706 return getMessage('NEVER_HAPPENED');
709 switch (getLanguage()) {
710 case 'de': // German date / time format
712 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
713 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
714 case '2': $ret = date('d.m.Y|H:i', $time); break;
715 case '3': $ret = date('d.m.Y', $time); break;
717 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
722 default: // Default is the US date / time format!
724 case '0': $ret = date('r', $time); break;
725 case '1': $ret = date('Y-m-d - g:i A', $time); break;
726 case '2': $ret = date('y-m-d|H:i', $time); break;
727 case '3': $ret = date('y-m-d', $time); break;
729 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
738 // Translates Y/N to yes/no
739 function translateYesNo ($yn) {
741 $translated = '??? (' . $yn . ')';
743 case 'Y': $translated = getMessage('YES'); break;
744 case 'N': $translated = getMessage('NO'); break;
747 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
755 // Translates the "pool type" into human-readable
756 function translatePoolType ($type) {
757 // Default?type is unknown
758 $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
761 $constName = sprintf("POOL_TYPE_%s", $type);
764 if (isMessageIdValid($constName)) {
766 $translated = getMessage($constName);
769 // Return "translation"
773 // Translates the american decimal dot into a german comma
774 function translateComma ($dotted, $cut = true, $max = '0') {
775 // Default is 3 you can change this in admin area "Misc -> Misc Options"
776 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
778 // Use from config is default
779 $maxComma = getConfig('max_comma');
781 // Use from parameter?
782 if ($max > 0) $maxComma = $max;
785 if (($cut === true) && ($max == '0')) {
786 // Test for commata if in cut-mode
787 $com = explode('.', $dotted);
788 if (count($com) < 2) {
789 // Don't display commatas even if there are none... ;-)
795 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
798 switch (getLanguage()) {
799 case 'de': // German language
800 $dotted = number_format($dotted, $maxComma, ',', '.');
803 default: // All others
804 $dotted = number_format($dotted, $maxComma, '.', ',');
808 // Return translated value
812 // Translate Uni*-like gender to human-readable
813 function translateGender ($gender) {
815 $ret = '!' . $gender . '!';
817 // Male/female or company?
819 case 'M': $ret = getMessage('GENDER_M'); break;
820 case 'F': $ret = getMessage('GENDER_F'); break;
821 case 'C': $ret = getMessage('GENDER_C'); break;
823 // Log unknown gender
824 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
828 // Return translated gender
832 // "Translates" the user status
833 function translateUserStatus ($status) {
834 // Generate message depending on status
839 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
844 $ret = getMessage('ACCOUNT_DELETED');
848 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
849 $ret = getMaskedMessage('UNKNOWN_STATUS', $status);
857 // Generates an URL for the dereferer
858 function generateDerefererUrl ($URL) {
859 // Don't de-refer our own links!
860 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
861 // De-refer this link
862 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
869 // Generates an URL for the frametester
870 function generateFrametesterUrl ($URL) {
871 // Prepare frametester URL
872 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
873 encodeString(compileUriCode($URL))
876 // Return the new URL
877 return $frametesterUrl;
880 // Count entries from e.g. a selection box
881 function countSelection ($array) {
883 if (!is_array($array)) {
885 debug_report_bug(__FUNCTION__.': No array provided.');
892 foreach ($array as $key => $selected) {
894 if (!empty($selected)) $ret++;
897 // Return counted selections
901 // Generate XHTML code for the CAPTCHA
902 function generateCaptchaCode ($code, $type, $DATA, $userid) {
903 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
906 // Generates a timestamp (some wrapper for mktime())
907 function makeTime ($hours, $minutes, $seconds, $stamp) {
908 // Extract day, month and year from given timestamp
909 $days = date('d', $stamp);
910 $months = date('m', $stamp);
911 $years = date('Y', $stamp);
913 // Create timestamp for wished time which depends on extracted date
924 // Redirects to an URL and if neccessarry extends it with own base URL
925 function redirectToUrl ($URL) {
927 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
929 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
930 $rel = ' rel="external"';
932 // Do we have internal or external URL?
933 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
934 // Own (=internal) URL
938 // Three different ways to debug...
939 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
940 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
941 //* DEBUG: */ die($URL);
943 // Simple probe for bots/spiders from search engines
945 // Secure the URL against bad things such als HTML insertions and so on...
946 $URL = secureString($URL);
948 // Output new location link as anchor
949 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
950 } elseif (!headers_sent()) {
951 // Clear own output buffer
952 $GLOBALS['output'] = '';
954 // Load URL when headers are not sent
955 sendHeader('Location: '.str_replace('&', '&', $URL));
957 // Output error message
958 loadInclude('inc/header.php');
959 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
960 loadInclude('inc/footer.php');
963 // Shut the mailer down here
967 // Wrapper for redirectToUrl but URL comes from a configuration entry
968 function redirectToConfiguredUrl ($configEntry) {
970 $URL = getConfig($configEntry);
975 debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
982 // Compiles the given HTML/mail code
983 function compileCode ($code, $simple = false, $constants = true, $full = true) {
984 // Is the code a string?
985 if (!is_string($code)) {
986 // Silently return it
991 $startCompile = microtime(true);
994 $code = compileRawCode($code, $simple, $constants, $full);
997 $compiled = microtime(true);
1000 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1002 // Return compiled code
1006 // Compiles the code (use compileCode() only for HTML because of the comments)
1007 // @TODO $simple is deprecated
1008 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1009 // Is the code a string?
1010 if (!is_string($code)) {
1011 // Silently return it
1015 // Init replacement-array with smaller set of security characters
1016 $secChars = $GLOBALS['url_chars'];
1018 // Select full set of chars to replace when we e.g. want to compile URLs
1019 if ($full === true) $secChars = $GLOBALS['security_chars'];
1021 // Compile more through a filter
1022 $code = runFilterChain('compile_code', $code);
1024 // Compile constants
1025 if ($constants === true) {
1026 // BEFORE 0.2.1 : Language and data constants
1027 // WITH 0.2.1+ : Only language constants
1028 $code = str_replace('{--', "\" . getMessage('", str_replace('--}', "') . \"", $code));
1030 // BEFORE 0.2.1 : Not used
1031 // WITH 0.2.1+ : Data constants
1032 $code = str_replace('{!', "\" . constant('", str_replace('!}', "') . \"", $code));
1035 // Compile QUOT and other non-HTML codes
1036 foreach ($secChars['to'] as $k => $to) {
1037 // Do the reversed thing as in inc/libs/security_functions.php
1038 $code = str_replace($to, $secChars['from'][$k], $code);
1041 // Find $content[bla][blub] entries
1042 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1043 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1045 // Are some matches found?
1046 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1047 // Replace all matches
1048 $matchesFound = array();
1049 foreach ($matches[0] as $key => $match) {
1050 // Fuzzy look has failed by default
1051 $fuzzyFound = false;
1053 // Fuzzy look on match if already found
1054 foreach ($matchesFound as $found => $set) {
1056 $test = substr($found, 0, strlen($match));
1058 // Does this entry exist?
1059 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1060 if ($test == $match) {
1062 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1069 if ($fuzzyFound === true) continue;
1071 // Take all string elements
1072 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1073 // Replace it in the code
1074 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1075 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1076 $code = str_replace($match, '".' . $newMatch . '."', $code);
1077 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1078 $matchesFound[$match] = 1;
1079 } elseif (!isset($matchesFound[$match])) {
1080 // Not yet replaced!
1081 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1082 $code = str_replace($match, '".' . $match . '."', $code);
1083 $matchesFound[$match] = 1;
1092 /************************************************************************
1094 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1095 * $a_sort sortiert: *
1097 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1098 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1099 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1100 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1101 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1103 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1104 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1105 * Sie, dass es doch nicht so schwer ist! :-) *
1107 ************************************************************************/
1108 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1110 while ($primary_key < count($a_sort)) {
1111 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1112 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1114 if ($nums === false) {
1115 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1116 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1117 } elseif ($key != $key2) {
1118 // Sort numbers (E.g.: 9 < 10)
1119 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1120 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1124 // We have found two different values, so let's sort whole array
1125 foreach ($dummy as $sort_key => $sort_val) {
1126 $t = $dummy[$sort_key][$key];
1127 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1128 $dummy[$sort_key][$key2] = $t;
1139 // Write back sorted array
1144 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1147 if ($type == 'yn') {
1148 // This is a yes/no selection only!
1149 if ($id > 0) $prefix .= "[" . $id."]";
1150 $OUT .= " <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
1152 // Begin with regular selection box here
1153 if (!empty($prefix)) $prefix .= "_";
1155 if ($id > 0) $type2 .= "[" . $id."]";
1156 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
1161 for ($idx = 1; $idx < 32; $idx++) {
1162 $OUT .= "<option value=\"" . $idx."\"";
1163 if ($default == $idx) $OUT .= ' selected="selected"';
1164 $OUT .= ">" . $idx."</option>\n";
1168 case 'month': // Month
1169 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1170 $OUT .= "<option value=\"" . $month."\"";
1171 if ($default == $month) $OUT .= ' selected="selected"';
1172 $OUT .= ">" . $descr."</option>\n";
1176 case 'year': // Year
1178 $year = date('Y', time());
1180 // Use configured min age or fixed?
1181 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1183 $startYear = $year - getConfig('min_age');
1186 $startYear = $year - 16;
1189 // Calculate earliest year (100 years old people can still enter Internet???)
1190 $minYear = $year - 100;
1192 // Check if the default value is larger than minimum and bigger than actual year
1193 if (($default > $minYear) && ($default >= $year)) {
1194 for ($idx = $year; $idx < ($year + 11); $idx++) {
1195 $OUT .= "<option value=\"" . $idx."\"";
1196 if ($default == $idx) $OUT .= ' selected="selected"';
1197 $OUT .= ">" . $idx."</option>\n";
1199 } elseif ($default == -1) {
1200 // Current year minus 1
1201 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1203 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1206 // Get current year and subtract the configured minimum age
1207 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1208 // Calculate earliest year depending on extension version
1209 if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
1210 // Use configured minimum age
1211 $year = date('Y', time()) - getConfig('min_age');
1213 // Use fixed 16 years age
1214 $year = date('Y', time()) - 16;
1217 // Construct year selection list
1218 for ($idx = $minYear; $idx <= $year; $idx++) {
1219 $OUT .= "<option value=\"" . $idx."\"";
1220 if ($default == $idx) $OUT .= ' selected="selected"';
1221 $OUT .= ">" . $idx."</option>\n";
1228 for ($idx = '0'; $idx < 60; $idx+=5) {
1229 if (strlen($idx) == 1) $idx = '0' . $idx;
1230 $OUT .= "<option value=\"" . $idx."\"";
1231 if ($default == $idx) $OUT .= ' selected="selected"';
1232 $OUT .= ">" . $idx."</option>\n";
1237 for ($idx = '0'; $idx < 24; $idx++) {
1238 if (strlen($idx) == 1) $idx = '0' . $idx;
1239 $OUT .= "<option value=\"" . $idx."\"";
1240 if ($default == $idx) $OUT .= ' selected="selected"';
1241 $OUT .= ">" . $idx."</option>\n";
1246 $OUT .= "<option value=\"Y\"";
1247 if ($default == 'Y') $OUT .= ' selected="selected"';
1248 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1249 if ($default != 'Y') $OUT .= ' selected="selected"';
1250 $OUT .= ">{--NO--}</option>\n";
1253 $OUT .= " </select>\n";
1258 // Deprecated : $length
1261 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1262 // Build server string
1263 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1266 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1267 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1268 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1269 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1270 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1272 // Build string from misc data
1273 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1275 // Add more additional data
1276 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1278 // Add referal id, language, theme and userid
1279 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1280 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1281 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1282 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1284 // Calculate number for generating the code
1285 $a = $code + getConfig('_ADD') - 1;
1287 if (isConfigEntrySet('master_salt')) {
1288 // Generate hash with master salt from modula of number with the prime number and other data
1289 $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'));
1291 // Create number from hash
1292 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1294 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1295 $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')));
1297 // Create number from hash
1298 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1301 // At least 10 numbers shall be secure enought!
1302 $len = getConfig('code_length');
1303 if ($len == '0') $len = $length;
1304 if ($len == '0') $len = 10;
1306 // Cut off requested counts of number
1307 $return = substr(str_replace('.', '', $rcode), 0, $len);
1309 // Done building code
1313 // Does only allow numbers
1314 function bigintval ($num, $castValue = true) {
1315 // Filter all numbers out
1316 $ret = preg_replace('/[^0123456789]/', '', $num);
1319 if ($castValue === true) $ret = (double)$ret;
1321 // Has the whole value changed?
1322 if ('' . $ret . '' != '' . $num . '') {
1324 debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
1331 // Insert the code in $img_code into jpeg or PNG image
1332 function generateImageOrCode ($img_code, $headerSent = true) {
1333 // Is the code size oversized or shouldn't we display it?
1334 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1335 // Stop execution of function here because of over-sized code length
1336 debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1337 } elseif ($headerSent === false) {
1338 // Return an HTML code here
1339 return "<img src=\"{%url=img.php?code=" . $img_code."%}\" alt=\"Image\" />\n";
1343 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1346 getConfig('img_type')
1350 if (isFileReadable($img)) {
1351 // Switch image type
1352 switch (getConfig('img_type'))
1355 // Okay, load image and hide all errors
1356 $image = imagecreatefromjpeg($img);
1360 // Okay, load image and hide all errors
1361 $image = imagecreatefrompng($img);
1365 // Exit function here
1366 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1370 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1371 $text_color = imagecolorallocate($image, 0, 0, 0);
1373 // Insert code into image
1374 imagestring($image, 5, 14, 2, $img_code, $text_color);
1376 // Return to browser
1377 sendHeader('Content-Type: image/' . getConfig('img_type'));
1379 // Output image with matching image factory
1380 switch (getConfig('img_type')) {
1381 case 'jpg': imagejpeg($image); break;
1382 case 'png': imagepng($image); break;
1385 // Remove image from memory
1386 imagedestroy($image);
1388 // Create selection box or array of splitted timestamp
1389 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1390 // Do not continue if ONE_DAY is absend
1391 if (!isConfigEntrySet('ONE_DAY')) {
1392 // And return the timestamp itself or empty array
1393 if ($return_array === true) {
1400 // Calculate 2-seconds timestamp
1401 $stamp = round($timestamp);
1402 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1404 // Do we have a leap year?
1406 $TEST = date('Y', time()) / 4;
1407 $M1 = date('m', time());
1408 $M2 = date('m', (time() + $timestamp));
1410 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1411 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1413 // First of all years...
1414 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1415 //* DEBUG: */ print("Y={$Y}<br />");
1417 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1418 //* DEBUG: */ print("M={$M}<br />");
1420 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1421 //* DEBUG: */ print("W={$W}<br />");
1423 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1424 //* DEBUG: */ print("D={$D}<br />");
1426 $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));
1427 //* DEBUG: */ print("h={$h}<br />");
1429 $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));
1430 //* DEBUG: */ print("m={$m}<br />");
1431 // And at last seconds...
1432 $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));
1433 //* DEBUG: */ print("s={$s}<br />");
1435 // Is seconds zero and time is < 60 seconds?
1436 if (($s == '0') && ($timestamp < 60)) {
1438 $s = round($timestamp);
1442 // Now we convert them in seconds...
1444 if ($return_array) {
1445 // Just put all data in an array for later use
1457 $OUT = "<div align=\"" . $align."\">\n";
1458 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"timebox_table dashed\">\n";
1461 if (ereg('Y', $display) || (empty($display))) {
1462 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1465 if (ereg('M', $display) || (empty($display))) {
1466 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1469 if (ereg('W', $display) || (empty($display))) {
1470 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1473 if (ereg('D', $display) || (empty($display))) {
1474 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1477 if (ereg('h', $display) || (empty($display))) {
1478 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1481 if (ereg('m', $display) || (empty($display))) {
1482 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1485 if (ereg('s', $display) || (empty($display))) {
1486 $OUT .= " <td align=\"center\" class=\"timebox_column bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1492 if (ereg('Y', $display) || (empty($display))) {
1493 // Generate year selection
1494 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ye\" size=\"1\">\n";
1495 for ($idx = '0'; $idx <= 10; $idx++) {
1496 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1497 if ($idx == $Y) $OUT .= ' selected="selected"';
1498 $OUT .= ">" . $idx."</option>\n";
1500 $OUT .= " </select></td>\n";
1502 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1505 if (ereg('M', $display) || (empty($display))) {
1506 // Generate month selection
1507 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mo\" size=\"1\">\n";
1508 for ($idx = '0'; $idx <= 11; $idx++)
1510 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1511 if ($idx == $M) $OUT .= ' selected="selected"';
1512 $OUT .= ">" . $idx."</option>\n";
1514 $OUT .= " </select></td>\n";
1516 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1519 if (ereg('W', $display) || (empty($display))) {
1520 // Generate week selection
1521 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_we\" size=\"1\">\n";
1522 for ($idx = '0'; $idx <= 4; $idx++) {
1523 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1524 if ($idx == $W) $OUT .= ' selected="selected"';
1525 $OUT .= ">" . $idx."</option>\n";
1527 $OUT .= " </select></td>\n";
1529 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1532 if (ereg('D', $display) || (empty($display))) {
1533 // Generate day selection
1534 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_da\" size=\"1\">\n";
1535 for ($idx = '0'; $idx <= 31; $idx++) {
1536 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1537 if ($idx == $D) $OUT .= ' selected="selected"';
1538 $OUT .= ">" . $idx."</option>\n";
1540 $OUT .= " </select></td>\n";
1542 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1545 if (ereg('h', $display) || (empty($display))) {
1546 // Generate hour selection
1547 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ho\" size=\"1\">\n";
1548 for ($idx = '0'; $idx <= 23; $idx++) {
1549 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1550 if ($idx == $h) $OUT .= ' selected="selected"';
1551 $OUT .= ">" . $idx."</option>\n";
1553 $OUT .= " </select></td>\n";
1555 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1558 if (ereg('m', $display) || (empty($display))) {
1559 // Generate minute selection
1560 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mi\" size=\"1\">\n";
1561 for ($idx = '0'; $idx <= 59; $idx++) {
1562 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1563 if ($idx == $m) $OUT .= ' selected="selected"';
1564 $OUT .= ">" . $idx."</option>\n";
1566 $OUT .= " </select></td>\n";
1568 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1571 if (ereg('s', $display) || (empty($display))) {
1572 // Generate second selection
1573 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_se\" size=\"1\">\n";
1574 for ($idx = '0'; $idx <= 59; $idx++) {
1575 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1576 if ($idx == $s) $OUT .= ' selected="selected"';
1577 $OUT .= ">" . $idx."</option>\n";
1579 $OUT .= " </select></td>\n";
1581 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1584 $OUT .= "</table>\n";
1586 // Return generated HTML code
1592 function createTimestampFromSelections ($prefix, $postData) {
1593 // Initial return value
1596 // Do we have a leap year?
1598 $TEST = date('Y', time()) / 4;
1599 $M1 = date('m', time());
1600 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1601 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
1602 // First add years...
1603 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1605 $ret += $postData[$prefix . '_mo'] * 2628000;
1607 $ret += $postData[$prefix . '_we'] * 604800;
1609 $ret += $postData[$prefix . '_da'] * 86400;
1611 $ret += $postData[$prefix . '_ho'] * 3600;
1613 $ret += $postData[$prefix . '_mi'] * 60;
1614 // And at last seconds...
1615 $ret += $postData[$prefix . '_se'];
1616 // Return calculated value
1620 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1621 function createFancyTime ($stamp) {
1622 // Get data array with years/months/weeks/days/...
1623 $data = createTimeSelections($stamp, '', '', '', true);
1625 foreach($data as $k => $v) {
1627 // Value is greater than 0 "eval" data to return string
1628 eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
1633 // Do we have something there?
1634 if (strlen($ret) > 0) {
1635 // Remove leading commata and space
1636 $ret = substr($ret, 2);
1639 $ret = "0 {--_SECONDS--}";
1642 // Return fancy time string
1646 // Generates a navigation row for listing emails
1647 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1648 $SEP = ''; $TOP = '';
1649 if ($show_form === false) {
1651 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1655 for ($page = 1; $page <= $PAGES; $page++) {
1656 // Is the page currently selected or shall we generate a link to it?
1657 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1658 // Is currently selected, so only highlight it
1659 $NAV .= '<strong>-';
1661 // Open anchor tag and add base URL
1662 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1664 // Add userid when we shall show all mails from a single member
1665 if ((isGetRequestParameterSet('userid')) && (bigintval(getRequestParameter('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestParameter('userid'));
1667 // Close open anchor tag
1671 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1672 // Is currently selected, so only highlight it
1673 $NAV .= '-</strong>';
1679 // Add seperator if we have not yet reached total pages
1680 if ($page < $PAGES) $NAV .= ' | ';
1683 // Define constants only once
1684 $content['nav'] = $NAV;
1685 $content['span'] = $colspan;
1686 $content['top'] = $TOP;
1687 $content['sep'] = $SEP;
1689 // Load navigation template
1690 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1692 if ($return === true) {
1693 // Return generated HTML-Code
1701 // Extract host from script name
1702 function extractHostnameFromUrl (&$script) {
1703 // Use default SERVER_URL by default... ;) So?
1704 $url = getConfig('SERVER_URL');
1706 // Is this URL valid?
1707 if (substr($script, 0, 7) == 'http://') {
1708 // Use the hostname from script URL as new hostname
1709 $url = substr($script, 7);
1710 $extract = explode('/', $url);
1712 // Done extracting the URL :)
1715 // Extract host name
1716 $host = str_replace('http://', '', $url);
1717 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1719 // Generate relative URL
1720 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1721 if (substr(strtolower($script), 0, 7) == 'http://') {
1722 // But only if http:// is in front!
1723 $script = substr($script, (strlen($url) + 7));
1724 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1726 $script = substr($script, (strlen($url) + 8));
1729 //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
1730 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1736 // Send a GET request
1737 function sendGetRequest ($script, $data = array()) {
1738 // Extract host name from script
1739 $host = extractHostnameFromUrl($script);
1742 $body = http_build_query($data, '', '&');
1744 // Do we have a question-mark in the script?
1745 if (strpos($script, '?') === false) {
1746 // No, so first char must be question mark
1747 $body = '?' . $body;
1750 $body = '&' . $body;
1756 // Remove trailed & to make it more conform
1757 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
1759 // Generate GET request header
1760 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1761 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1762 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1763 if (isConfigEntrySet('FULL_VERSION')) {
1764 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1766 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1768 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1769 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1770 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1771 $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1772 $request .= 'Content-Length: 0' . getConfig('HTTP_EOL');
1773 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1774 $request .= getConfig('HTTP_EOL');
1776 // Send the raw request
1777 $response = sendRawRequest($host, $request);
1779 // Return the result to the caller function
1783 // Send a POST request
1784 function sendPostRequest ($script, $postData) {
1785 // Is postData an array?
1786 if (!is_array($postData)) {
1788 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1789 return array('', '', '');
1792 // Extract host name from script
1793 $host = extractHostnameFromUrl($script);
1795 // Construct request
1796 $body = http_build_query($postData, '', '&');
1798 // Generate POST request header
1799 $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1800 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1801 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1802 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1803 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1804 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1805 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1806 $request .= getConfig('HTTP_EOL');
1811 // Send the raw request
1812 $response = sendRawRequest($host, $request);
1814 // Return the result to the caller function
1818 // Sends a raw request to another host
1819 function sendRawRequest ($host, $request) {
1820 // Init errno and errdesc with 'all fine' values
1821 $errno = '0'; $errdesc = '';
1824 $response = array('', '', '');
1826 // Default is not to use proxy
1829 // Are proxy settins set?
1830 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1836 //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1837 if ($useProxy === true) {
1838 // Connect to host through proxy connection
1839 $fp = fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1841 // Connect to host directly
1842 $fp = fsockopen($host, 80, $errno, $errdesc, 30);
1846 if (!is_resource($fp)) {
1848 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
1850 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
1851 // Cannot set non-blocking mode or timeout
1852 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
1857 if ($useProxy === true) {
1858 // Generate CONNECT request header
1859 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.1' . getConfig('HTTP_EOL');
1860 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1862 // Use login data to proxy? (username at least!)
1863 if (getConfig('proxy_username') != '') {
1865 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
1866 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1869 // Add last new-line
1870 $proxyTunnel .= getConfig('HTTP_EOL');
1871 //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1874 fwrite($fp, $proxyTunnel);
1878 // No response received
1882 // Read the first line
1883 $resp = trim(fgets($fp, 10240));
1884 $respArray = explode(' ', $resp);
1885 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1886 // Invalid response!
1892 fwrite($fp, $request);
1895 $start = microtime(true);
1898 while (!feof($fp)) {
1899 // Get info from stream
1900 $info = stream_get_meta_data($fp);
1902 // Is it timed out? 15 seconds is a really patient...
1903 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1905 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1911 // Get line from stream
1912 $line = fgets($fp, 128);
1914 // Ignore empty lines because of non-blocking mode
1916 // uslepp a little to avoid 100% CPU load
1923 // Add it to response
1924 $response[] = trim($line);
1930 // Time request if debug-mode is enabled
1931 if (isDebugModeEnabled()) {
1932 // Add debug message...
1933 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds.');
1936 // Skip first empty lines
1938 foreach ($resp as $idx => $line) {
1940 $line = trim($line);
1942 // Is this line empty?
1945 array_shift($response);
1947 // Abort on first non-empty line
1952 //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1954 // Proxy agent found or something went wrong?
1955 if (!isset($response[0])) {
1956 // No response, maybe timeout
1957 $response = array('', '', '');
1958 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1959 // Proxy header detected, so remove two lines
1960 array_shift($response);
1961 array_shift($response);
1964 // Was the request successfull?
1965 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1966 // Not found / access forbidden
1967 $response = array('', '', '');
1974 // Taken from www.php.net eregi() user comments
1975 function isEmailValid ($email) {
1976 // Check first part of email address
1977 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1980 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1983 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1985 // Return check result
1986 return preg_match($regex, $email);
1989 // Function taken from user comments on www.php.net / function eregi()
1990 function isUrlValid ($URL, $compile=true) {
1991 // Trim URL a little
1992 $URL = trim(urldecode($URL));
1993 //* DEBUG: */ outputHtml($URL.'<br />');
1995 // Compile some chars out...
1996 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1997 //* DEBUG: */ outputHtml($URL.'<br />');
1999 // Check for the extension filter
2000 if (isExtensionActive('filter')) {
2001 // Use the extension's filter set
2002 return FILTER_VALIDATE_URL($URL, false);
2005 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2006 // https:// in front of the URLs
2007 return isUrlValidSimple($URL);
2010 // Generate a list of administrative links to a given userid
2011 function generateMemberAdminActionLinks ($userid, $status = '') {
2012 // Make sure userid is a number
2013 if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
2015 // Define all main targets
2016 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2018 // Begin of navigation links
2021 foreach ($targetArray as $tar) {
2022 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
2023 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
2024 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2025 // Locked accounts shall be unlocked
2026 $OUT .= 'UNLOCK_USER';
2028 // All other status is fine
2029 $OUT .= strtoupper($tar);
2031 $OUT .= '_TITLE--}">{--ADMIN_';
2032 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2033 // Locked accounts shall be unlocked
2034 $OUT .= 'UNLOCK_USER';
2036 // All other status is fine
2037 $OUT .= strtoupper($tar);
2039 $OUT .= '--}</a></span> | ';
2042 // Finish navigation link
2043 $OUT = substr($OUT, 0, -7) . ']';
2049 // Generate an email link
2050 function generateEmailLink ($email, $table = 'admins') {
2051 // Default email link (INSECURE! Spammer can read this by harvester programs)
2052 $EMAIL = 'mailto:' . $email;
2054 // Check for several extensions
2055 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2056 // Create email link for contacting admin in guest area
2057 $EMAIL = generateAdminEmailLink($email);
2058 } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
2059 // Create email link for contacting a member within admin area (or later in other areas, too?)
2060 $EMAIL = generateUserEmailLink($email, 'admin');
2061 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2062 // Create email link to contact sponsor within admin area (or like the link above?)
2063 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2066 // Shall I close the link when there is no admin?
2067 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2069 // Return email link
2073 // Generate a hash for extra-security for all passwords
2074 function generateHash ($plainText, $salt = '') {
2075 // Is the required extension 'sql_patches' there and a salt is not given?
2076 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2077 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2078 return md5($plainText);
2081 // Do we miss an arry element here?
2082 if (!isConfigEntrySet('file_hash')) {
2084 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2087 // When the salt is empty build a new one, else use the first x configured characters as the salt
2089 // Build server string (inc/databases.php is no longer updated with every commit)
2090 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2093 $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');
2096 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2098 // Calculate number for generating the code
2099 $a = time() + getConfig('_ADD') - 1;
2101 // Generate SHA1 sum from modula of number and the prime number
2102 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2103 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2104 $sha1 = scrambleString($sha1);
2105 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2106 //* DEBUG: */ $sha1b = descrambleString($sha1);
2107 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2109 // Generate the password salt string
2110 $salt = substr($sha1, 0, getConfig('salt_length'));
2111 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2114 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2115 $salt = substr($salt, 0, getConfig('salt_length'));
2116 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2118 // Sanity check on salt
2119 if (strlen($salt) != getConfig('salt_length')) {
2121 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2126 return $salt.sha1($salt . $plainText);
2129 // Scramble a string
2130 function scrambleString($str) {
2134 // Final check, in case of failture it will return unscrambled string
2135 if (strlen($str) > 40) {
2136 // The string is to long
2138 } elseif (strlen($str) == 40) {
2140 $scrambleNums = explode(':', getConfig('pass_scramble'));
2142 // Generate new numbers
2143 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2146 // Compare both lengths and abort if different
2147 if (strlen($str) != count($scrambleNums)) return $str;
2149 // Scramble string here
2150 //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2151 for ($idx = '0'; $idx < strlen($str); $idx++) {
2152 // Get char on scrambled position
2153 $char = substr($str, $scrambleNums[$idx], 1);
2155 // Add it to final output string
2156 $scrambled .= $char;
2159 // Return scrambled string
2160 //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2164 // De-scramble a string scrambled by scrambleString()
2165 function descrambleString($str) {
2166 // Scramble only 40 chars long strings
2167 if (strlen($str) != 40) return $str;
2169 // Load numbers from config
2170 $scrambleNums = explode(':', getConfig('pass_scramble'));
2173 if (count($scrambleNums) != 40) return $str;
2175 // Begin descrambling
2176 $orig = str_repeat(' ', 40);
2177 //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2178 for ($idx = '0'; $idx < 40; $idx++) {
2179 $char = substr($str, $idx, 1);
2180 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2183 // Return scrambled string
2184 //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2188 // Generated a "string" for scrambling
2189 function genScrambleString ($len) {
2190 // Prepare array for the numbers
2191 $scrambleNumbers = array();
2193 // First we need to setup randomized numbers from 0 to 31
2194 for ($idx = '0'; $idx < $len; $idx++) {
2196 $rand = mt_rand(0, ($len -1));
2198 // Check for it by creating more numbers
2199 while (array_key_exists($rand, $scrambleNumbers)) {
2200 $rand = mt_rand(0, ($len -1));
2204 $scrambleNumbers[$rand] = $rand;
2207 // So let's create the string for storing it in database
2208 $scrambleString = implode(':', $scrambleNumbers);
2209 return $scrambleString;
2212 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2213 function generatePassString ($passHash) {
2214 // Return vanilla password hash
2217 // Is a secret key and master salt already initialized?
2218 if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2219 // Only calculate when the secret key is generated
2220 $newHash = ''; $start = 9;
2221 for ($idx = '0'; $idx < 10; $idx++) {
2222 $part1 = hexdec(substr($passHash, $start, 4));
2223 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2224 $mod = dechex($idx);
2225 if ($part1 > $part2) {
2226 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2227 } elseif ($part2 > $part1) {
2228 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2230 $mod = substr($mod, 0, 4);
2231 //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2232 $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2233 //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2238 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2239 $ret = generateHash($newHash, getConfig('master_salt'));
2240 //* DEBUG: */ print('ret='.$ret.'<br />');
2243 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2244 $ret = md5($passHash);
2245 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2252 // Fix "deleted" cookies
2253 function fixDeletedCookies ($cookies) {
2254 // Is this an array with entries?
2255 if ((is_array($cookies)) && (count($cookies) > 0)) {
2256 // Then check all cookies if they are marked as deleted!
2257 foreach ($cookies as $cookieName) {
2258 // Is the cookie set to "deleted"?
2259 if (getSession($cookieName) == 'deleted') {
2260 setSession($cookieName, '');
2266 // Output error messages in a fasioned way and die...
2267 function app_die ($F, $L, $message) {
2268 // Check if Script is already dieing and not let it kill itself another 1000 times
2269 if (!isset($GLOBALS['app_died'])) {
2270 // Make sure, that the script realy realy diese here and now
2271 $GLOBALS['app_died'] = true;
2274 loadIncludeOnce('inc/header.php');
2276 // Rewrite message for output
2277 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2279 // Better log this message away
2280 if ($F != 'debug_report_bug') logDebugMessage($F, $L, $message);
2282 // Load the message template
2283 loadTemplate('app_die_message', false, $message);
2286 loadIncludeOnce('inc/footer.php');
2288 // Script tried to kill itself twice
2289 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2293 // Display parsing time and number of SQL queries in footer
2294 function displayParsingTime() {
2295 // Is the timer started?
2296 if (!isset($GLOBALS['startTime'])) {
2302 $endTime = microtime(true);
2304 // "Explode" both times
2305 $start = explode(' ', $GLOBALS['startTime']);
2306 $end = explode(' ', $endTime);
2307 $runTime = $end[0] - $start[0];
2308 if ($runTime < 0) $runTime = '0';
2312 'runtime' => translateComma($runTime),
2313 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2316 // Load the template
2317 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
2320 // Check wether a boolean constant is set
2321 // Taken from user comments in PHP documentation for function constant()
2322 function isBooleanConstantAndTrue ($constName) { // : Boolean
2323 // Failed by default
2327 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2329 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2330 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2333 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2334 if (defined($constName)) {
2336 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2337 $res = (constant($constName) === true);
2341 $GLOBALS['cache_array']['const'][$constName] = $res;
2343 //* DEBUG: */ var_dump($res);
2349 // Checks if a given apache module is loaded
2350 function isApacheModuleLoaded ($apacheModule) {
2351 // Check it and return result
2352 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2355 // Get current theme name
2356 function getCurrentTheme () {
2357 // The default theme is 'default'... ;-)
2360 // Do we have ext-theme installed and active?
2361 if (isExtensionActive('theme')) {
2362 // Call inner method
2363 $ret = getActualTheme();
2366 // Return theme value
2370 // Generates an error code from given account status
2371 function generateErrorCodeFromUserStatus ($status='') {
2372 // If no status is provided, use the default, cached
2373 if ((empty($status)) && (isMember())) {
2375 $status = getUserData('status');
2378 // Default error code if unknown account status
2379 $errorCode = getCode('UNKNOWN_STATUS');
2381 // Generate constant name
2382 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2384 // Is the constant there?
2385 if (isCodeSet($codeName)) {
2387 $errorCode = getCode($codeName);
2390 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2393 // Return error code
2397 // Function to search for the last modifified file
2398 function searchDirsRecursive ($dir, &$last_changed) {
2400 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2401 // Does it match what we are looking for? (We skip a lot files already!)
2402 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2403 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2404 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2405 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2407 // Walk through all entries
2408 foreach ($ds as $d) {
2409 // Generate proper FQFN
2410 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2412 // Is it a file and readable?
2413 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2414 if (isDirectory($FQFN)) {
2415 // $FQFN is a directory so also crawl into this directory
2417 if (!empty($dir)) $newDir = $dir . '/'. $d;
2418 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2419 searchDirsRecursive($newDir, $last_changed);
2420 } elseif (isFileReadable($FQFN)) {
2421 // $FQFN is a filename and no directory
2422 $time = filemtime($FQFN);
2423 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2424 if ($last_changed['time'] < $time) {
2425 // This file is newer as the file before
2426 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2427 $last_changed['path_name'] = $FQFN;
2428 $last_changed['time'] = $time;
2434 // "Getter" for revision/version data
2435 function getActualVersion ($type = 'Revision') {
2436 // By default nothing is new... ;-)
2439 // Is the cache entry there?
2440 if (isset($GLOBALS['cache_array']['revision'][$type])) {
2441 // Found so increase cache hit
2442 incrementStatsEntry('cache_hits');
2445 return $GLOBALS['cache_array']['revision'][$type][0];
2447 // FQFN of revision file
2448 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2450 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2451 if ((isGetRequestParameterSet('check_revision_data')) && (getRequestParameter('check_revision_data') == 'yes')) {
2452 // Forced rebuild of .revision file
2455 // Check for revision file
2456 if (!isFileReadable($FQFN)) {
2457 // Not found, so we need to create it
2460 // Revision file found
2461 $ins_vers = explode("\n", readFromFile($FQFN));
2463 // Get array for mapping information
2464 $mapper = array_flip(getSearchFor());
2465 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2467 // Is the content valid?
2468 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2469 // File needs update!
2472 // Generate fake cache entry
2473 foreach ($mapper as $map => $idx) {
2474 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2477 // Return found value
2478 return trim($ins_vers[$mapper[$type]]);
2483 // Has it been updated?
2484 if ($new === true) {
2486 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2488 // ... and call recursive
2489 return getActualVersion($type);
2494 // Repares an array we are looking for
2495 // The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
2496 function getSearchFor () {
2497 // Add Revision, Date, Tag and Author
2498 $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2500 // Return the created array
2504 // @TODO Please describe this function
2505 function getArrayFromActualVersion () {
2509 // Directory to start with search
2510 $last_changed = array(
2515 // Init return array
2516 $akt_vers = array();
2518 // Init value for counting the founded keywords
2521 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2522 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2525 $last_file = readFromFile($last_changed['path_name']);
2527 // Get all the keywords to search for
2528 $searchFor = getSearchFor();
2530 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2531 foreach ($searchFor as $search) {
2532 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2533 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2534 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2535 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2538 // Save the last-changed filename for debugging
2539 $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2541 // at least 3 keyword-Tags are needed for propper values
2542 if ($res && $res >= 3
2543 && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2544 && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2545 && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2546 // Prepare content witch need special treadment
2548 // Prepare timestamp for date
2549 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2550 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2552 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2553 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2554 $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2558 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2559 $version = sendGetRequest('check-updates3.php');
2562 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2563 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2564 if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
2565 if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
2566 if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
2567 if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
2570 // Return prepared array
2571 return $GLOBALS['cache_array']['revision'];
2574 // Back-ported from the new ship-simu engine. :-)
2575 function debug_get_printable_backtrace () {
2577 $backtrace = "<ol>\n";
2579 // Get and prepare backtrace for output
2580 $backtraceArray = debug_backtrace();
2581 foreach ($backtraceArray as $key => $trace) {
2582 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2583 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2584 if (!isset($trace['args'])) $trace['args'] = array();
2585 $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";
2589 $backtrace .= "</ol>\n";
2591 // Return the backtrace
2595 // A mail-able backtrace
2596 function debug_get_mailable_backtrace () {
2600 // Get and prepare backtrace for output
2601 $backtraceArray = debug_backtrace();
2602 foreach ($backtraceArray as $key => $trace) {
2603 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2604 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2605 if (!isset($trace['args'])) $trace['args'] = array();
2606 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2609 // Return the backtrace
2613 // Output a debug backtrace to the user
2614 function debug_report_bug ($message = '', $sendEmail = true) {
2615 // Is this already called?
2616 if (isset($GLOBALS[__FUNCTION__])) {
2618 print 'Message:'.$message.'<br />Backtrace:<pre>';
2619 debug_print_backtrace();
2623 // Set this function as called
2624 $GLOBALS[__FUNCTION__] = true;
2629 // Is the optional message set?
2630 if (!empty($message)) {
2632 $debug = sprintf("Note: %s<br />\n",
2636 // @TODO Add a little more infos here
2637 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2641 $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>";
2642 $debug .= debug_get_printable_backtrace();
2643 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2644 $debug .= "Thank you for finding bugs.";
2646 // Send an email? (e.g. not wanted for evaluation errors)
2647 if (($sendEmail === true) && (!isInstallationPhase())) {
2650 'message' => trim($message),
2651 'backtrace' => trim(debug_get_mailable_backtrace())
2654 // Send email to webmaster
2655 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2659 app_die(__FUNCTION__, __LINE__, $debug);
2662 // Generates a ***weak*** seed
2663 function generateSeed () {
2664 return microtime(true) * 100000;
2667 // Converts a message code to a human-readable message
2668 function getMessageFromErrorCode ($code) {
2672 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2673 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2674 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2675 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2676 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2677 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2678 case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2679 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2680 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2681 case getCode('ACCOUNT_LOCKED') : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2682 case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2683 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2684 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2685 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2686 case getCode('MODULE_MEM_ONLY') : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestParameter('mod')); break;
2687 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2688 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2689 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2690 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestParameter('blist'), 0); break;
2691 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2692 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2693 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2694 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2695 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2696 case getCode('MORE_RECEIVERS3') : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
2697 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2698 case getCode('UNKNOWN_ERROR') : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
2699 case getCode('UNKNOWN_STATUS') : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
2701 case getCode('ERROR_MAILID'):
2702 if (isExtensionActive('mailid', true)) {
2703 $message = getMessage('ERROR_CONFIRMING_MAIL');
2705 $message = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'mailid');
2709 case getCode('EXTENSION_PROBLEM'):
2710 if (isGetRequestParameterSet('ext')) {
2711 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
2713 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2717 case getCode('URL_TLOCK'):
2718 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2719 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2720 array(bigintval(getRequestParameter('id'))), __FILE__, __LINE__);
2722 // Load timestamp from last order
2723 list($timestamp) = SQL_FETCHROW($result);
2726 SQL_FREERESULT($result);
2728 // Translate it for templates
2729 $timestamp = generateDateTime($timestamp, 1);
2731 // Calculate hours...
2732 $STD = round(getConfig('url_tlock') / 60 / 60);
2735 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2738 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2740 // Finally contruct the message
2741 // @TODO Rewrite this old lost code to a template
2742 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2743 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2744 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2748 // Missing/invalid code
2749 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2752 logDebugMessage(__FUNCTION__, __LINE__, $message);
2756 // Return the message
2760 // Compile characters which are allowed in URLs
2761 function compileUriCode ($code, $simple = true) {
2762 // Compile constants
2763 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2765 // Compile QUOT and other non-HTML codes
2766 $code = str_replace('{DOT}', '.',
2767 str_replace('{SLASH}', '/',
2768 str_replace('{QUOT}', "'",
2769 str_replace('{DOLLAR}', '$',
2770 str_replace('{OPEN_ANCHOR}', '(',
2771 str_replace('{CLOSE_ANCHOR}', ')',
2772 str_replace('{OPEN_SQR}', '[',
2773 str_replace('{CLOSE_SQR}', ']',
2774 str_replace('{PER}', '%',
2778 // Return compiled code
2782 // Function taken from user comments on www.php.net / function eregi()
2783 function isUrlValidSimple ($url) {
2785 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2787 // Allows http and https
2788 $http = "(http|https)+(:\/\/)";
2790 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2791 // Test double-domains (e.g. .de.vu)
2792 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2794 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2796 $dir = "((/)+([-_\.[:alnum:]])+)*";
2798 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2799 // ... and the string after and including question character
2800 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2801 // Pattern for URLs like http://url/dir/doc.html?var=value
2802 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2803 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2804 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2805 // Pattern for URLs like http://url/dir/?var=value
2806 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2807 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2808 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2809 // Pattern for URLs like http://url/dir/page.ext
2810 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2811 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2812 $pattern['ipdp'] = $http . $ip . $dir . $page;
2813 // Pattern for URLs like http://url/dir
2814 $pattern['d1d'] = $http . $domain1 . $dir;
2815 $pattern['d2d'] = $http . $domain2 . $dir;
2816 $pattern['ipd'] = $http . $ip . $dir;
2817 // Pattern for URLs like http://url/?var=value
2818 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2819 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2820 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2821 // Pattern for URLs like http://url?var=value
2822 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2823 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2824 $pattern['ipg12'] = $http . $ip . $getstring1;
2825 // Test all patterns
2827 foreach ($pattern as $key => $pat) {
2829 if (isDebugRegExpressionEnabled()) {
2830 // @TODO Are these convertions still required?
2831 $pat = str_replace('.', "\.", $pat);
2832 $pat = str_replace('@', "\@", $pat);
2833 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2836 // Check if expression matches
2837 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2840 if ($reg === true) break;
2843 // Return true/false
2847 // Wtites data to a config.php-style file
2848 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2849 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2850 // Initialize some variables
2856 // Is the file there and read-/write-able?
2857 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2858 $search = 'CFG: ' . $comment;
2859 $tmp = $FQFN . '.tmp';
2861 // Open the source file
2862 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2864 // Is the resource valid?
2865 if (is_resource($fp)) {
2866 // Open temporary file
2867 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2869 // Is the resource again valid?
2870 if (is_resource($fp_tmp)) {
2871 // Mark temporary file as readable
2872 $GLOBALS['file_readable'][$tmp] = true;
2875 while (!feof($fp)) {
2876 // Read from source file
2877 $line = fgets ($fp, 1024);
2879 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2882 if ($next === $seek) {
2884 $line = $prefix . $DATA . $suffix . "\n";
2890 // Write to temp file
2891 fwrite($fp_tmp, $line);
2897 // Finished writing tmp file
2901 // Close source file
2904 if (($done === true) && ($found === true)) {
2905 // Copy back tmp file and delete tmp :-)
2906 copyFileVerified($tmp, $FQFN, 0644);
2907 return removeFile($tmp);
2908 } elseif ($found === false) {
2909 outputHtml('<strong>CHANGE:</strong> 404!');
2911 outputHtml('<strong>TMP:</strong> UNDONE!');
2915 // File not found, not readable or writeable
2916 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2919 // An error was detected!
2922 // Send notification to admin
2923 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2924 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2926 sendAdminsEmails($subject, $templateName, $content, $userid);
2928 // Send out out-dated way
2929 $message = loadEmailTemplate($templateName, $content, $userid);
2930 sendAdminEmails($subject, $message);
2934 // Debug message logger
2935 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2936 // Is debug mode enabled?
2937 if ((isDebugModeEnabled()) || ($force === true)) {
2939 $message = str_replace("\r", '', str_replace("\n", '', $message));
2941 // Log this message away, we better don't call app_die() here to prevent an endless loop
2942 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2943 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2948 // Handle extra values
2949 function handleExtraValues ($filterFunction, $value, $extraValue) {
2950 // Default is the value itself
2953 // Do we have a special filter function?
2954 if (!empty($filterFunction)) {
2955 // Does the filter function exist?
2956 if (function_exists($filterFunction)) {
2957 // Do we have extra parameters here?
2958 if (!empty($extraValue)) {
2959 // Put both parameters in one new array by default
2960 $args = array($value, $extraValue);
2962 // If we have an array simply use it and pre-extend it with our value
2963 if (is_array($extraValue)) {
2964 // Make the new args array
2965 $args = merge_array(array($value), $extraValue);
2968 // Call the multi-parameter call-back
2969 $ret = call_user_func_array($filterFunction, $args);
2971 // One parameter call
2972 $ret = call_user_func($filterFunction, $value);
2981 // Converts timestamp selections into a timestamp
2982 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2983 // Init test variable
2987 // Get last three chars
2988 $test = substr($id, -3);
2990 // Improved way of checking! :-)
2991 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2992 // Found a multi-selection for timings?
2993 $test = substr($id, 0, -3);
2994 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)) {
2995 // Generate timestamp
2996 $postData[$test] = createTimestampFromSelections($test, $postData);
2997 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2998 $GLOBALS['skip_config'][$test] = true;
3000 // Remove data from array
3001 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3002 unset($postData[$test . '_' . $rem]);
3013 // Reverts the german decimal comma into Computer decimal dot
3014 function convertCommaToDot ($str) {
3015 // Default float is not a float... ;-)
3018 // Which language is selected?
3019 switch (getLanguage()) {
3020 case 'de': // German language
3021 // Remove german thousand dots first
3022 $str = str_replace('.', '', $str);
3024 // Replace german commata with decimal dot and cast it
3025 $float = (float)str_replace(',', '.', $str);
3028 default: // US and so on
3029 // Remove thousand dots first and cast
3030 $float = (float)str_replace(',', '', $str);
3038 // Handle menu-depending failed logins and return the rendered content
3039 function handleLoginFailtures ($accessLevel) {
3040 // Default output is empty ;-)
3043 // Is the session data set?
3044 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3045 // Ignore zero values
3046 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3047 // Non-guest has login failures found, get both data and prepare it for template
3048 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3050 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3051 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
3055 $OUT = loadTemplate('login_failures', true, $content);
3058 // Reset session data
3059 setSession('mxchange_' . $accessLevel.'_failures', '');
3060 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3063 // Return rendered content
3068 function rebuildCacheFile ($cache, $inc = '', $force = false) {
3070 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3072 // Shall I remove the cache file?
3073 if (isCacheInstanceValid()) {
3075 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3077 $GLOBALS['cache_instance']->removeCacheFile($force);
3080 // Include file given?
3083 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3085 // Is the include there?
3086 if (isIncludeReadable($inc)) {
3087 // And rebuild it from scratch
3088 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3091 // Include not found!
3092 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3098 // Determines the real remote address
3099 function determineRealRemoteAddress () {
3100 // Is a proxy in use?
3101 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3103 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3104 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3105 // Yet, another proxy
3106 $address = $_SERVER['HTTP_CLIENT_IP'];
3108 // The regular address when no proxy was used
3109 $address = $_SERVER['REMOTE_ADDR'];
3112 // This strips out the real address from proxy output
3113 if (strstr($address, ',')) {
3114 $addressArray = explode(',', $address);
3115 $address = $addressArray[0];
3118 // Return the result
3122 // Adds a bonus mail to the queue
3123 // This is a high-level function!
3124 function addNewBonusMail ($data, $mode = '', $output=true) {
3125 // Use mode from data if not set and availble ;-)
3126 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3128 // Generate receiver list
3129 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3132 if (!empty($receiver)) {
3133 // Add bonus mail to queue
3134 addBonusMailToQueue(
3146 // Mail inserted into bonus pool
3147 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3148 } elseif ($output) {
3149 // More entered than can be reached!
3150 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3153 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3157 // Determines referal id and sets it
3158 function determineReferalId () {
3159 // Skip this in non-html-mode and outside ref.php
3160 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3162 // Check if refid is set
3163 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3165 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3166 // The variable user comes from the click-counter script click.php and we only accept this here
3167 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
3168 } elseif (isPostRequestParameterSet('refid')) {
3169 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3170 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
3171 } elseif (isGetRequestParameterSet('refid')) {
3172 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3173 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
3174 } elseif (isGetRequestParameterSet('ref')) {
3175 // Set refid=ref (the referal link uses such variable)
3176 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
3177 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3178 // Set session refid als global
3179 $GLOBALS['refid'] = bigintval(getSession('refid'));
3180 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3181 // Select a random user which has confirmed enougth mails
3182 $GLOBALS['refid'] = determineRandomReferalId();
3183 } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3184 // Set default refid as refid in URL
3185 $GLOBALS['refid'] = getConfig('def_refid');
3187 // No default id when sql_patches is not installed or none set
3188 $GLOBALS['refid'] = '0';
3191 // Set cookie when default refid > 0
3192 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3193 // Default is not found
3196 // Do we have nickname or userid set?
3197 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3198 // Nickname in URL, so load the id
3199 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3200 } elseif ($GLOBALS['refid'] > 0) {
3201 // Direct userid entered
3202 $found = fetchUserData($GLOBALS['refid']);
3205 // Is the record valid?
3206 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3207 // No, then reset referal id
3208 $GLOBALS['refid'] = getConfig('def_refid');
3212 setSession('refid', $GLOBALS['refid']);
3215 // Return determined refid
3216 return $GLOBALS['refid'];
3219 // Enables the reset mode and runs it
3220 function doReset () {
3221 // Enable the reset mode
3222 $GLOBALS['reset_enabled'] = true;
3225 runFilterChain('reset');
3228 // Our shutdown-function
3229 function shutdown () {
3230 // Call the filter chain 'shutdown'
3231 runFilterChain('shutdown', null);
3233 // Check if not in installation phase and the link is up
3234 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
3236 SQL_CLOSE(__FILE__, __LINE__);
3237 } elseif (!isInstallationPhase()) {
3239 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3242 // Stop executing here
3247 function initMemberId () {
3248 $GLOBALS['member_id'] = '0';
3251 // Setter for member id
3252 function setMemberId ($memberid) {
3253 // We should not set member id to zero
3254 if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3257 $GLOBALS['member_id'] = bigintval($memberid);
3260 // Getter for member id or returns zero
3261 function getMemberId () {
3262 // Default member id
3265 // Is the member id set?
3266 if (isMemberIdSet()) {
3268 $memberid = $GLOBALS['member_id'];
3275 // Checks ether the member id is set
3276 function isMemberIdSet () {
3277 return (isset($GLOBALS['member_id']));
3280 // Handle message codes from URL
3281 function handleCodeMessage () {
3282 if (isGetRequestParameterSet('code')) {
3283 // Default extension is 'unknown'
3286 // Is extension given?
3287 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
3289 // Convert the 'code' parameter from URL to a human-readable message
3290 $message = getMessageFromErrorCode(getRequestParameter('code'));
3292 // Load message template
3293 loadTemplate('message', false, $message);
3297 // Setter for extra title
3298 function setExtraTitle ($extraTitle) {
3299 $GLOBALS['extra_title'] = $extraTitle;
3302 // Getter for extra title
3303 function getExtraTitle () {
3304 // Is the extra title set?
3305 if (!isExtraTitleSet()) {
3306 // No, then abort here
3307 debug_report_bug('extra_title is not set!');
3311 return $GLOBALS['extra_title'];
3314 // Checks if the extra title is set
3315 function isExtraTitleSet () {
3316 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3319 // Generates a 'extension foo inactive' message
3320 function generateExtensionInactiveMessage ($ext_name) {
3321 // Is the extension empty?
3322 if (empty($ext_name)) {
3323 // This should not happen
3324 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3328 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3330 // Is an admin logged in?
3332 // Then output admin message
3333 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3336 // Return prepared message
3340 // Generates a 'extension foo not installed' message
3341 function generateExtensionNotInstalledMessage ($ext_name) {
3342 // Is the extension empty?
3343 if (empty($ext_name)) {
3344 // This should not happen
3345 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3349 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3351 // Is an admin logged in?
3353 // Then output admin message
3354 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
3357 // Return prepared message
3361 // Generates a message depending on if the extension is not installed or not
3363 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3367 // Is the extension not installed or just deactivated?
3368 switch (isExtensionInstalled($ext_name)) {
3369 case true; // Deactivated!
3370 $message = generateExtensionInactiveMessage($ext_name);
3373 case false; // Not installed!
3374 $message = generateExtensionNotInstalledMessage($ext_name);
3377 default: // Should not happen!
3378 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3379 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3383 // Return the message
3387 // Reads a directory recursively by default and searches for files not matching
3388 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3389 // a whole directory.
3390 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3391 // Add default entries we should exclude
3392 $excludeArray[] = '.';
3393 $excludeArray[] = '..';
3394 $excludeArray[] = '.svn';
3395 $excludeArray[] = '.htaccess';
3397 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3402 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3405 while ($baseFile = readdir($dirPointer)) {
3406 // Exclude '.', '..' and entries in $excludeArray automatically
3407 if (in_array($baseFile, $excludeArray, true)) {
3409 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3413 // Construct include filename and FQFN
3414 $fileName = $baseDir . $baseFile;
3415 $FQFN = getConfig('PATH') . $fileName;
3417 // Remove double slashes
3418 $FQFN = str_replace('//', '/', $FQFN);
3420 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3421 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3422 // These Lines are only for debugging!!
3423 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3424 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3425 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3431 // Skip also files with non-matching prefix genericly
3432 if (($recursive === true) && (isDirectory($FQFN))) {
3433 // Is a redirectory so read it as well
3434 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3436 // And skip further processing
3438 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3440 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3442 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3443 // Skip wrong suffix as well
3444 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3446 } elseif (!isFileReadable($FQFN)) {
3447 // Not readable so skip it
3448 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3452 // Is the file a PHP script or other?
3453 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3454 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3455 // Is this a valid include file?
3456 if ($extension == '.php') {
3457 // Remove both for extension name
3458 $extName = substr($baseFile, strlen($prefix), -4);
3460 // Is the extension valid and active?
3461 if (isExtensionNameValid($extName)) {
3462 // Then add this file
3463 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3464 $files[] = $fileName;
3466 // Add non-extension files as well
3467 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3468 if ($addBaseDir === true) {
3469 $files[] = $fileName;
3471 $files[] = $baseFile;
3475 // We found .php file but should not search for them, why?
3476 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3478 } elseif (substr($baseFile, -4, 4) == $extension) {
3479 // Other, generic file found
3480 $files[] = $fileName;
3485 closedir($dirPointer);
3490 // Return array with include files
3491 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3495 // Maps a module name into a database table name
3496 function mapModuleToTable ($moduleName) {
3497 // Map only these, still lame code...
3498 switch ($moduleName) {
3499 // 'index' is the guest's menu
3500 case 'index': $moduleName = 'guest'; break;
3501 // ... and 'login' the member's menu
3502 case 'login': $moduleName = 'member'; break;
3503 // Anything else will not be mapped, silently.
3510 // Add SQL debug data to array for later output
3511 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3512 // Already executed?
3513 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3514 // Then abort here, we don't need to profile a query twice
3518 // Remeber this as profiled (or not, but we don't care here)
3519 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3521 // Do we have cache?
3522 if (!isset($GLOBALS['debug_sql_available'])) {
3523 // Check it and cache it in $GLOBALS
3524 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3527 // Don't execute anything here if we don't need or ext-other is missing
3528 if ($GLOBALS['debug_sql_available'] === false) {
3534 'num_rows' => SQL_NUMROWS($result),
3535 'affected' => SQL_AFFECTEDROWS(),
3536 'sql_str' => $sqlString,
3537 'timing' => $timing,
3538 'file' => basename($F),
3543 $GLOBALS['debug_sqls'][] = $record;
3546 // Initializes the cache instance
3547 function initCacheInstance () {
3548 // Load include for CacheSystem class
3549 loadIncludeOnce('inc/classes/cachesystem.class.php');
3551 // Initialize cache system only when it's needed
3552 $GLOBALS['cache_instance'] = new CacheSystem();
3553 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3554 // Failed to initialize cache sustem
3555 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3559 // Getter for message from array or raw message
3560 function getMessageFromIndexedArray ($message, $pos, $array) {
3561 // Check if the requested message was found in array
3562 if (isset($array[$pos])) {
3563 // ... if yes then use it!
3564 $ret = $array[$pos];
3566 // ... else use default message
3574 // Print code with line numbers
3575 function linenumberCode ($code) {
3576 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3577 $count_lines = count($codeE);
3579 $r = 'Line | Code:<br />';
3580 foreach($codeE as $line => $c) {
3581 $r .= '<div class="line"><span class="linenum">';
3582 if ($count_lines == 1) {
3585 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3590 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3593 return '<div class="code">' . $r . '</div>';
3596 // Convert ';' to ', ' for e.g. receiver list
3597 function convertReceivers ($old) {
3598 return str_replace(';', ', ', $old);
3601 // Determines the right page title
3602 function determinePageTitle () {
3603 // Config and database connection valid?
3604 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3608 // Title decoration enabled?
3609 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3611 // Do we have some extra title?
3612 if (isExtraTitleSet()) {
3614 $TITLE .= getExtraTitle() . ' by ';
3618 $TITLE .= getConfig('MAIN_TITLE');
3620 // Add title of module? (middle decoration will also be added!)
3621 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3622 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3625 // Add title from what file
3627 if (getModule() == 'login') $mode = 'member';
3628 elseif (getModule() == 'index') $mode = 'guest';
3629 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3631 // Add title decorations? (right)
3632 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3634 // Remember title in constant for the template
3635 $pageTitle = $TITLE;
3636 } elseif ((isInstalled()) && (isAdminRegistered())) {
3637 // Installed, admin registered but no ext-sql_patches
3638 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3639 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3640 // Installed but no admin registered
3641 $pageTitle = getMessage('SETUP_OF_MXCHANGE');
3642 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3643 // Installation mode
3644 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3646 // Configuration not found!
3647 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3649 // Do not add the fatal message in installation mode
3650 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3654 return decodeEntities($pageTitle);
3657 // Checks wethere there is a cache file there. This function is cached.
3658 function isTemplateCached ($template) {
3659 // Do we have cached this result?
3660 if (!isset($GLOBALS['template_cache'][$template])) {
3662 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3665 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3669 return $GLOBALS['template_cache'][$template];
3672 // Flushes non-flushed template cache to disk
3673 function flushTemplateCache ($template, $eval) {
3674 // Is this cache flushed?
3675 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3677 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3679 // Replace username with a call
3680 $eval = str_replace('$username', '".getUsername()."', $eval);
3683 writeToFile($FQFN, $eval, true);
3687 // Reads a template cache
3688 function readTemplateCache ($template) {
3690 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3692 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3695 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3699 return $GLOBALS['template_eval'][$template];
3702 // Escapes quotes (default is only double-quotes)
3703 function escapeQuotes ($str, $single = false) {
3704 // Should we escape all?
3705 if ($single === true) {
3706 // Escape all (including null)
3707 $str = addslashes($str);
3709 // Escape only double-quotes but prevent double-quoting
3710 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3713 // Return the escaped string
3717 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3718 function escapeJavaScriptQuotes ($str) {
3719 // Replace all double-quotes and secure back-ticks
3720 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3726 // Send out mails depending on the 'mod/modes' combination
3727 // @TODO Lame description for this function
3728 function sendModeMails ($mod, $modes) {
3730 if (fetchUserData(getMemberId())) {
3731 // Extract salt from cookie
3732 $salt = substr(getSession('u_hash'), 0, -40);
3734 // Now let's compare passwords
3735 $hash = generatePassString(getUserData('password'));
3737 // Does the hash match or should we change it?
3738 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
3740 $content = getUserDataArray();
3743 $content['gender'] = translateGender($content['gender']);
3745 // Clear/init the content variable
3746 $content['message'] = '';
3749 // @TODO Move this in a filter
3752 foreach ($modes as $mode) {
3754 case 'normal': break; // Do not add any special lines
3755 case 'email': // Email was changed!
3756 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestParameter('old_email')."\n";
3759 case 'pass': // Password was changed
3760 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3764 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3765 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3770 if (isExtensionActive('country')) {
3771 // Replace code with description
3772 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
3775 // Merge content with data from POST
3776 $content = merge_array($content, postRequestArray());
3779 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3781 if (getConfig('admin_notify') == 'Y') {
3782 // The admin needs to be notified about a profile change
3783 $message_admin = 'admin_mydata_notify';
3784 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3787 $message_admin = '';
3791 // Set subject lines
3792 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3794 // Output success message
3795 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3798 default: // Unsupported module!
3799 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3800 $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
3804 // Passwords mismatch
3805 $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
3808 // Could not load profile
3809 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
3812 // Send email to user if required
3813 if ((!empty($sub_mem)) && (!empty($message))) {
3815 sendEmail($content['email'], $sub_mem, $message);
3818 // Send only if no other error has occured
3819 if (empty($content)) {
3820 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3822 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3823 } elseif (getConfig('admin_notify') == 'Y') {
3824 // Cannot send mails to admin!
3825 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3828 $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3833 loadTemplate('admin_settings_saved', false, $content);
3836 // Generates a 'selection box' from given array
3837 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent) {
3839 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3840 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3842 // Walk through all options
3843 foreach ($options as $option) {
3844 // Add the <option> entry
3845 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3848 // Finish selection box
3849 $OUT .= '</select>';
3853 'selection_box' => $OUT,
3854 'module' => getModule(),
3858 // Load template and return it
3859 return loadTemplate('select_' . $name . '_box', true, $content);
3862 // Get a module from filename and access level
3863 function getModuleFromFileName ($file, $accessLevel) {
3864 // Default is 'invalid';
3865 $modCheck = 'invalid';
3867 // @TODO This is still very static, rewrite it somehow
3868 switch ($accessLevel) {
3870 $modCheck = 'admin';
3876 $modCheck = getModule();
3879 default: // Unsupported file name / access level
3880 debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3888 // Encodes an URL for adding session id, etc.
3889 function encodeUrl ($url, $outputMode = '0') {
3890 // Do we have already have a PHPSESSID inside? Then it is already converted...
3891 if (strpos($url, session_name()) !== false) return $url;
3893 // Do we have a valid session?
3894 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3896 // Determine right seperator
3897 $seperator = '&';
3898 if (strpos($url, '?') === false) {
3901 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3907 if (session_id() != '') {
3908 $url .= $seperator . session_name() . '=' . session_id();
3913 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3915 $url = '{?URL?}/' . $url;
3922 // Simple check for spider
3923 function isSpider () {
3925 $userAgent = strtolower(detectUserAgent(true));
3927 // It should not be empty, if so it is better a spider/bot
3928 if (empty($userAgent)) return true;
3931 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false));
3934 // Prepares the header for HTML output
3935 function loadHtmlHeader () {
3936 // Determine the page title
3937 $content['header_title'] = determinePageTitle();
3939 // Output page header code
3940 $GLOBALS['page_header'] = loadTemplate('page_header', true, $content);
3942 // Include meta data in 'guest' module
3943 if (getModule() == 'index') {
3944 // Load meta data template
3945 $GLOBALS['page_header'] .= loadTemplate('metadata', true);
3947 // Add meta description to header
3948 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
3949 // Add meta description not in admin and login module and when the script is installed
3950 generateMetaDescriptionCode();
3954 // Include more header data here
3955 $GLOBALS['page_header'] .= loadTemplate('header', true);
3957 // Include stylesheet
3958 loadIncludeOnce('inc/stylesheet.php');
3961 $GLOBALS['page_header'] .= '</head>';
3964 // Adds page header and footer to output array element
3965 function addPageHeaderFooter () {
3966 // Add them all together. This is maybe to simple
3967 $GLOBALS['output'] = $GLOBALS['page_header'] . $GLOBALS['output'] . $GLOBALS['page_footer'];
3970 // Generates meta description for current module and 'what' value
3971 function generateMetaDescriptionCode () {
3972 // Only include from guest area
3973 if (getModule() == 'index') {
3974 // Construct dynamic description
3975 $DESCR = '{?MAIN_TITLE?} '.trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
3977 // Output it directly
3978 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
3982 unset($GLOBALS['ref_level']);
3985 //////////////////////////////////////////////////
3986 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3987 //////////////////////////////////////////////////
3989 if (!function_exists('html_entity_decode')) {
3990 // Taken from documentation on www.php.net
3991 function html_entity_decode ($string) {
3992 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3993 $trans_tbl = array_flip($trans_tbl);
3994 return strtr($string, $trans_tbl);
3998 if (!function_exists('http_build_query')) {
3999 // Taken from documentation on www.php.net, credits to Marco K. (Germany)
4000 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
4002 foreach ((array)$data as $k => $v) {
4003 if (is_int($k) && $prefix != null) {
4004 $k = urlencode($prefix . $k);
4007 if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
4009 if (is_array($v) || is_object($v)) {
4010 array_push($ret, http_build_query($v, '', $sep, $k));
4012 array_push($ret, $k.'='.urlencode($v));
4016 if (empty($sep)) $sep = ini_get('arg_separator.output');
4018 return implode($sep, $ret);