2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/25/2003 *
4 * =================== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
46 function outputHtml ($htmlCode, $newLine = true) {
48 if (!isset($GLOBALS['output'])) {
49 $GLOBALS['output'] = '';
53 $username = getMessage('USERNAME_UNKNOWN');
54 if (isset($GLOBALS['username'])) $username = getUsername();
56 // Do we have HTML-Code here?
57 if (!empty($htmlCode)) {
58 // Yes, so we handle it as you have configured
59 switch (getConfig('OUTPUT_MODE')) {
61 // That's why you don't need any \n at the end of your HTML code... :-)
62 if (getPhpCaching() == 'on') {
63 // Output into PHP's internal buffer
64 outputRawCode($htmlCode);
66 // That's why you don't need any \n at the end of your HTML code... :-)
67 if ($newLine === true) print("\n");
69 // Render mode for old or lame servers...
70 $GLOBALS['output'] .= $htmlCode;
72 // That's why you don't need any \n at the end of your HTML code... :-)
73 if ($newLine === true) $GLOBALS['output'] .= "\n";
78 // If we are switching from render to direct output rendered code
79 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
81 // The same as above... ^
82 outputRawCode($htmlCode);
83 if ($newLine === true) print("\n");
87 // Huh, something goes wrong or maybe you have edited config.php ???
88 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
91 } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
92 // Output cached HTML code
93 $GLOBALS['output'] = ob_get_contents();
95 // Clear output buffer for later output if output is found
96 if (!empty($GLOBALS['output'])) {
100 // Send all HTTP headers
103 // Compile and run finished rendered HTML code
104 compileFinalOutput();
106 // Output code here, DO NOT REMOVE! ;-)
107 outputRawCode($GLOBALS['output']);
108 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
109 // Send all HTTP headers
112 // Compile and run finished rendered HTML code
113 compileFinalOutput();
115 // Output code here, DO NOT REMOVE! ;-)
116 outputRawCode($GLOBALS['output']);
118 // And flush all headers
123 // Sends out all headers required for HTTP/1.1 reply
124 function sendHttpHeaders () {
126 $now = gmdate('D, d M Y H:i:s') . ' GMT';
129 sendHeader('HTTP/1.1 ' . getHttpStatus());
131 // General headers for no caching
132 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
133 sendHeader('Last-Modified: ' . $now);
134 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
135 sendHeader('Pragma: no-cache'); // HTTP/1.0
136 sendHeader('Connection: Close');
137 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
138 sendHeader('Content-Language: ' . getLanguage());
141 // Compiles the final output
142 function compileFinalOutput () {
146 // Add page header and footer
147 addPageHeaderFooter();
150 while (((strpos($GLOBALS['output'], '{--') !== false) || (strpos($GLOBALS['output'], '{DQUOTE}') !== false) || (strpos($GLOBALS['output'], '{!') !== false) || (strpos($GLOBALS['output'], '{?') !== false) || (strpos($GLOBALS['output'], '{%') !== false)) && ($cnt < 3)) {
151 // Init common variables
156 //* DEBUG: */ print '<pre>'.htmlentities($GLOBALS['output']).'</pre>';
157 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($GLOBALS['output']))) . '";';
158 //* DEBUG: */ die('<pre>'.htmlentities($eval).'</pre>');
160 //* DEBUG: */ die('<pre>'.htmlentities($newContent).'</pre>');
162 // Was that eval okay?
163 if (empty($newContent)) {
164 // Something went wrong!
165 debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
169 $GLOBALS['output'] = $newContent;
175 // Extension 'rewrite' installed?
176 if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
177 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
181 if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
182 // Compress it for HTTP gzip
183 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
186 sendHeader('Content-Encoding: gzip');
187 } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
188 // Compress it for HTTP deflate
189 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
192 sendHeader('Content-Encoding: deflate');
196 sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
202 // Output the raw HTML code
203 function outputRawCode ($htmlCode) {
204 // Output stripped HTML code to avoid broken JavaScript code, etc.
205 print(str_replace('{BACK}', "\\", $htmlCode));
207 // Flush the output if only getPhpCaching() is not 'on'
208 if (getPhpCaching() != 'on') {
214 // Init fatal message array
215 function initFatalMessages () {
216 $GLOBALS['fatal_messages'] = array();
219 // Getter for whole fatal error messages
220 function getFatalArray () {
221 return $GLOBALS['fatal_messages'];
224 // Add a fatal error message to the queue array
225 function addFatalMessage ($F, $L, $message, $extra = '') {
226 if (is_array($extra)) {
227 // Multiple extras for a message with masks
228 $message = call_user_func_array('sprintf', $extra);
229 } elseif (!empty($extra)) {
230 // $message is text with a mask plus extras to insert into the text
231 $message = sprintf($message, $extra);
234 // Add message to $GLOBALS['fatal_messages']
235 $GLOBALS['fatal_messages'][] = $message;
237 // Log fatal messages away
238 logDebugMessage($F, $L, 'Fatal error message: ' . $message);
241 // Getter for total fatal message count
242 function getTotalFatalErrors () {
246 // Do we have at least the first entry?
247 if (!empty($GLOBALS['fatal_messages'][0])) {
249 $count = count($GLOBALS['fatal_messages']);
256 // Load a template file and return it's content (only it's name; do not use ' or ")
257 function loadTemplate ($template, $return = false, $content = array()) {
258 // @TODO Remove this sanity-check if all is fine
259 if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
261 // @TODO Try to rewrite all $DATA to $content
265 if (isTemplateCached($template)) {
266 // Evaluate the cache
267 eval(readTemplateCache($template));
268 } elseif (!isset($GLOBALS['template_eval'][$template])) {
269 // Add more variables which you want to use in your template files
270 $username = getUsername();
272 // Make all template names lowercase
273 $template = strtolower($template);
277 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
280 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
281 $extraPath = detectExtraTemplatePath($template);;
283 ////////////////////////
284 // Generate file name //
285 ////////////////////////
286 $FQFN = $basePath . $extraPath . $template . '.tpl';
288 // Does the special template exists?
289 if (!isFileReadable($FQFN)) {
290 // Reset to default template
291 $FQFN = $basePath . $template . '.tpl';
294 // Now does the final template exists?
295 if (isFileReadable($FQFN)) {
296 // Count the template load
297 incrementConfigEntry('num_templates');
299 // The local file does exists so we load it. :)
300 $GLOBALS['tpl_content'] = readFromFile($FQFN);
302 // Do we have to compile the code?
304 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)) {
305 // Normal HTML output?
306 if (getOutputMode() == '0') {
307 // Add surrounding HTML comments to help finding bugs faster
308 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
310 // Prepare eval() command
311 $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
312 } elseif (substr($template, 0, 3) == 'js_') {
313 // JavaScripts don't like entities and timings
314 $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
316 // Prepare eval() command, other output doesn't like entities, maybe
317 $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
320 // Add surrounding HTML comments to help finding bugs faster
321 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
322 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
325 // Cache the eval() command here
326 $GLOBALS['template_eval'][$template] = $eval;
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';
344 if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
346 eval($GLOBALS['template_eval'][$template]);
349 // Do we have some content to output or return?
351 // Not empty so let's put it out! ;)
352 if ($return === true) {
353 // Return the HTML code
359 } elseif (isDebugModeEnabled()) {
360 // Warning, empty output!
361 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
365 // Detects the extra template path from given template name
366 function detectExtraTemplatePath ($template) {
371 if (!isset($GLOBALS['extra_path'][$template])) {
372 // Check for admin/guest/member/etc. templates
373 if (substr($template, 0, 6) == 'admin_') {
374 // Admin template found
375 $extraPath = 'admin/';
376 } elseif (substr($template, 0, 6) == 'guest_') {
377 // Guest template found
378 $extraPath = 'guest/';
379 } elseif (substr($template, 0, 7) == 'member_') {
380 // Member template found
381 $extraPath = 'member/';
382 } elseif (substr($template, 0, 7) == 'select_') {
383 // Selection template found
384 $extraPath = 'select/';
385 } elseif (substr($template, 0, 8) == 'install_') {
386 // Installation template found
387 $extraPath = 'install/';
388 } elseif (substr($template, 0, 4) == 'ext_') {
389 // Extension template found
391 } elseif (substr($template, 0, 3) == 'la_') {
392 // 'Logical-area' template found
394 } elseif (substr($template, 0, 3) == 'js_') {
395 // JavaScript template found
397 } elseif (substr($template, 0, 5) == 'menu_') {
398 // Menu template found
399 $extraPath = 'menu/';
401 // Test for extension
402 $test = substr($template, 0, strpos($template, '_'));
404 // Probe for valid extension name
405 if (isExtensionNameValid($test)) {
406 // Set extra path to extension's name
407 $extraPath = $test . '/';
412 $GLOBALS['extra_path'][$template] = $extraPath;
416 return $GLOBALS['extra_path'][$template];
419 // Loads an email template and compiles it
420 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
423 // Make sure all template names are lowercase!
424 $template = strtolower($template);
426 // Default 'nickname' if extension is not installed
429 // Neutral email address is default
430 $email = getConfig('WEBMASTER');
432 // Is content an array?
433 if (is_array($content)) {
434 // Add expiration to array
435 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
436 // Will never expire!
437 $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
438 } elseif (isConfigEntrySet('auto_purge')) {
439 // Create nice date string
440 $content['expiration'] = createFancyTime(getConfig('auto_purge'));
443 $content['expiration'] = getMessage('MAIL_NO_CONFIG_AUTO_PURGE');
448 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content).'<br />');
449 if (($userid > 0) && (is_array($content))) {
450 // If nickname extension is installed, fetch nickname as well
451 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
452 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
454 fetchUserData($userid, 'nickname');
456 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
458 fetchUserData($userid);
461 // Merge data if valid
462 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
463 if (isUserDataValid()) {
464 $content = merge_array($content, getUserDataArray());
466 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
469 // Translate M to male or F to female if present
470 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
472 // Overwrite email from data if present
473 if (isset($content['email'])) $email = $content['email'];
475 // Store email for some functions in global $DATA array
476 // @TODO Do only use $content, not $DATA or raw variables
477 $DATA['email'] = $email;
480 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
483 $extraPath = detectExtraTemplatePath($template);
485 // Generate full FQFN
486 $FQFN = $basePath . $extraPath . $template . '.tpl';
488 // Does the special template exists?
489 if (!isFileReadable($FQFN)) {
490 // Reset to default template
491 $FQFN = $basePath . $template . '.tpl';
494 // Now does the final template exists?
496 if (isFileReadable($FQFN)) {
497 // The local file does exists so we load it. :)
498 $GLOBALS['tpl_content'] = readFromFile($FQFN);
501 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
502 eval($GLOBALS['tpl_content']);
503 } elseif (!empty($template)) {
504 // Template file not found!
505 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
506 {--TEMPLATE_CONTENT--}
507 <pre>' . print_r($content, true) . '</pre>
509 <pre>' . print_r($DATA, true) . '</pre>
512 // Debug mode not active? Then remove the HTML tags
513 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
515 // No template name supplied!
516 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
519 // Is there some content?
520 if (empty($newContent)) {
522 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
524 // Add last error if the required function exists
525 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
528 // Remove content and data
536 // Send mail out to an email address
537 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
538 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail},SUBJECT={$subject}<br />");
540 // Compile subject line (for POINTS constant etc.)
541 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
544 if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
545 // Value detected, is the message extension installed?
546 // @TODO Extension 'msg' does not exist
547 if (isExtensionActive('msg')) {
548 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
551 // Does the user exist?
552 if (fetchUserData($toEmail)) {
554 $toEmail = getUserData('email');
557 $toEmail = getConfig('WEBMASTER');
560 } elseif ($toEmail == '0') {
562 $toEmail = getConfig('WEBMASTER');
564 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
566 // Check for PHPMailer or debug-mode
567 if (!checkPhpMailerUsage()) {
568 // Not in PHPMailer-Mode
569 if (empty($mailHeader)) {
570 // Load email header template
571 $mailHeader = loadEmailTemplate('header');
574 $mailHeader .= loadEmailTemplate('header');
576 } elseif (isDebugModeEnabled()) {
577 if (empty($mailHeader)) {
578 // Load email header template
579 $mailHeader = loadEmailTemplate('header');
582 $mailHeader .= loadEmailTemplate('header');
587 eval('$toEmail = "' . compileRawCode(escapeQuotes($toEmail)) . '";');
590 eval('$message = "' . str_replace('$', '$', compileRawCode(escapeQuotes($message))) . '";');
592 // Fix HTML parameter (default is no!)
593 if (empty($isHtml)) $isHtml = 'N';
594 if (isDebugModeEnabled()) {
595 // In debug mode we want to display the mail instead of sending it away so we can debug this part
597 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
598 To : ' . htmlentities(utf8_decode($toEmail)) . '
599 Subject : ' . htmlentities(utf8_decode($subject)) . '
600 Message : ' . htmlentities(utf8_decode($message)) . '
602 } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
603 // Send mail as HTML away
604 return sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
605 } elseif (!empty($toEmail)) {
607 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
608 } elseif ($isHtml != 'Y') {
610 return sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
614 // Check to use wether legacy mail() command or PHPMailer class
615 // @TODO Rewrite this to an extension 'smtp'
617 function checkPhpMailerUsage() {
618 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
621 // Send out a raw email with PHPMailer class or legacy mail() command
622 function sendRawEmail ($toEmail, $subject, $message, $from) {
623 // Just compile all again, to put out all configs, etc.
624 eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
625 eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
626 eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
627 eval('$from = decodeEntities("' . compileRawCode(escapeQuotes($from)) . '");');
629 // Shall we use PHPMailer class or legacy mode?
630 if (checkPhpMailerUsage()) {
631 // Use PHPMailer class with SMTP enabled
632 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
633 loadIncludeOnce('inc/phpmailer/class.smtp.php');
636 $mail = new PHPMailer();
638 // Set charset to UTF-8
639 $mail->CharSet = 'UTF-8';
641 // Path for PHPMailer
642 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
645 $mail->SMTPAuth = true;
646 $mail->Host = getConfig('SMTP_HOSTNAME');
648 $mail->Username = getConfig('SMTP_USER');
649 $mail->Password = getConfig('SMTP_PASSWORD');
651 $mail->From = getConfig('WEBMASTER');
655 $mail->FromName = getConfig('MAIN_TITLE');
656 $mail->Subject = $subject;
657 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
658 $mail->Body = $message;
659 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
660 $mail->WordWrap = 70;
663 $mail->Body = decodeEntities($message);
665 $mail->AddAddress($toEmail, '');
666 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
667 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
668 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
671 // Has an error occured?
672 if (!empty($mail->ErrorInfo)) {
674 logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
683 // Use legacy mail() command
684 return mail($toEmail, $subject, decodeEntities($message), $from);
688 // Generate a password in a specified length or use default password length
689 function generatePassword ($length = '0') {
690 // Auto-fix invalid length of zero
691 if ($length == '0') $length = getConfig('pass_len');
693 // Initialize array with all allowed chars
694 $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,-,+,_,/,.');
696 // Start creating password
698 for ($i = '0'; $i < $length; $i++) {
699 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
702 // When the size is below 40 we can also add additional security by scrambling
703 // it. Otherwise we may corrupt hashes
704 if (strlen($PASS) <= 40) {
705 // Also scramble the password
706 $PASS = scrambleString($PASS);
709 // Return the password
713 // Generates a human-readable timestamp from the Uni* stamp
714 function generateDateTime ($time, $mode = '0') {
715 // Filter out numbers
716 $time = bigintval($time);
718 // If the stamp is zero it mostly didn't "happen"
721 return getMessage('NEVER_HAPPENED');
724 switch (getLanguage()) {
725 case 'de': // German date / time format
727 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
728 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
729 case '2': $ret = date('d.m.Y|H:i', $time); break;
730 case '3': $ret = date('d.m.Y', $time); break;
732 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
737 default: // Default is the US date / time format!
739 case '0': $ret = date('r', $time); break;
740 case '1': $ret = date('Y-m-d - g:i A', $time); break;
741 case '2': $ret = date('y-m-d|H:i', $time); break;
742 case '3': $ret = date('y-m-d', $time); break;
744 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
753 // Translates Y/N to yes/no
754 function translateYesNo ($yn) {
756 $translated = '??? (' . $yn . ')';
758 case 'Y': $translated = getMessage('YES'); break;
759 case 'N': $translated = getMessage('NO'); break;
762 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
770 // Translates the "pool type" into human-readable
771 function translatePoolType ($type) {
772 // Default?type is unknown
773 $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
776 $constName = sprintf("POOL_TYPE_%s", $type);
779 if (isMessageIdValid($constName)) {
781 $translated = getMessage($constName);
784 // Return "translation"
788 // Translates the american decimal dot into a german comma
789 function translateComma ($dotted, $cut = true, $max = '0') {
790 // First, cast all to double, due to PHP changes
791 $dotted = (double) $dotted;
793 // Default is 3 you can change this in admin area "Misc -> Misc Options"
794 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
796 // Use from config is default
797 $maxComma = getConfig('max_comma');
799 // Use from parameter?
800 if ($max > 0) $maxComma = $max;
803 if (($cut === true) && ($max == '0')) {
804 // Test for commata if in cut-mode
805 $com = explode('.', $dotted);
806 if (count($com) < 2) {
807 // Don't display commatas even if there are none... ;-)
813 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
816 switch (getLanguage()) {
817 case 'de': // German language
818 $dotted = number_format($dotted, $maxComma, ',', '.');
821 default: // All others
822 $dotted = number_format($dotted, $maxComma, '.', ',');
826 // Return translated value
830 // Translate Uni*-like gender to human-readable
831 function translateGender ($gender) {
833 $ret = '!' . $gender . '!';
835 // Male/female or company?
837 case 'M': $ret = getMessage('GENDER_M'); break;
838 case 'F': $ret = getMessage('GENDER_F'); break;
839 case 'C': $ret = getMessage('GENDER_C'); break;
841 // Please report bugs on unknown genders
842 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
846 // Return translated gender
850 // "Translates" the user status
851 function translateUserStatus ($status) {
852 // Generate message depending on status
857 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
862 $ret = getMessage('ACCOUNT_DELETED');
866 // Please report all unknown status
867 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
875 // "Translates" 'visible' and 'locked' to a CSS class
876 function translateMenuVisibleLocked ($content, $prefix = '') {
877 // Translate 'visible' and keep an eye on the prefix
878 switch ($content[$prefix . 'visible']) {
880 case 'Y': $content[$prefix . 'visible_css'] = $prefix . 'menu_visible' ; break;
881 case 'N': $content[$prefix . 'visible_css'] = $prefix . 'menu_invisible'; break;
883 // Please report this
884 debug_report_bug('Unsupported visible value detected. content=<pre>'.print_r($content, true).'</pre>');
888 // Translate 'locked' and keep an eye on the prefix
889 switch ($content[$prefix . 'locked']) {
891 case 'Y': $content[$prefix . 'locked_css'] = $prefix . 'menu_locked' ; break;
892 case 'N': $content[$prefix . 'locked_css'] = $prefix . 'menu_unlocked'; break;
894 // Please report this
895 debug_report_bug('Unsupported locked value detected. content=<pre>'.print_r($content, true).'</pre>');
899 // Return the resulting array
903 // Generates an URL for the dereferer
904 function generateDerefererUrl ($URL) {
905 // Don't de-refer our own links!
906 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
907 // De-refer this link
908 $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
915 // Generates an URL for the frametester
916 function generateFrametesterUrl ($URL) {
917 // Prepare frametester URL
918 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
919 encodeString(compileUriCode($URL))
922 // Return the new URL
923 return $frametesterUrl;
926 // Count entries from e.g. a selection box
927 function countSelection ($array) {
929 if (!is_array($array)) {
931 debug_report_bug(__FUNCTION__.': No array provided.');
938 foreach ($array as $key => $selected) {
940 if (!empty($selected)) $ret++;
943 // Return counted selections
947 // Generate XHTML code for the CAPTCHA
948 function generateCaptchaCode ($code, $type, $DATA, $userid) {
949 return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '%}" />';
952 // Generates a timestamp (some wrapper for mktime())
953 function makeTime ($hours, $minutes, $seconds, $stamp) {
954 // Extract day, month and year from given timestamp
955 $days = date('d', $stamp);
956 $months = date('m', $stamp);
957 $years = date('Y', $stamp);
959 // Create timestamp for wished time which depends on extracted date
970 // Redirects to an URL and if neccessarry extends it with own base URL
971 function redirectToUrl ($URL, $allowSpider = true) {
973 eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
975 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
976 $rel = ' rel="external"';
978 // Do we have internal or external URL?
979 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
980 // Own (=internal) URL
984 // Three different ways to debug...
985 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
986 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
987 //* DEBUG: */ die($URL);
989 // Simple probe for bots/spiders from search engines
990 if ((isSpider()) && ($allowSpider === true)) {
991 // Secure the URL against bad things such als HTML insertions and so on...
992 $URL = secureString($URL);
994 // Set content-type here to fix a missing array element
995 setContentType('text/html');
997 // Output new location link as anchor
998 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
999 } elseif (!headers_sent()) {
1000 // Clear own output buffer
1001 $GLOBALS['output'] = '';
1004 setHttpStatus('302 Found');
1006 // Load URL when headers are not sent
1007 sendHeader('Location: '.str_replace('&', '&', $URL));
1009 // Output error message
1010 loadInclude('inc/header.php');
1011 loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
1012 loadInclude('inc/footer.php');
1015 // Shut the mailer down here
1019 // Wrapper for redirectToUrl but URL comes from a configuration entry
1020 function redirectToConfiguredUrl ($configEntry) {
1022 $URL = getConfig($configEntry);
1025 if (is_null($URL)) {
1027 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Configuration entry %s is not set!", $configEntry));
1031 redirectToUrl($URL);
1034 // Compiles the given HTML/mail code
1035 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1036 // Is the code a string?
1037 if (!is_string($code)) {
1038 // Silently return it
1043 $startCompile = microtime(true);
1046 $code = compileRawCode($code, $simple, $constants, $full);
1049 $compiled = microtime(true);
1052 $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1054 // Return compiled code
1058 // Compiles the code (use compileCode() only for HTML because of the comments)
1059 // @TODO $simple is deprecated
1060 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1061 // Is the code a string?
1062 if (!is_string($code)) {
1063 // Silently return it
1067 // Init replacement-array with smaller set of security characters
1068 $secChars = $GLOBALS['url_chars'];
1070 // Select full set of chars to replace when we e.g. want to compile URLs
1071 if ($full === true) $secChars = $GLOBALS['security_chars'];
1073 // Compile more through a filter
1074 $code = runFilterChain('compile_code', $code);
1076 // Compile constants
1077 if ($constants === true) {
1078 // BEFORE 0.2.1 : Language and data constants
1079 // WITH 0.2.1+ : Only language constants
1080 $code = str_replace('{--', "\" . getMessage('", str_replace('--}', "') . \"", $code));
1082 // BEFORE 0.2.1 : Not used
1083 // WITH 0.2.1+ : Data constants
1084 $code = str_replace('{!', "\" . constant('", str_replace('!}', "') . \"", $code));
1087 // Compile QUOT and other non-HTML codes
1088 foreach ($secChars['to'] as $k => $to) {
1089 // Do the reversed thing as in inc/libs/security_functions.php
1090 $code = str_replace($to, $secChars['from'][$k], $code);
1093 // Find $content[bla][blub] entries
1094 // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1095 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1097 // Are some matches found?
1098 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1099 // Replace all matches
1100 $matchesFound = array();
1101 foreach ($matches[0] as $key => $match) {
1102 // Fuzzy look has failed by default
1103 $fuzzyFound = false;
1105 // Fuzzy look on match if already found
1106 foreach ($matchesFound as $found => $set) {
1108 $test = substr($found, 0, strlen($match));
1110 // Does this entry exist?
1111 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
1112 if ($test == $match) {
1114 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
1121 if ($fuzzyFound === true) continue;
1123 // Take all string elements
1124 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1125 // Replace it in the code
1126 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
1127 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1128 $code = str_replace($match, '".' . $newMatch . '."', $code);
1129 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1130 $matchesFound[$match] = 1;
1131 } elseif (!isset($matchesFound[$match])) {
1132 // Not yet replaced!
1133 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
1134 $code = str_replace($match, '".' . $match . '."', $code);
1135 $matchesFound[$match] = 1;
1144 /************************************************************************
1146 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1147 * $a_sort sortiert: *
1149 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1150 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1151 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1152 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1153 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1155 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1156 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1157 * Sie, dass es doch nicht so schwer ist! :-) *
1159 ************************************************************************/
1160 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1162 while ($primary_key < count($a_sort)) {
1163 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1164 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1166 if ($nums === false) {
1167 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1168 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1169 } elseif ($key != $key2) {
1170 // Sort numbers (E.g.: 9 < 10)
1171 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1172 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1176 // We have found two different values, so let's sort whole array
1177 foreach ($dummy as $sort_key => $sort_val) {
1178 $t = $dummy[$sort_key][$key];
1179 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1180 $dummy[$sort_key][$key2] = $t;
1191 // Write back sorted array
1196 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1199 if ($type == 'yn') {
1200 // This is a yes/no selection only!
1201 if ($id > 0) $prefix .= '[' . $id . ']';
1202 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
1204 // Begin with regular selection box here
1205 if (!empty($prefix)) $prefix .= "_";
1207 if ($id > 0) $type2 .= '[' . $id . ']';
1208 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
1213 for ($idx = 1; $idx < 32; $idx++) {
1214 $OUT .= '<option value="' . $idx . '"';
1215 if ($default == $idx) $OUT .= ' selected="selected"';
1216 $OUT .= '>' . $idx . '</option>';
1220 case 'month': // Month
1221 foreach ($GLOBALS['month_descr'] as $idx => $descr) {
1222 $OUT .= '<option value="' . $idx . '"';
1223 if ($default == $idx) $OUT .= ' selected="selected"';
1224 $OUT .= '>' . $descr . '</option>';
1228 case 'year': // Year
1230 $year = date('Y', time());
1232 // Use configured min age or fixed?
1233 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1235 $startYear = $year - getConfig('min_age');
1238 $startYear = $year - 16;
1241 // Calculate earliest year (100 years old people can still enter Internet???)
1242 $minYear = $year - 100;
1244 // Check if the default value is larger than minimum and bigger than actual year
1245 if (($default > $minYear) && ($default >= $year)) {
1246 for ($idx = $year; $idx < ($year + 11); $idx++) {
1247 $OUT .= '<option value="' . $idx . '"';
1248 if ($default == $idx) $OUT .= ' selected="selected"';
1249 $OUT .= '>' . $idx . '</option>';
1251 } elseif ($default == -1) {
1252 // Current year minus 1
1253 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
1254 $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
1257 // Get current year and subtract the configured minimum age
1258 $OUT .= '<option value="' . ($minYear - 1) . '"><' . $minYear . '</option>';
1259 // Calculate earliest year depending on extension version
1260 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1261 // Use configured minimum age
1262 $year = date('Y', time()) - getConfig('min_age');
1264 // Use fixed 16 years age
1265 $year = date('Y', time()) - 16;
1268 // Construct year selection list
1269 for ($idx = $minYear; $idx <= $year; $idx++) {
1270 $OUT .= '<option value="' . $idx . '"';
1271 if ($default == $idx) $OUT .= ' selected="selected"';
1272 $OUT .= '>' . $idx . '</option>';
1279 for ($idx = 0; $idx < 60; $idx+=5) {
1280 if (strlen($idx) == 1) $idx = '0' . $idx;
1281 $OUT .= '<option value="' . $idx . '"';
1282 if ($default == $idx) $OUT .= ' selected="selected"';
1283 $OUT .= '>' . $idx . '</option>';
1288 for ($idx = 0; $idx < 24; $idx++) {
1289 if (strlen($idx) == 1) $idx = '0' . $idx;
1290 $OUT .= '<option value="' . $idx . '"';
1291 if ($default == $idx) $OUT .= ' selected="selected"';
1292 $OUT .= '>' . $idx . '</option>';
1297 $OUT .= '<option value="Y"';
1298 if ($default == 'Y') $OUT .= ' selected="selected"';
1299 $OUT .= '>{--YES--}</option><option value="N"';
1300 if ($default != 'Y') $OUT .= ' selected="selected"';
1301 $OUT .= '>{--NO--}</option>';
1304 $OUT .= '</select>';
1309 // Deprecated : $length
1312 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1313 // Build server string
1314 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
1317 $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1318 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1319 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1320 $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1321 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1323 // Build string from misc data
1324 $data = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1326 // Add more additional data
1327 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1329 // Add referal id, language, theme and userid
1330 $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1331 $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1332 $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1333 $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1335 // Calculate number for generating the code
1336 $a = $code + getConfig('_ADD') - 1;
1338 if (isConfigEntrySet('master_salt')) {
1339 // Generate hash with master salt from modula of number with the prime number and other data
1340 $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'));
1342 // Create number from hash
1343 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1345 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1346 $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')));
1348 // Create number from hash
1349 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1352 // At least 10 numbers shall be secure enought!
1353 $len = getConfig('code_length');
1354 if ($len == '0') $len = $length;
1355 if ($len == '0') $len = 10;
1357 // Cut off requested counts of number
1358 $return = substr(str_replace('.', '', $rcode), 0, $len);
1360 // Done building code
1364 // Does only allow numbers
1365 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
1366 // Filter all numbers out
1367 $ret = preg_replace('/[^0123456789]/', '', $num);
1370 if ($castValue === true) $ret = (double)$ret;
1372 // Has the whole value changed?
1373 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
1375 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret=' . $ret . ', num='. $num);
1382 // Insert the code in $img_code into jpeg or PNG image
1383 function generateImageOrCode ($img_code, $headerSent = true) {
1384 // Is the code size oversized or shouldn't we display it?
1385 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1386 // Stop execution of function here because of over-sized code length
1387 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1388 } elseif ($headerSent === false) {
1389 // Return an HTML code here
1390 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
1394 $img = sprintf("%s/theme/%s/images/code_bg.%s",
1397 getConfig('img_type')
1401 if (isFileReadable($img)) {
1402 // Switch image type
1403 switch (getConfig('img_type')) {
1405 // Okay, load image and hide all errors
1406 $image = imagecreatefromjpeg($img);
1410 // Okay, load image and hide all errors
1411 $image = imagecreatefrompng($img);
1415 // Exit function here
1416 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1420 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1421 $text_color = imagecolorallocate($image, 0, 0, 0);
1423 // Insert code into image
1424 imagestring($image, 5, 14, 2, $img_code, $text_color);
1426 // Return to browser
1427 sendHeader('Content-Type: image/' . getConfig('img_type'));
1429 // Output image with matching image factory
1430 switch (getConfig('img_type')) {
1431 case 'jpg': imagejpeg($image); break;
1432 case 'png': imagepng($image); break;
1435 // Remove image from memory
1436 imagedestroy($image);
1438 // Create selection box or array of splitted timestamp
1439 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1440 // Do not continue if ONE_DAY is absend
1441 if (!isConfigEntrySet('ONE_DAY')) {
1442 // And return the timestamp itself or empty array
1443 if ($return_array === true) {
1450 // Calculate 2-seconds timestamp
1451 $stamp = round($timestamp);
1452 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1454 // Do we have a leap year?
1456 $TEST = date('Y', time()) / 4;
1457 $M1 = date('m', time());
1458 $M2 = date('m', (time() + $timestamp));
1460 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1461 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('ONE_DAY');
1463 // First of all years...
1464 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1465 //* DEBUG: */ print("Y={$Y}<br />");
1467 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1468 //* DEBUG: */ print("M={$M}<br />");
1470 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1471 //* DEBUG: */ print("W={$W}<br />");
1473 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1474 //* DEBUG: */ print("D={$D}<br />");
1476 $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));
1477 //* DEBUG: */ print("h={$h}<br />");
1479 $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));
1480 //* DEBUG: */ print("m={$m}<br />");
1481 // And at last seconds...
1482 $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));
1483 //* DEBUG: */ print("s={$s}<br />");
1485 // Is seconds zero and time is < 60 seconds?
1486 if (($s == '0') && ($timestamp < 60)) {
1488 $s = round($timestamp);
1492 // Now we convert them in seconds...
1494 if ($return_array) {
1495 // Just put all data in an array for later use
1507 $OUT = '<div align="' . $align . '">';
1508 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1511 if (isInString('Y', $display) || (empty($display))) {
1512 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
1515 if (isInString('M', $display) || (empty($display))) {
1516 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
1519 if (isInString('W', $display) || (empty($display))) {
1520 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
1523 if (isInString('D', $display) || (empty($display))) {
1524 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
1527 if (isInString('h', $display) || (empty($display))) {
1528 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
1531 if (isInString('m', $display) || (empty($display))) {
1532 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
1535 if (isInString('s', $display) || (empty($display))) {
1536 $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
1542 if (isInString('Y', $display) || (empty($display))) {
1543 // Generate year selection
1544 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
1545 for ($idx = 0; $idx <= 10; $idx++) {
1546 $OUT .= '<option class="mini_select" value="' . $idx . '"';
1547 if ($idx == $Y) $OUT .= ' selected="selected"';
1548 $OUT .= '>' . $idx . '</option>';
1550 $OUT .= '</select></td>';
1552 $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1555 if (isInString('M', $display) || (empty($display))) {
1556 // Generate month selection
1557 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
1558 for ($idx = 0; $idx <= 11; $idx++) {
1559 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1560 if ($idx == $M) $OUT .= ' selected="selected"';
1561 $OUT .= '>' . $idx . '</option>';
1563 $OUT .= '</select></td>';
1565 $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1568 if (isInString('W', $display) || (empty($display))) {
1569 // Generate week selection
1570 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
1571 for ($idx = 0; $idx <= 4; $idx++) {
1572 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1573 if ($idx == $W) $OUT .= ' selected="selected"';
1574 $OUT .= '>' . $idx . '</option>';
1576 $OUT .= '</select></td>';
1578 $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1581 if (isInString('D', $display) || (empty($display))) {
1582 // Generate day selection
1583 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
1584 for ($idx = 0; $idx <= 31; $idx++) {
1585 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1586 if ($idx == $D) $OUT .= ' selected="selected"';
1587 $OUT .= '>' . $idx . '</option>';
1589 $OUT .= '</select></td>';
1591 $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1594 if (isInString('h', $display) || (empty($display))) {
1595 // Generate hour selection
1596 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1597 for ($idx = 0; $idx <= 23; $idx++) {
1598 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1599 if ($idx == $h) $OUT .= ' selected="selected"';
1600 $OUT .= '>' . $idx . '</option>';
1602 $OUT .= '</select></td>';
1604 $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1607 if (isInString('m', $display) || (empty($display))) {
1608 // Generate minute selection
1609 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1610 for ($idx = 0; $idx <= 59; $idx++) {
1611 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1612 if ($idx == $m) $OUT .= ' selected="selected"';
1613 $OUT .= '>' . $idx . '</option>';
1615 $OUT .= '</select></td>';
1617 $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1620 if (isInString('s', $display) || (empty($display))) {
1621 // Generate second selection
1622 $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1623 for ($idx = 0; $idx <= 59; $idx++) {
1624 $OUT .= ' <option class="mini_select" value="' . $idx . '"';
1625 if ($idx == $s) $OUT .= ' selected="selected"';
1626 $OUT .= '>' . $idx . '</option>';
1628 $OUT .= '</select></td>';
1630 $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1637 // Return generated HTML code
1642 function createTimestampFromSelections ($prefix, $postData) {
1643 // Initial return value
1646 // Do we have a leap year?
1648 $TEST = date('Y', time()) / 4;
1649 $M1 = date('m', time());
1651 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1652 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) $SWITCH = getConfig('ONE_DAY');
1654 // First add years...
1655 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1658 $ret += $postData[$prefix . '_mo'] * 2628000;
1661 $ret += $postData[$prefix . '_we'] * 604800;
1664 $ret += $postData[$prefix . '_da'] * 86400;
1667 $ret += $postData[$prefix . '_ho'] * 3600;
1670 $ret += $postData[$prefix . '_mi'] * 60;
1672 // And at last seconds...
1673 $ret += $postData[$prefix . '_se'];
1675 // Return calculated value
1679 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1680 function createFancyTime ($stamp) {
1681 // Get data array with years/months/weeks/days/...
1682 $data = createTimeSelections($stamp, '', '', '', true);
1684 foreach($data as $k => $v) {
1686 // Value is greater than 0 "eval" data to return string
1687 eval('$ret .= ", ".$v." {--_' . strtoupper($k) . '--}";');
1692 // Do we have something there?
1693 if (strlen($ret) > 0) {
1694 // Remove leading commata and space
1695 $ret = substr($ret, 2);
1698 $ret = '0 {--_SECONDS--}';
1701 // Return fancy time string
1705 // Generates a navigation row for listing emails
1706 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1708 if ($show_form === false) {
1713 for ($page = 1; $page <= $PAGES; $page++) {
1714 // Is the page currently selected or shall we generate a link to it?
1715 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1716 // Is currently selected, so only highlight it
1717 $NAV .= '<strong>-';
1719 // Open anchor tag and add base URL
1720 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1722 // Add userid when we shall show all mails from a single member
1723 if ((isGetRequestParameterSet('userid')) && (bigintval(getRequestParameter('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestParameter('userid'));
1725 // Close open anchor tag
1729 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1730 // Is currently selected, so only highlight it
1731 $NAV .= '-</strong>';
1737 // Add seperator if we have not yet reached total pages
1738 if ($page < $PAGES) {
1744 // Define constants only once
1745 $content['nav'] = $NAV;
1746 $content['span'] = $colspan;
1747 $content['top'] = $TOP;
1749 // Load navigation template
1750 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1752 if ($return === true) {
1753 // Return generated HTML-Code
1761 // Extract host from script name
1762 function extractHostnameFromUrl (&$script) {
1763 // Use default SERVER_URL by default... ;) So?
1764 $url = getConfig('SERVER_URL');
1766 // Is this URL valid?
1767 if (substr($script, 0, 7) == 'http://') {
1768 // Use the hostname from script URL as new hostname
1769 $url = substr($script, 7);
1770 $extract = explode('/', $url);
1772 // Done extracting the URL :)
1775 // Extract host name
1776 $host = str_replace('http://', '', $url);
1777 if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1779 // Generate relative URL
1780 //* DEBUG: */ print('SCRIPT=' . $script.'<br />');
1781 if (substr(strtolower($script), 0, 7) == 'http://') {
1782 // But only if http:// is in front!
1783 $script = substr($script, (strlen($url) + 7));
1784 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1786 $script = substr($script, (strlen($url) + 8));
1789 //* DEBUG: */ print('SCRIPT=' . $script.'<br />');
1790 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1796 // Send a GET request
1797 function sendGetRequest ($script, $data = array()) {
1798 // Extract host name from script
1799 $host = extractHostnameFromUrl($script);
1802 $body = http_build_query($data, '', '&');
1804 // Do we have a question-mark in the script?
1805 if (strpos($script, '?') === false) {
1806 // No, so first char must be question mark
1807 $body = '?' . $body;
1810 $body = '&' . $body;
1816 // Remove trailed & to make it more conform
1817 if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
1819 // Generate GET request header
1820 $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1821 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1822 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1823 if (isConfigEntrySet('FULL_VERSION')) {
1824 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1826 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1828 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
1829 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1830 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
1831 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1832 $request .= getConfig('HTTP_EOL');
1834 // Send the raw request
1835 $response = sendRawRequest($host, $request);
1837 // Return the result to the caller function
1841 // Send a POST request
1842 function sendPostRequest ($script, $postData) {
1843 // Is postData an array?
1844 if (!is_array($postData)) {
1846 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1847 return array('', '', '');
1850 // Extract host name from script
1851 $host = extractHostnameFromUrl($script);
1853 // Construct request body
1854 $body = http_build_query($postData, '', '&');
1856 // Generate POST request header
1857 $request = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
1858 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1859 $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1860 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1861 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1862 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1863 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1864 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1865 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
1866 $request .= 'Connection: close' . getConfig('HTTP_EOL');
1867 $request .= getConfig('HTTP_EOL');
1872 // Send the raw request
1873 $response = sendRawRequest($host, $request);
1875 // Return the result to the caller function
1879 // Sends a raw request to another host
1880 function sendRawRequest ($host, $request) {
1881 // Init errno and errdesc with 'all fine' values
1882 $errno = '0'; $errdesc = '';
1885 $response = array('', '', '');
1887 // Default is not to use proxy
1890 // Are proxy settins set?
1891 if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1897 loadIncludeOnce('inc/classes/resolver.class.php');
1899 // Get resolver instance
1900 $resolver = new HostnameResolver();
1903 //* DEBUG: */ die('SCRIPT=' . $script.'<br />');
1904 if ($useProxy === true) {
1905 // Resolve hostname into IP address
1906 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
1908 // Connect to host through proxy connection
1909 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1911 // Resolve hostname into IP address
1912 $ip = $resolver->resolveHostname($host);
1914 // Connect to host directly
1915 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
1919 if (!is_resource($fp)) {
1921 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
1923 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
1924 // Cannot set non-blocking mode or timeout
1925 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
1930 if ($useProxy === true) {
1931 // Setup proxy tunnel
1932 $response = setupProxyTunnel($host, $fp);
1934 // If the response is invalid, abort
1935 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
1936 // Invalid response!
1937 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
1943 fwrite($fp, $request);
1946 $start = microtime(true);
1949 while (!feof($fp)) {
1950 // Get info from stream
1951 $info = stream_get_meta_data($fp);
1953 // Is it timed out? 15 seconds is a really patient...
1954 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1956 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1962 // Get line from stream
1963 $line = fgets($fp, 128);
1965 // Ignore empty lines because of non-blocking mode
1967 // uslepp a little to avoid 100% CPU load
1974 // Add it to response
1975 $response[] = trim($line);
1981 // Time request if debug-mode is enabled
1982 if (isDebugModeEnabled()) {
1983 // Add debug message...
1984 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1987 // Skip first empty lines
1989 foreach ($resp as $idx => $line) {
1991 $line = trim($line);
1993 // Is this line empty?
1996 array_shift($response);
1998 // Abort on first non-empty line
2003 //* DEBUG: */ print('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
2004 //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
2006 // Proxy agent found or something went wrong?
2007 if (!isset($response[0])) {
2008 // No response, maybe timeout
2009 $response = array('', '', '');
2010 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
2011 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
2012 // Proxy header detected, so remove two lines
2013 array_shift($response);
2014 array_shift($response);
2017 // Was the request successfull?
2018 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
2019 // Not found / access forbidden
2020 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
2021 $response = array('', '', '');
2028 // Sets up a proxy tunnel for given hostname and through resource
2029 function setupProxyTunnel ($host, $resource) {
2031 $response = array('', '', '');
2033 // Generate CONNECT request header
2034 $proxyTunnel = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
2035 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
2037 // Use login data to proxy? (username at least!)
2038 if (getConfig('proxy_username') != '') {
2040 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
2041 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
2044 // Add last new-line
2045 $proxyTunnel .= getConfig('HTTP_EOL');
2046 //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
2049 fwrite($fp, $proxyTunnel);
2053 // No response received
2057 // Read the first line
2058 $resp = trim(fgets($fp, 10240));
2059 $respArray = explode(' ', $resp);
2060 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
2061 // Invalid response!
2069 // Taken from www.php.net isInStringIgnoreCase() user comments
2070 function isEmailValid ($email) {
2071 // Check first part of email address
2072 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
2075 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
2078 $regex = '@^' . $first . '\@' . $domain . '$@iU';
2080 // Return check result
2081 return preg_match($regex, $email);
2084 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2085 function isUrlValid ($URL, $compile=true) {
2086 // Trim URL a little
2087 $URL = trim(urldecode($URL));
2088 //* DEBUG: */ outputHtml($URL.'<br />');
2090 // Compile some chars out...
2091 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
2092 //* DEBUG: */ outputHtml($URL.'<br />');
2094 // Check for the extension filter
2095 if (isExtensionActive('filter')) {
2096 // Use the extension's filter set
2097 return FILTER_VALIDATE_URL($URL, false);
2100 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2101 // https:// in front of the URLs
2102 return isUrlValidSimple($URL);
2105 // Generate a list of administrative links to a given userid
2106 function generateMemberAdminActionLinks ($userid, $status = '') {
2107 // Make sure userid is a number
2108 if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
2110 // Define all main targets
2111 $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2113 // Begin of navigation links
2116 foreach ($targetArray as $tar) {
2117 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&what=' . $tar . '&userid=' . $userid . '%}" title="{--ADMIN_LINK_';
2118 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
2119 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2120 // Locked accounts shall be unlocked
2121 $OUT .= 'UNLOCK_USER';
2123 // All other status is fine
2124 $OUT .= strtoupper($tar);
2126 $OUT .= '_TITLE--}">{--ADMIN_';
2127 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2128 // Locked accounts shall be unlocked
2129 $OUT .= 'UNLOCK_USER';
2131 // All other status is fine
2132 $OUT .= strtoupper($tar);
2134 $OUT .= '--}</a></span>|';
2137 // Finish navigation link
2138 $OUT = substr($OUT, 0, -7) . ']';
2144 // Generate an email link
2145 function generateEmailLink ($email, $table = 'admins') {
2146 // Default email link (INSECURE! Spammer can read this by harvester programs)
2147 $EMAIL = 'mailto:' . $email;
2149 // Check for several extensions
2150 if ((isExtensionActive('admins')) && ($table == 'admins')) {
2151 // Create email link for contacting admin in guest area
2152 $EMAIL = generateAdminEmailLink($email);
2153 } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
2154 // Create email link for contacting a member within admin area (or later in other areas, too?)
2155 $EMAIL = generateUserEmailLink($email, 'admin');
2156 } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2157 // Create email link to contact sponsor within admin area (or like the link above?)
2158 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2161 // Shall I close the link when there is no admin?
2162 if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2164 // Return email link
2168 // Generate a hash for extra-security for all passwords
2169 function generateHash ($plainText, $salt = '', $hash = true) {
2171 //* DEBUG: */ outputHtml('plainText=' . $plainText . ',salt=' . $salt . ',hash='.intval($hash).'<br />');
2173 // Is the required extension 'sql_patches' there and a salt is not given?
2174 // 0123 4 43 3 4 432 2 3 32 2 3 3210
2175 if ((((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')))) {
2176 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2177 if ($hash === true) {
2178 // Is plain password
2179 return md5($plainText);
2181 // Is already a hash
2186 // Do we miss an arry element here?
2187 if (!isConfigEntrySet('file_hash')) {
2189 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
2192 // When the salt is empty build a new one, else use the first x configured characters as the salt
2194 // Build server string for more entropy
2195 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2198 $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');
2201 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2203 // Calculate number for generating the code
2204 $a = time() + getConfig('_ADD') - 1;
2206 // Generate SHA1 sum from modula of number and the prime number
2207 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2208 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2209 $sha1 = scrambleString($sha1);
2210 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2211 //* DEBUG: */ $sha1b = descrambleString($sha1);
2212 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2214 // Generate the password salt string
2215 $salt = substr($sha1, 0, getConfig('salt_length'));
2216 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2219 //* DEBUG: */ outputHtml('salt=' . $salt . '<br />');
2220 $salt = substr($salt, 0, getConfig('salt_length'));
2221 //* DEBUG: */ outputHtml('salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />');
2223 // Sanity check on salt
2224 if (strlen($salt) != getConfig('salt_length')) {
2226 debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2230 // Generate final hash (for debug output)
2231 $finalHash = $salt . sha1($salt . $plainText);
2234 //* DEBUG: */ outputHtml('finalHash=' . $finalHash);
2240 // Scramble a string
2241 function scrambleString($str) {
2245 // Final check, in case of failture it will return unscrambled string
2246 if (strlen($str) > 40) {
2247 // The string is to long
2249 } elseif (strlen($str) == 40) {
2251 $scrambleNums = explode(':', getConfig('pass_scramble'));
2253 // Generate new numbers
2254 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2257 // Compare both lengths and abort if different
2258 if (strlen($str) != count($scrambleNums)) return $str;
2260 // Scramble string here
2261 //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2262 for ($idx = 0; $idx < strlen($str); $idx++) {
2263 // Get char on scrambled position
2264 $char = substr($str, $scrambleNums[$idx], 1);
2266 // Add it to final output string
2267 $scrambled .= $char;
2270 // Return scrambled string
2271 //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2275 // De-scramble a string scrambled by scrambleString()
2276 function descrambleString($str) {
2277 // Scramble only 40 chars long strings
2278 if (strlen($str) != 40) return $str;
2280 // Load numbers from config
2281 $scrambleNums = explode(':', getConfig('pass_scramble'));
2284 if (count($scrambleNums) != 40) return $str;
2286 // Begin descrambling
2287 $orig = str_repeat(' ', 40);
2288 //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2289 for ($idx = 0; $idx < 40; $idx++) {
2290 $char = substr($str, $idx, 1);
2291 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2294 // Return scrambled string
2295 //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2299 // Generated a "string" for scrambling
2300 function genScrambleString ($len) {
2301 // Prepare array for the numbers
2302 $scrambleNumbers = array();
2304 // First we need to setup randomized numbers from 0 to 31
2305 for ($idx = 0; $idx < $len; $idx++) {
2307 $rand = mt_rand(0, ($len -1));
2309 // Check for it by creating more numbers
2310 while (array_key_exists($rand, $scrambleNumbers)) {
2311 $rand = mt_rand(0, ($len -1));
2315 $scrambleNumbers[$rand] = $rand;
2318 // So let's create the string for storing it in database
2319 $scrambleString = implode(':', $scrambleNumbers);
2320 return $scrambleString;
2323 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2324 function encodeHashForCookie ($passHash) {
2325 // Return vanilla password hash
2328 // Is a secret key and master salt already initialized?
2329 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
2330 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2331 // Only calculate when the secret key is generated
2332 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getConfig('secret_key')));
2333 if ((strlen($passHash) != 49) || (strlen(getConfig('secret_key')) != 40)) {
2334 // Both keys must have same length so return unencrypted
2335 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getConfig('secret_key')) . '!=40');
2339 $newHash = ''; $start = 9;
2340 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
2341 for ($idx = 0; $idx < 20; $idx++) {
2342 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getConfig('secret_key'))), 2));
2343 $part2 = hexdec(substr(getConfig('secret_key'), $start, 2));
2344 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
2345 $mod = dechex($idx);
2346 if ($part1 > $part2) {
2347 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2348 } elseif ($part2 > $part1) {
2349 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2351 $mod = substr($mod, 0, 2);
2352 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
2353 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
2354 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
2359 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
2360 $ret = generateHash($newHash, getConfig('master_salt'));
2364 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
2368 // Fix "deleted" cookies
2369 function fixDeletedCookies ($cookies) {
2370 // Is this an array with entries?
2371 if ((is_array($cookies)) && (count($cookies) > 0)) {
2372 // Then check all cookies if they are marked as deleted!
2373 foreach ($cookies as $cookieName) {
2374 // Is the cookie set to "deleted"?
2375 if (getSession($cookieName) == 'deleted') {
2376 setSession($cookieName, '');
2382 // Output error messages in a fasioned way and die...
2383 function app_die ($F, $L, $message) {
2384 // Check if Script is already dieing and not let it kill itself another 1000 times
2385 if (!isset($GLOBALS['app_died'])) {
2386 // Make sure, that the script realy realy diese here and now
2387 $GLOBALS['app_died'] = true;
2389 // Set content type as text/html
2390 setContentType('text/html');
2393 loadIncludeOnce('inc/header.php');
2395 // Rewrite message for output
2396 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
2398 // Load the message template
2399 loadTemplate('app_die_message', false, $message);
2402 loadIncludeOnce('inc/footer.php');
2404 // Script tried to kill itself twice
2405 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2409 // Display parsing time and number of SQL queries in footer
2410 function displayParsingTime () {
2411 // Is the timer started?
2412 if (!isset($GLOBALS['startTime'])) {
2418 $endTime = microtime(true);
2420 // "Explode" both times
2421 $start = explode(' ', $GLOBALS['startTime']);
2422 $end = explode(' ', $endTime);
2423 $runTime = $end[0] - $start[0];
2424 if ($runTime < 0) $runTime = '0';
2427 // @TODO This can be easily moved out after the merge from EL branch to this is complete
2429 'run_time' => translateComma($runTime),
2430 'sql_time' => translateComma(getConfig('sql_time') * 1000),
2433 // Load the template
2434 $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
2437 // Check wether a boolean constant is set
2438 // Taken from user comments in PHP documentation for function constant()
2439 function isBooleanConstantAndTrue ($constName) { // : Boolean
2440 // Failed by default
2444 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2446 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-CACHE!<br />");
2447 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2450 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-RESOLVE!<br />");
2451 if (defined($constName)) {
2453 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-FOUND!<br />");
2454 $res = (constant($constName) === true);
2458 $GLOBALS['cache_array']['const'][$constName] = $res;
2460 //* DEBUG: */ var_dump($res);
2466 // Checks if a given apache module is loaded
2467 function isApacheModuleLoaded ($apacheModule) {
2468 // Check it and return result
2469 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2472 // Get current theme name
2473 function getCurrentTheme () {
2474 // The default theme is 'default'... ;-)
2477 // Do we have ext-theme installed and active?
2478 if (isExtensionActive('theme')) {
2479 // Call inner method
2480 $ret = getActualTheme();
2483 // Return theme value
2487 // Generates an error code from given account status
2488 function generateErrorCodeFromUserStatus ($status='') {
2489 // If no status is provided, use the default, cached
2490 if ((empty($status)) && (isMember())) {
2492 $status = getUserData('status');
2495 // Default error code if unknown account status
2496 $errorCode = getCode('UNKNOWN_STATUS');
2498 // Generate constant name
2499 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2501 // Is the constant there?
2502 if (isCodeSet($codeName)) {
2504 $errorCode = getCode($codeName);
2507 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2510 // Return error code
2514 // Back-ported from the new ship-simu engine. :-)
2515 function debug_get_printable_backtrace () {
2517 $backtrace = "<ol>\n";
2519 // Get and prepare backtrace for output
2520 $backtraceArray = debug_backtrace();
2521 foreach ($backtraceArray as $key => $trace) {
2522 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2523 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2524 if (!isset($trace['args'])) $trace['args'] = array();
2525 $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";
2529 $backtrace .= "</ol>\n";
2531 // Return the backtrace
2535 // A mail-able backtrace
2536 function debug_get_mailable_backtrace () {
2540 // Get and prepare backtrace for output
2541 $backtraceArray = debug_backtrace();
2542 foreach ($backtraceArray as $key => $trace) {
2543 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2544 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2545 if (!isset($trace['args'])) $trace['args'] = array();
2546 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2549 // Return the backtrace
2553 // Output a debug backtrace to the user
2554 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
2555 // Is this already called?
2556 if (isset($GLOBALS[__FUNCTION__])) {
2558 print 'Message:'.$message.'<br />Backtrace:<pre>';
2559 debug_print_backtrace();
2563 // Set this function as called
2564 $GLOBALS[__FUNCTION__] = true;
2569 // Is the optional message set?
2570 if (!empty($message)) {
2572 $debug = sprintf("Note: %s<br />\n",
2576 // @TODO Add a little more infos here
2577 logDebugMessage($F, $L, strip_tags($message));
2581 $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>";
2582 $debug .= debug_get_printable_backtrace();
2583 $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2584 $debug .= "Thank you for finding bugs.";
2586 // Send an email? (e.g. not wanted for evaluation errors)
2587 if (($sendEmail === true) && (!isInstallationPhase())) {
2590 'message' => trim($message),
2591 'backtrace' => trim(debug_get_mailable_backtrace())
2594 // Send email to webmaster
2595 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2599 app_die($F, $L, $debug);
2602 // Generates a ***weak*** seed
2603 function generateSeed () {
2604 return microtime(true) * 100000;
2607 // Converts a message code to a human-readable message
2608 function getMessageFromErrorCode ($code) {
2612 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2613 case getCode('LOGOUT_FAILED') : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2614 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2615 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2616 case getCode('USER_404') : $message = getMessage('USER_404'); break;
2617 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2618 case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2619 case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
2620 case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
2621 case getCode('ACCOUNT_LOCKED') : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2622 case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2623 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2624 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2625 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2626 case getCode('MODULE_MEM_ONLY') : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestParameter('mod')); break;
2627 case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2628 case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2629 case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2630 case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestParameter('blist'), 0); break;
2631 case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2632 case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2633 case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2634 case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2635 case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2636 case getCode('MORE_RECEIVERS3') : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
2637 case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2638 case getCode('NO_MAIL_TYPE') : $message = getMessage('MEMBER_NO_MAIL_TYPE_SELECTED'); break;
2639 case getCode('UNKNOWN_ERROR') : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
2640 case getCode('UNKNOWN_STATUS') : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
2642 case getCode('ERROR_MAILID'):
2643 if (isExtensionActive('mailid', true)) {
2644 $message = getMessage('ERROR_CONFIRMING_MAIL');
2646 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', 'mailid');
2650 case getCode('EXTENSION_PROBLEM'):
2651 if (isGetRequestParameterSet('ext')) {
2652 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
2654 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2658 case getCode('URL_TLOCK'):
2659 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2660 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2661 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
2663 // Load timestamp from last order
2664 list($timestamp) = SQL_FETCHROW($result);
2667 SQL_FREERESULT($result);
2669 // Translate it for templates
2670 $timestamp = generateDateTime($timestamp, 1);
2672 // Calculate hours...
2673 $STD = round(getConfig('url_tlock') / 60 / 60);
2676 $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2679 $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2681 // Finally contruct the message
2682 // @TODO Rewrite this old lost code to a template
2683 $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2684 {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2685 {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2689 // Missing/invalid code
2690 $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2693 logDebugMessage(__FUNCTION__, __LINE__, $message);
2697 // Return the message
2701 // Compile characters which are allowed in URLs
2702 function compileUriCode ($code, $simple = true) {
2703 // Compile constants
2704 if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2706 // Compile QUOT and other non-HTML codes
2707 $code = str_replace('{DOT}', '.',
2708 str_replace('{SLASH}', '/',
2709 str_replace('{QUOT}', "'",
2710 str_replace('{DOLLAR}', '$',
2711 str_replace('{OPEN_ANCHOR}', '(',
2712 str_replace('{CLOSE_ANCHOR}', ')',
2713 str_replace('{OPEN_SQR}', '[',
2714 str_replace('{CLOSE_SQR}', ']',
2715 str_replace('{PER}', '%',
2719 // Return compiled code
2723 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2724 function isUrlValidSimple ($url) {
2726 $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2728 // Allows http and https
2729 $http = "(http|https)+(:\/\/)";
2731 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2732 // Test double-domains (e.g. .de.vu)
2733 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2735 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2737 $dir = "((/)+([-_\.[:alnum:]])+)*";
2739 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2740 // ... and the string after and including question character
2741 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2742 // Pattern for URLs like http://url/dir/doc.html?var=value
2743 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2744 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2745 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2746 // Pattern for URLs like http://url/dir/?var=value
2747 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2748 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2749 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2750 // Pattern for URLs like http://url/dir/page.ext
2751 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2752 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2753 $pattern['ipdp'] = $http . $ip . $dir . $page;
2754 // Pattern for URLs like http://url/dir
2755 $pattern['d1d'] = $http . $domain1 . $dir;
2756 $pattern['d2d'] = $http . $domain2 . $dir;
2757 $pattern['ipd'] = $http . $ip . $dir;
2758 // Pattern for URLs like http://url/?var=value
2759 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2760 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2761 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2762 // Pattern for URLs like http://url?var=value
2763 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2764 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2765 $pattern['ipg12'] = $http . $ip . $getstring1;
2767 // Test all patterns
2769 foreach ($pattern as $key => $pat) {
2771 if (isDebugRegularExpressionEnabled()) {
2772 // @TODO Are these convertions still required?
2773 $pat = str_replace('.', "\.", $pat);
2774 $pat = str_replace('@', "\@", $pat);
2775 //* DEBUG: */ outputHtml($key."= " . $pat . '<br />');
2778 // Check if expression matches
2779 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
2782 if ($reg === true) break;
2785 // Return true/false
2789 // Wtites data to a config.php-style file
2790 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2791 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2792 // Initialize some variables
2798 // Is the file there and read-/write-able?
2799 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2800 $search = 'CFG: ' . $comment;
2801 $tmp = $FQFN . '.tmp';
2803 // Open the source file
2804 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2806 // Is the resource valid?
2807 if (is_resource($fp)) {
2808 // Open temporary file
2809 $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2811 // Is the resource again valid?
2812 if (is_resource($fp_tmp)) {
2813 // Mark temporary file as readable
2814 $GLOBALS['file_readable'][$tmp] = true;
2817 while (!feof($fp)) {
2818 // Read from source file
2819 $line = fgets ($fp, 1024);
2821 if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2824 if ($next === $seek) {
2826 $line = $prefix . $DATA . $suffix . "\n";
2832 // Write to temp file
2833 fwrite($fp_tmp, $line);
2839 // Finished writing tmp file
2843 // Close source file
2846 if (($done === true) && ($found === true)) {
2847 // Copy back tmp file and delete tmp :-)
2848 copyFileVerified($tmp, $FQFN, 0644);
2849 return removeFile($tmp);
2850 } elseif ($found === false) {
2851 outputHtml('<strong>CHANGE:</strong> 404!');
2853 outputHtml('<strong>TMP:</strong> UNDONE!');
2857 // File not found, not readable or writeable
2858 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2861 // An error was detected!
2864 // Send notification to admin
2865 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2866 if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2868 sendAdminsEmails($subject, $templateName, $content, $userid);
2870 // Send out out-dated way
2871 $message = loadEmailTemplate($templateName, $content, $userid);
2872 sendAdminEmails($subject, $message);
2876 // Debug message logger
2877 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2878 // Is debug mode enabled?
2879 if ((isDebugModeEnabled()) || ($force === true)) {
2881 $message = str_replace("\r", '', str_replace("\n", '', $message));
2883 // Log this message away
2884 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write logfile debug.log!');
2885 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2890 // Handle extra values
2891 function handleExtraValues ($filterFunction, $value, $extraValue) {
2892 // Default is the value itself
2895 // Do we have a special filter function?
2896 if (!empty($filterFunction)) {
2897 // Does the filter function exist?
2898 if (function_exists($filterFunction)) {
2899 // Do we have extra parameters here?
2900 if (!empty($extraValue)) {
2901 // Put both parameters in one new array by default
2902 $args = array($value, $extraValue);
2904 // If we have an array simply use it and pre-extend it with our value
2905 if (is_array($extraValue)) {
2906 // Make the new args array
2907 $args = merge_array(array($value), $extraValue);
2910 // Call the multi-parameter call-back
2911 $ret = call_user_func_array($filterFunction, $args);
2913 // One parameter call
2914 $ret = call_user_func($filterFunction, $value);
2923 // Converts timestamp selections into a timestamp
2924 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2925 // Init test variable
2929 // Get last three chars
2930 $test = substr($id, -3);
2932 // Improved way of checking! :-)
2933 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2934 // Found a multi-selection for timings?
2935 $test = substr($id, 0, -3);
2936 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)) {
2937 // Generate timestamp
2938 $postData[$test] = createTimestampFromSelections($test, $postData);
2939 $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2940 $GLOBALS['skip_config'][$test] = true;
2942 // Remove data from array
2943 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2944 unset($postData[$test . '_' . $rem]);
2955 // Reverts the german decimal comma into Computer decimal dot
2956 function convertCommaToDot ($str) {
2957 // Default float is not a float... ;-)
2960 // Which language is selected?
2961 switch (getLanguage()) {
2962 case 'de': // German language
2963 // Remove german thousand dots first
2964 $str = str_replace('.', '', $str);
2966 // Replace german commata with decimal dot and cast it
2967 $float = (float)str_replace(',', '.', $str);
2970 default: // US and so on
2971 // Remove thousand dots first and cast
2972 $float = (float)str_replace(',', '', $str);
2980 // Handle menu-depending failed logins and return the rendered content
2981 function handleLoginFailures ($accessLevel) {
2982 // Default output is empty ;-)
2985 // Is the session data set?
2986 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
2987 // Ignore zero values
2988 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
2989 // Non-guest has login failures found, get both data and prepare it for template
2990 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "accessLevel={$accessLevel}<br />");
2992 'login_failures' => getSession('mailer_' . $accessLevel . '_failures'),
2993 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
2997 $OUT = loadTemplate('login_failures', true, $content);
3000 // Reset session data
3001 setSession('mailer_' . $accessLevel . '_failures', '');
3002 setSession('mailer_' . $accessLevel . '_last_failure', '');
3005 // Return rendered content
3010 function rebuildCache ($cache, $inc = '', $force = false) {
3012 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
3014 // Shall I remove the cache file?
3015 if (isCacheInstanceValid()) {
3017 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3019 $GLOBALS['cache_instance']->removeCacheFile($force);
3022 // Include file given?
3025 $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3027 // Is the include there?
3028 if (isIncludeReadable($inc)) {
3029 // And rebuild it from scratch
3030 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
3033 // Include not found!
3034 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3040 // Determines the real remote address
3041 function determineRealRemoteAddress () {
3042 // Is a proxy in use?
3043 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3045 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3046 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3047 // Yet, another proxy
3048 $address = $_SERVER['HTTP_CLIENT_IP'];
3050 // The regular address when no proxy was used
3051 $address = $_SERVER['REMOTE_ADDR'];
3054 // This strips out the real address from proxy output
3055 if (strstr($address, ',')) {
3056 $addressArray = explode(',', $address);
3057 $address = $addressArray[0];
3060 // Return the result
3064 // Adds a bonus mail to the queue
3065 // This is a high-level function!
3066 function addNewBonusMail ($data, $mode = '', $output=true) {
3067 // Use mode from data if not set and availble ;-)
3068 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3070 // Generate receiver list
3071 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3074 if (!empty($receiver)) {
3075 // Add bonus mail to queue
3076 addBonusMailToQueue(
3088 // Mail inserted into bonus pool
3089 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3090 } elseif ($output) {
3091 // More entered than can be reached!
3092 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3095 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3099 // Determines referal id and sets it
3100 function determineReferalId () {
3101 // Skip this in non-html-mode and outside ref.php
3102 if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3104 // Check if refid is set
3105 if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3107 } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3108 // The variable user comes from the click-counter script click.php and we only accept this here
3109 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
3110 } elseif (isPostRequestParameterSet('refid')) {
3111 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3112 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
3113 } elseif (isGetRequestParameterSet('refid')) {
3114 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3115 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
3116 } elseif (isGetRequestParameterSet('ref')) {
3117 // Set refid=ref (the referal link uses such variable)
3118 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
3119 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3120 // Set session refid als global
3121 $GLOBALS['refid'] = bigintval(getSession('refid'));
3122 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3123 // Select a random user which has confirmed enougth mails
3124 $GLOBALS['refid'] = determineRandomReferalId();
3125 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (getConfig('def_refid') > 0)) {
3126 // Set default refid as refid in URL
3127 $GLOBALS['refid'] = getConfig('def_refid');
3129 // No default id when sql_patches is not installed or none set
3130 $GLOBALS['refid'] = '0';
3133 // Set cookie when default refid > 0
3134 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3135 // Default is not found
3138 // Do we have nickname or userid set?
3139 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3140 // Nickname in URL, so load the id
3141 $found = fetchUserData($GLOBALS['refid'], 'nickname');
3142 } elseif ($GLOBALS['refid'] > 0) {
3143 // Direct userid entered
3144 $found = fetchUserData($GLOBALS['refid']);
3147 // Is the record valid?
3148 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3149 // No, then reset referal id
3150 $GLOBALS['refid'] = getConfig('def_refid');
3154 setSession('refid', $GLOBALS['refid']);
3157 // Return determined refid
3158 return $GLOBALS['refid'];
3161 // Enables the reset mode and runs it
3162 function doReset () {
3163 // Enable the reset mode
3164 $GLOBALS['reset_enabled'] = true;
3167 runFilterChain('reset');
3170 // Our shutdown-function
3171 function shutdown () {
3172 // Call the filter chain 'shutdown'
3173 runFilterChain('shutdown', null);
3175 // Check if not in installation phase and the link is up
3176 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
3178 SQL_CLOSE(__FUNCTION__, __LINE__);
3179 } elseif (!isInstallationPhase()) {
3181 addFatalMessage(__FUNCTION__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3184 // Stop executing here
3189 function initMemberId () {
3190 $GLOBALS['member_id'] = '0';
3193 // Setter for member id
3194 function setMemberId ($memberid) {
3195 // We should not set member id to zero
3196 if ($memberid == '0') debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
3199 $GLOBALS['member_id'] = bigintval($memberid);
3202 // Getter for member id or returns zero
3203 function getMemberId () {
3204 // Default member id
3207 // Is the member id set?
3208 if (isMemberIdSet()) {
3210 $memberid = $GLOBALS['member_id'];
3217 // Checks ether the member id is set
3218 function isMemberIdSet () {
3219 return (isset($GLOBALS['member_id']));
3222 // Handle message codes from URL
3223 function handleCodeMessage () {
3224 if (isGetRequestParameterSet('code')) {
3225 // Default extension is 'unknown'
3228 // Is extension given?
3229 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
3231 // Convert the 'code' parameter from URL to a human-readable message
3232 $message = getMessageFromErrorCode(getRequestParameter('code'));
3234 // Load message template
3235 loadTemplate('message', false, $message);
3239 // Setter for extra title
3240 function setExtraTitle ($extraTitle) {
3241 $GLOBALS['extra_title'] = $extraTitle;
3244 // Getter for extra title
3245 function getExtraTitle () {
3246 // Is the extra title set?
3247 if (!isExtraTitleSet()) {
3248 // No, then abort here
3249 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
3253 return $GLOBALS['extra_title'];
3256 // Checks if the extra title is set
3257 function isExtraTitleSet () {
3258 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3261 // Generates a 'extension foo inactive' message
3262 function generateExtensionInactiveMessage ($ext_name) {
3263 // Is the extension empty?
3264 if (empty($ext_name)) {
3265 // This should not happen
3266 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3270 $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3272 // Is an admin logged in?
3274 // Then output admin message
3275 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3278 // Return prepared message
3282 // Generates a 'extension foo not installed' message
3283 function generateExtensionNotInstalledMessage ($ext_name) {
3284 // Is the extension empty?
3285 if (empty($ext_name)) {
3286 // This should not happen
3287 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3291 $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3293 // Is an admin logged in?
3295 // Then output admin message
3296 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3299 // Return prepared message
3303 // Generates a message depending on if the extension is not installed or not
3305 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3309 // Is the extension not installed or just deactivated?
3310 switch (isExtensionInstalled($ext_name)) {
3311 case true; // Deactivated!
3312 $message = generateExtensionInactiveMessage($ext_name);
3315 case false; // Not installed!
3316 $message = generateExtensionNotInstalledMessage($ext_name);
3319 default: // Should not happen!
3320 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3321 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3325 // Return the message
3329 // Reads a directory recursively by default and searches for files not matching
3330 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3331 // a whole directory.
3332 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3333 // Add default entries we should exclude
3334 $excludeArray[] = '.';
3335 $excludeArray[] = '..';
3336 $excludeArray[] = '.svn';
3337 $excludeArray[] = '.htaccess';
3339 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3344 $dirPointer = opendir(getConfig('PATH') . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3347 while ($baseFile = readdir($dirPointer)) {
3348 // Exclude '.', '..' and entries in $excludeArray automatically
3349 if (in_array($baseFile, $excludeArray, true)) {
3351 //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3355 // Construct include filename and FQFN
3356 $fileName = $baseDir . $baseFile;
3357 $FQFN = getConfig('PATH') . $fileName;
3359 // Remove double slashes
3360 $FQFN = str_replace('//', '/', $FQFN);
3362 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3363 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3364 // These Lines are only for debugging!!
3365 //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3366 //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3367 //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3373 // Skip also files with non-matching prefix genericly
3374 if (($recursive === true) && (isDirectory($FQFN))) {
3375 // Is a redirectory so read it as well
3376 $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3378 // And skip further processing
3380 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3382 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3384 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3385 // Skip wrong suffix as well
3386 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3388 } elseif (!isFileReadable($FQFN)) {
3389 // Not readable so skip it
3390 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3394 // Is the file a PHP script or other?
3395 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3396 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3397 // Is this a valid include file?
3398 if ($extension == '.php') {
3399 // Remove both for extension name
3400 $extName = substr($baseFile, strlen($prefix), -4);
3402 // Is the extension valid and active?
3403 if (isExtensionNameValid($extName)) {
3404 // Then add this file
3405 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3406 $files[] = $fileName;
3408 // Add non-extension files as well
3409 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3410 if ($addBaseDir === true) {
3411 $files[] = $fileName;
3413 $files[] = $baseFile;
3417 // We found .php file but should not search for them, why?
3418 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
3420 } elseif (substr($baseFile, -4, 4) == $extension) {
3421 // Other, generic file found
3422 $files[] = $fileName;
3427 closedir($dirPointer);
3432 // Return array with include files
3433 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3437 // Maps a module name into a database table name
3438 function mapModuleToTable ($moduleName) {
3439 // Map only these, still lame code...
3440 switch ($moduleName) {
3441 // 'index' is the guest's menu
3442 case 'index': $moduleName = 'guest'; break;
3443 // ... and 'login' the member's menu
3444 case 'login': $moduleName = 'member'; break;
3445 // Anything else will not be mapped, silently.
3452 // Add SQL debug data to array for later output
3453 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3454 // Already executed?
3455 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3456 // Then abort here, we don't need to profile a query twice
3460 // Remeber this as profiled (or not, but we don't care here)
3461 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3463 // Do we have cache?
3464 if (!isset($GLOBALS['debug_sql_available'])) {
3465 // Check it and cache it in $GLOBALS
3466 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3469 // Don't execute anything here if we don't need or ext-other is missing
3470 if ($GLOBALS['debug_sql_available'] === false) {
3476 'num_rows' => SQL_NUMROWS($result),
3477 'affected' => SQL_AFFECTEDROWS(),
3478 'sql_str' => $sqlString,
3479 'timing' => $timing,
3480 'file' => basename($F),
3485 $GLOBALS['debug_sqls'][] = $record;
3488 // Initializes the cache instance
3489 function initCacheInstance () {
3490 // Load include for CacheSystem class
3491 loadIncludeOnce('inc/classes/cachesystem.class.php');
3493 // Initialize cache system only when it's needed
3494 $GLOBALS['cache_instance'] = new CacheSystem();
3495 if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3496 // Failed to initialize cache sustem
3497 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3501 // Getter for message from array or raw message
3502 function getMessageFromIndexedArray ($message, $pos, $array) {
3503 // Check if the requested message was found in array
3504 if (isset($array[$pos])) {
3505 // ... if yes then use it!
3506 $ret = $array[$pos];
3508 // ... else use default message
3516 // Print code with line numbers
3517 function linenumberCode ($code) {
3518 if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3519 $count_lines = count($codeE);
3521 $r = 'Line | Code:<br />';
3522 foreach($codeE as $line => $c) {
3523 $r .= '<div class="line"><span class="linenum">';
3524 if ($count_lines == 1) {
3527 $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
3532 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3535 return '<div class="code">' . $r . '</div>';
3538 // Convert ';' to ', ' for e.g. receiver list
3539 function convertReceivers ($old) {
3540 return str_replace(';', ', ', $old);
3543 // Determines the right page title
3544 function determinePageTitle () {
3545 // Config and database connection valid?
3546 if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3550 // Title decoration enabled?
3551 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3553 // Do we have some extra title?
3554 if (isExtraTitleSet()) {
3556 $TITLE .= getExtraTitle() . ' by ';
3560 $TITLE .= getConfig('MAIN_TITLE');
3562 // Add title of module? (middle decoration will also be added!)
3563 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3564 $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3567 // Add title from what file
3569 if (getModule() == 'login') $mode = 'member';
3570 elseif (getModule() == 'index') $mode = 'guest';
3571 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3573 // Add title decorations? (right)
3574 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3576 // Remember title in constant for the template
3577 $pageTitle = $TITLE;
3578 } elseif ((isInstalled()) && (isAdminRegistered())) {
3579 // Installed, admin registered but no ext-sql_patches
3580 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3581 } elseif ((isInstalled()) && (!isAdminRegistered())) {
3582 // Installed but no admin registered
3583 $pageTitle = getMessage('SETUP_OF_MAILER');
3584 } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3585 // Installation mode
3586 $pageTitle = getMessage('INSTALLATION_OF_MAILER');
3588 // Configuration not found!
3589 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3591 // Do not add the fatal message in installation mode
3592 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3596 return decodeEntities($pageTitle);
3599 // Checks wethere there is a cache file there. This function is cached.
3600 function isTemplateCached ($template) {
3601 // Do we have cached this result?
3602 if (!isset($GLOBALS['template_cache'][$template])) {
3604 $FQFN = generateCacheFqfn($template);
3607 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3611 return $GLOBALS['template_cache'][$template];
3614 // Flushes non-flushed template cache to disk
3615 function flushTemplateCache ($template, $eval) {
3616 // Is this cache flushed?
3617 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3619 $FQFN = generateCacheFqfn($template);
3621 // Replace username with a call
3622 $eval = str_replace('$username', '".getUsername()."', $eval);
3625 writeToFile($FQFN, $eval, true);
3629 // Reads a template cache
3630 function readTemplateCache ($template) {
3632 if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3634 $FQFN = generateCacheFqfn($template);
3637 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3641 return $GLOBALS['template_eval'][$template];
3644 // Escapes quotes (default is only double-quotes)
3645 function escapeQuotes ($str, $single = false) {
3646 // Should we escape all?
3647 if ($single === true) {
3648 // Escape all (including null)
3649 $str = addslashes($str);
3651 // Escape only double-quotes but prevent double-quoting
3652 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3655 // Return the escaped string
3659 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3660 function escapeJavaScriptQuotes ($str) {
3661 // Replace all double-quotes and secure back-ticks
3662 $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3668 // Send out mails depending on the 'mod/modes' combination
3669 // @TODO Lame description for this function
3670 function sendModeMails ($mod, $modes) {
3672 if (fetchUserData(getMemberId())) {
3673 // Extract salt from cookie
3674 $salt = substr(getSession('u_hash'), 0, -40);
3676 // Now let's compare passwords
3677 $hash = encodeHashForCookie(getUserData('password'));
3679 // Does the hash match or should we change it?
3680 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
3682 $content = getUserDataArray();
3685 $content['gender'] = translateGender($content['gender']);
3687 // Clear/init the content variable
3688 $content['message'] = '';
3691 // @TODO Move this in a filter
3694 foreach ($modes as $mode) {
3696 case 'normal': break; // Do not add any special lines
3697 case 'email': // Email was changed!
3698 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestParameter('old_email')."\n";
3701 case 'pass': // Password was changed
3702 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3706 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3707 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3712 if (isExtensionActive('country')) {
3713 // Replace code with description
3714 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
3717 // Merge content with data from POST
3718 $content = merge_array($content, postRequestArray());
3721 $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3723 if (getConfig('admin_notify') == 'Y') {
3724 // The admin needs to be notified about a profile change
3725 $message_admin = 'admin_mydata_notify';
3726 $sub_adm = getMessage('ADMIN_CHANGED_DATA');
3729 $message_admin = '';
3733 // Set subject lines
3734 $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3736 // Output success message
3737 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3740 default: // Unsupported module!
3741 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3742 $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
3746 // Passwords mismatch
3747 $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
3750 // Could not load profile
3751 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
3754 // Send email to user if required
3755 if ((!empty($sub_mem)) && (!empty($message))) {
3757 sendEmail($content['email'], $sub_mem, $message);
3760 // Send only if no other error has occured
3761 if (empty($content)) {
3762 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3764 sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3765 } elseif (getConfig('admin_notify') == 'Y') {
3766 // Cannot send mails to admin!
3767 $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3770 $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3775 loadTemplate('admin_settings_saved', false, $content);
3778 // Generates a 'selection box' from given array
3779 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
3781 $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3782 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3784 // Walk through all options
3785 foreach ($options as $option) {
3786 // Add the <option> entry
3787 if (empty($optionContent)) {
3788 // ... from template
3789 $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
3792 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3796 // Finish selection box
3797 $OUT .= '</select>';
3801 'selection_box' => $OUT,
3802 'module' => getModule(),
3806 // Load template and return it
3807 return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
3810 // Get a module from filename and access level
3811 function getModuleFromFileName ($file, $accessLevel) {
3812 // Default is 'invalid';
3813 $modCheck = 'invalid';
3815 // @TODO This is still very static, rewrite it somehow
3816 switch ($accessLevel) {
3818 $modCheck = 'admin';
3824 $modCheck = getModule();
3827 default: // Unsupported file name / access level
3828 debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3836 // Encodes an URL for adding session id, etc.
3837 function encodeUrl ($url, $outputMode = '0') {
3838 // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
3839 if ((strpos($url, session_name()) !== false) || (getOutputMode() == -3)) return $url;
3841 // Do we have a valid session?
3842 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3844 // Determine right seperator
3845 $seperator = '&';
3846 if (strpos($url, '?') === false) {
3849 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3855 if (session_id() != '') {
3856 $url .= $seperator . session_name() . '=' . session_id();
3861 if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3863 $url = '{?URL?}/' . $url;
3870 // Simple check for spider
3871 function isSpider () {
3873 $userAgent = strtolower(detectUserAgent(true));
3875 // It should not be empty, if so it is better a spider/bot
3876 if (empty($userAgent)) return true;
3879 return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
3882 // Prepares the header for HTML output
3883 function loadHtmlHeader () {
3885 // 1.) pre_page_header (mainly loads the page_header template and includes
3886 // meta description)
3887 runFilterChain('pre_page_header');
3889 // Here can be something be added, but normally one of the two filters
3890 // around this line should do the job for you.
3892 // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
3893 // to close the head-tag)
3894 // Include more header data here
3895 runFilterChain('post_page_header');
3898 // Adds page header and footer to output array element
3899 function addPageHeaderFooter () {
3903 // Add them all together. This is maybe to simple
3904 foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
3905 // Add page part if set
3906 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
3909 // Transfer $OUT to 'output'
3910 $GLOBALS['output'] = $OUT;
3913 // Generates meta description for current module and 'what' value
3914 function generateMetaDescriptionCode () {
3915 // Only include from guest area and if sql_patches has correct version
3916 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3917 // Construct dynamic description
3918 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
3920 // Output it directly
3921 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
3925 unset($GLOBALS['ref_level']);
3928 // Generates an FQFN for template cache from the given template name
3929 function generateCacheFqfn ($template) {
3931 if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
3932 // Generate the FQFN
3933 $GLOBALS['template_cache_fqfn'][$template] = sprintf("%s_compiled/html/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3937 return $GLOBALS['template_cache_fqfn'][$template];
3940 // Function to search for the last modified file
3941 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
3943 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
3944 // Does it match what we are looking for? (We skip a lot files already!)
3945 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
3946 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
3948 $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
3949 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
3951 // Walk through all entries
3952 foreach ($ds as $d) {
3953 // Generate proper FQFN
3954 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir . '/' . $d);
3956 // Is it a file and readable?
3957 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
3958 if (isFileReadable($FQFN)) {
3959 // $FQFN is a readable file so extract the requested data from it
3960 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
3961 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
3963 // Is the file more recent?
3964 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
3965 // This file is newer as the file before
3966 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
3967 $last_changed['path_name'] = $FQFN;
3968 $last_changed[$lookFor] = $check;
3972 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
3977 // "Fixes" null or empty string to count of dashes
3978 function fixNullEmptyToDashes ($str, $num) {
3979 // Use str as default
3983 if ((is_null($str)) || (trim($str) == '')) {
3985 $return = str_repeat('-', $num);
3988 // Return final string
3992 // Handles the braces [] of a field (e.g. value of 'name' attribute)
3993 function handleFieldWithBraces ($field) {
3994 // Are there braces [] at the end?
3995 if (substr($field, -2, 2) == '[]') {
3996 // Try to find one and replace it. I do it this way to allow easy
3997 // extending of this code.
3998 foreach (array('admin_list_builder_id_value') as $key) {
3999 // Is the cache entry set?
4000 if (isset($GLOBALS[$key])) {
4002 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
4014 //////////////////////////////////////////////////
4015 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
4016 //////////////////////////////////////////////////
4018 if (!function_exists('html_entity_decode')) {
4019 // Taken from documentation on www.php.net
4020 function html_entity_decode ($string) {
4021 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
4022 $trans_tbl = array_flip($trans_tbl);
4023 return strtr($string, $trans_tbl);
4027 if (!function_exists('http_build_query')) {
4028 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
4029 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
4031 foreach ((array)$data as $k => $v) {
4032 if (is_int($k) && $prefix != null) {
4033 $k = urlencode($prefix . $k);
4036 if ((!empty($key)) || ($key === 0)) $k = $key . '[' . urlencode($k) . ']';
4038 if (is_array($v) || is_object($v)) {
4039 array_push($ret, http_build_query($v, '', $sep, $k));
4041 array_push($ret, $k.'='.urlencode($v));
4045 if (empty($sep)) $sep = ini_get('arg_separator.output');
4047 return implode($sep, $ret);