2 /************************************************************************
3 * MXChange v0.2.1 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 - 2008 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
44 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
45 function OUTPUT_HTML ($HTML, $newLine = true) {
46 // Some global variables
47 global $OUTPUT, $username;
49 // Prepare IP number and User Agent
50 $REMOTE_ADDR = detectRemoteAddr();
51 $HTTP_USER_AGENT = detectUserAgent();
53 // Do we have HTML-Code here?
55 // Yes, so we handle it as you have configured
56 switch (getConfig('OUTPUT_MODE'))
59 // That's why you don't need any \n at the end of your HTML code... :-)
60 if (constant('_OB_CACHING') == 'on') {
61 // Output into PHP's internal buffer
64 // That's why you don't need any \n at the end of your HTML code... :-)
65 if ($newLine) print("\n");
67 // Render mode for old or lame servers...
70 // That's why you don't need any \n at the end of your HTML code... :-)
71 if ($newLine) $OUTPUT .= "\n";
76 // If we are switching from render to direct output rendered code
77 if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != 'on')) { outputRawCode($OUTPUT); $OUTPUT = ''; }
79 // The same as above... ^
81 if ($newLine) print("\n");
85 // Huh, something goes wrong or maybe you have edited config.php ???
86 app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
89 } elseif ((constant('_OB_CACHING') == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
90 // Headers already sent?
93 DEBUG_LOG(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
95 // Trigger an user error
96 debug_report_bug('Headers are already sent!');
99 // Output cached HTML code
100 $OUTPUT = ob_get_contents();
102 // Clear output buffer for later output if output is found
103 if (!empty($OUTPUT)) {
108 sendHeader('HTTP/1.1 200');
111 $now = gmdate('D, d M Y H:i:s') . ' GMT';
113 // General headers for no caching
114 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
115 sendHeader('Last-Modified: ' . $now);
116 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
117 sendHeader('Pragma: no-cache'); // HTTP/1.0
118 sendHeader('Connection: Close');
120 // Extension 'rewrite' installed?
121 if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
122 $OUTPUT = rewriteLinksInCode($OUTPUT);
125 // Compile and run finished rendered HTML code
126 while (strpos($OUTPUT, '{!') > 0) {
127 // Replace _MYSQL_PREFIX
128 $OUTPUT = str_replace('{!_MYSQL_PREFIX!}', getConfig('_MYSQL_PREFIX'), $OUTPUT);
130 // Prepare the content and eval() it...
133 $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
136 // Was that eval okay?
137 if (empty($newContent)) {
138 // Something went wrong!
139 app_die(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . htmlentities($eval) . '</pre>');
141 $OUTPUT = $newContent;
144 // Output code here, DO NOT REMOVE! ;-)
145 outputRawCode($OUTPUT);
146 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($OUTPUT))) {
147 // Rewrite links when rewrite extension is active
148 if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
149 $OUTPUT = rewriteLinksInCode($OUTPUT);
152 // Compile and run finished rendered HTML code
153 while (strpos($OUTPUT, '{!') > 0) {
154 $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
158 // Output code here, DO NOT REMOVE! ;-)
159 outputRawCode($OUTPUT);
163 // Output the raw HTML code
164 function outputRawCode ($HTML) {
165 // Output stripped HTML code to avoid broken JavaScript code, etc.
166 print(stripslashes(stripslashes($HTML)));
168 // Flush the output if only constant('_OB_CACHING') is not 'on'
169 if (constant('_OB_CACHING') != 'on') {
175 // Init fatal message array
176 function initFatalMessages () {
177 $GLOBALS['fatal_messages'] = array();
180 // Getter for whole fatal error messages
181 function getFatalArray () {
182 return $GLOBALS['fatal_messages'];
185 // Add a fatal error message to the queue array
186 function addFatalMessage ($F, $L, $message, $extra='') {
187 if (is_array($extra)) {
188 // Multiple extras for a message with masks
189 $message = call_user_func_array('sprintf', $extra);
190 } elseif (!empty($extra)) {
191 // $message is text with a mask plus extras to insert into the text
192 $message = sprintf($message, $extra);
195 // Add message to $GLOBALS['fatal_messages']
196 $GLOBALS['fatal_messages'][] = $message;
198 // Log fatal messages away
199 DEBUG_LOG($F, $L, " message={$message}");
202 // Getter for total fatal message count
203 function getTotalFatalErrors () {
207 // Do we have at least the first entry?
208 if (!empty($GLOBALS['fatal_messages'][0])) {
210 $count = count($GLOBALS['fatal_messages']);
217 // Load a template file and return it's content (only it's name; do not use ' or ")
218 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
219 // @TODO Remove this sanity-check if all is fine
220 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
222 // Prepare IP number and User Agent
223 $REMOTE_ADDR = detectRemoteAddr();
224 $HTTP_USER_AGENT = detectUserAgent();
226 // Add more variables which you want to use in your template files
227 global $DATA, $username;
229 // Make all template names lowercase
230 $template = strtolower($template);
232 // Count the template load
233 incrementConfigEntry('num_templates');
237 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
239 // Generate date/time string
240 $date_time = generateDateTime(time(), '1');
242 // Is content an array
243 if (is_array($content)) $content['date_time'] = $date_time;
245 // @DEPRECATED Try to rewrite the if() condition
246 if ($template == 'member_support_form') {
247 // Support request of a member
248 $result = SQL_QUERY_ESC("SELECT `userid`, `gender`, `surname`, `family`, `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
249 array(getUserId()), __FUNCTION__, __LINE__);
251 // Is content an array?
252 if (is_array($content)) {
254 $content = merge_array($content, SQL_FETCHARRAY($result));
257 $content['gender'] = translateGender($content['gender']);
260 // @TODO Find all templates which are using these direct variables and rewrite them.
261 // @TODO After this step is done, this else-block is history
262 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
265 $gender = translateGender($gender);
266 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
270 SQL_FREERESULT($result);
274 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
277 // Check for admin/guest/member templates
278 if (strpos($template, 'admin_') > -1) {
279 // Admin template found
281 } elseif (strpos($template, 'guest_') > -1) {
282 // Guest template found
284 } elseif (strpos($template, 'member_') > -1) {
285 // Member template found
287 } elseif (strpos($template, 'install_') > -1) {
288 // Installation template found
290 } elseif (strpos($template, 'ext_') > -1) {
291 // Extension template found
293 } elseif (strpos($template, 'la_') > -1) {
294 // 'Logical-area' template found
296 } elseif (strpos($template, 'js_') > -1) {
297 // JavaScript template found
300 // Test for extension
301 $test = substr($template, 0, strpos($template, '_'));
302 if (EXT_IS_ACTIVE($test)) {
303 // Set extra path to extension's name
308 ////////////////////////
309 // Generate file name //
310 ////////////////////////
311 $FQFN = $basePath . $mode . $template . '.tpl';
313 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
314 // Select what depended header/footer template file for admin/guest/member area
315 $file2 = sprintf("%s%s%s_%s.tpl",
323 if (isFileReadable($file2)) $FQFN = $file2;
325 // Remove variable from memory
329 // Does the special template exists?
330 if (!isFileReadable($FQFN)) {
331 // Reset to default template
332 $FQFN = $basePath . $template . '.tpl';
335 // Now does the final template exists?
336 if (isFileReadable($FQFN)) {
337 // The local file does exists so we load it. :)
338 $tmpl_file = readFromFile($FQFN);
340 // Replace ' to our own chars to preventing them being quoted
341 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
343 // Do we have to compile the code?
345 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
347 $eval = "\$ret = \"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
349 // NEW WAY: $ret = str_replace("\$content", "\$GLOBALS[compile][".$template."]", $tmpl_file);
350 // NEW WAY: $ret = str_replace("\$DATA", "\$GLOBALS[data][".$template."]", $ret);
351 // NEW WAY: $GLOBALS['compile'][$template] = $content;
352 // NEW WAY: $GLOBALS['data'][$template] = $DATA;
354 // Simply return loaded code
358 // Normal HTML output?
359 if ($GLOBALS['output_mode'] == 0) {
360 // Add surrounding HTML comments to help finding bugs faster
361 $ret = "<!-- Template " . $template . " - Start -->\n" . $ret . "<!-- Template " . $template . " - End -->\n";
363 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
364 // Only admins shall see this warning or when installation mode is active
365 $ret = "<br /><span class=\"guest_failed\">{--TEMPLATE_404--}</span><br />
366 (".basename($FQFN).")<br />
368 {--TEMPLATE_CONTENT--}
369 <pre>".print_r($content, true)."</pre>
371 <pre>".print_r($DATA, true)."</pre>
375 // Remove content and data
379 // Do we have some content to output or return?
381 // Not empty so let's put it out! ;)
382 if ($return === true) {
383 // Return the HTML code
389 } elseif (isDebugModeEnabled()) {
390 // Warning, empty output!
391 return "E:" . $template."<br />\n";
395 // Send mail out to an email address
396 function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '') {
397 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
399 // Compile subject line (for POINTS constant etc.)
400 $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
404 if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
405 // Value detected, is the message extension installed?
406 // @TODO Extension 'msg' does not exist
407 if (EXT_IS_ACTIVE('msg')) {
408 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
411 // Load email address
412 $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
413 array(bigintval($toEmail)), __FUNCTION__, __LINE__);
414 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />");
416 // Does the user exist?
417 if (SQL_NUMROWS($result_email)) {
418 // Load email address
419 list($toEmail) = SQL_FETCHROW($result_email);
422 $toEmail = getConfig('WEBMASTER');
426 SQL_FREERESULT($result_email);
428 } elseif ($toEmail == '0') {
430 $toEmail = getConfig('WEBMASTER');
432 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
434 // Check for PHPMailer or debug-mode
435 if (!checkPhpMailerUsage()) {
436 // Not in PHPMailer-Mode
437 if (empty($mailHeader)) {
438 // Load email header template
439 $mailHeader = LOAD_EMAIL_TEMPLATE('header');
442 $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
444 } elseif (isDebugModeEnabled()) {
445 if (empty($mailHeader)) {
446 // Load email header template
447 $mailHeader = LOAD_EMAIL_TEMPLATE('header');
450 $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
455 $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
459 $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
462 // Fix HTML parameter (default is no!)
463 if (empty($HTML)) $HTML = 'N';
464 if (isDebugModeEnabled()) {
465 // In debug mode we want to display the mail instead of sending it away so we can debug this part
467 ".htmlentities(trim($mailHeader))."
469 Subject : " . $subject."
470 Message : " . $message."
472 } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE('html_mail'))) {
473 // Send mail as HTML away
474 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
475 } elseif (!empty($toEmail)) {
477 sendRawEmail($toEmail, $subject, $message, $mailHeader);
478 } elseif ($HTML == 'N') {
480 sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
484 // Check if legacy or PHPMailer command
485 // @TODO Rewrite this to an extension 'smtp'
487 function checkPhpMailerUsage() {
488 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
491 // Send out a raw email with PHPMailer class or legacy mail() command
492 function sendRawEmail ($toEmail, $subject, $message, $from) {
493 // Shall we use PHPMailer class or legacy mode?
494 if (checkPhpMailerUsage()) {
495 // Use PHPMailer class with SMTP enabled
496 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
497 loadIncludeOnce('inc/phpmailer/class.smtp.php');
500 $mail = new PHPMailer();
501 $mail->PluginDir = sprintf("%sinc/phpmailer/", getConfig('PATH'));
504 $mail->SMTPAuth = true;
505 $mail->Host = getConfig('SMTP_HOSTNAME');
507 $mail->Username = getConfig('SMTP_USER');
508 $mail->Password = getConfig('SMTP_PASSWORD');
510 $mail->From = getConfig('WEBMASTER');
514 $mail->FromName = getConfig('MAIN_TITLE');
515 $mail->Subject = $subject;
516 if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($message) != $message)) {
517 $mail->Body = $message;
518 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
519 $mail->WordWrap = 70;
522 $mail->Body = decodeEntities($message);
524 $mail->AddAddress($toEmail, '');
525 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
526 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
527 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
530 // Use legacy mail() command
531 mail($toEmail, $subject, decodeEntities($message), $from);
535 // Generate a password in a specified length or use default password length
536 function generatePassword ($length = 0) {
537 // Auto-fix invalid length of zero
538 if ($length == 0) $length = getConfig('pass_len');
540 // Initialize array with all allowed chars
541 $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,-,+,_,/,.');
543 // Start creating password
545 for ($i = 0; $i < $length; $i++) {
546 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
549 // When the size is below 40 we can also add additional security by scrambling
550 // it. Otherwise we may corrupt hashes
551 if (strlen($PASS) <= 40) {
552 // Also scramble the password
553 $PASS = scrambleString($PASS);
556 // Return the password
560 // Generates a human-readable timestamp from the Uni* stamp
561 function generateDateTime ($time, $mode = '0') {
562 // Filter out numbers
563 $time = bigintval($time);
565 // If the stamp is zero it mostly didn't "happen"
568 return getMessage('NEVER_HAPPENED');
571 switch (getLanguage())
573 case 'de': // German date / time format
575 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
576 case '1': $ret = strtolower(date("d.m.Y - H:i", $time)); break;
577 case '2': $ret = date("d.m.Y|H:i", $time); break;
578 case '3': $ret = date("d.m.Y", $time); break;
580 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
585 default: // Default is the US date / time format!
587 case '0': $ret = date("r", $time); break;
588 case '1': $ret = date("Y-m-d - g:i A", $time); break;
589 case '2': $ret = date("y-m-d|H:i", $time); break;
590 case '3': $ret = date("y-m-d", $time); break;
592 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
599 // Translates Y/N to yes/no
600 function translateYesNo ($yn) {
602 $translated = "??? (" . $yn.')';
604 case 'Y': $translated = getMessage('YES'); break;
605 case 'N': $translated = getMessage('NO'); break;
608 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
616 // Translates the "pool type" into human-readable
617 function translatePoolType ($type) {
618 // Default?type is unknown
619 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
622 $constName = sprintf("POOL_TYPE_%s", $type);
625 if (defined($constName)) {
627 $translated = getMessage($constName);
630 // Return "translation"
634 // Translates the american decimal dot into a german comma
635 function translateComma ($dotted, $cut = true, $max = 0) {
636 // Default is 3 you can change this in admin area "Misc -> Misc Options"
637 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
639 // Use from config is default
640 $maxComma = getConfig('max_comma');
642 // Use from parameter?
643 if ($max > 0) $maxComma = $max;
646 if (($cut) && ($max == 0)) {
647 // Test for commata if in cut-mode
648 $com = explode('.', $dotted);
649 if (count($com) < 2) {
650 // Don't display commatas even if there are none... ;-)
656 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
659 switch (getLanguage()) {
661 $dotted = number_format($dotted, $maxComma, ',', '.');
665 $dotted = number_format($dotted, $maxComma, '.', ',');
669 // Return translated value
673 // Translate Uni*-like gender to human-readable
674 function translateGender ($gender) {
676 $ret = '!' . $gender . '!';
678 // Male/female or company?
680 case 'M': $ret = getMessage('GENDER_M'); break;
681 case 'F': $ret = getMessage('GENDER_F'); break;
682 case 'C': $ret = getMessage('GENDER_C'); break;
684 // Log unknown gender
685 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
689 // Return translated gender
693 // "Translates" the user status
694 function translateUserStatus ($status) {
700 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
705 $ret = getMessage('ACCOUNT_DELETED');
709 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
710 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
718 // Generates an URL for the dereferer
719 function DEREFERER ($URL) {
720 // Don't de-refer our own links!
721 if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
722 // De-refer this link
723 $URL = 'modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
730 // Generates an URL for the frametester
731 function FRAMETESTER ($URL) {
732 // Prepare frametester URL
733 $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&url=%s",
734 encodeString(compileUriCode($URL))
736 return $frametesterUrl;
739 // Count entries from e.g. a selection box
740 function countSelection ($array) {
742 if (is_array($array)) {
743 foreach ($array as $key => $selected) {
744 if (!empty($selected)) $ret++;
750 // Generate XHTML code for the CAPTCHA
751 function generateCaptchaCode ($code, $type, $DATA, $uid) {
752 return '<IMG border="0" alt="Code" src="{?URL?}/mailid_top.php?uid=' . $uid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
755 // Loads an email template and compiles it
756 function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
759 // Our configuration is kept non-global here
760 $_CONFIG = getConfigArray();
762 // Make sure all template names are lowercase!
763 $template = strtolower($template);
765 // Default 'nickname' if extension is not installed
768 // Prepare IP number and User Agent
769 $REMOTE_ADDR = detectRemoteAddr();
770 $HTTP_USER_AGENT = detectUserAgent();
773 $ADMIN = getConfig('MAIN_TITLE');
775 // Is the admin logged in?
778 $aid = getCurrentAdminId();
781 $ADMIN = getAdminEmail($aid);
784 // Neutral email address is default
785 $email = getConfig('WEBMASTER');
787 // Expiration in a nice output format
788 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
789 if (getConfig('auto_purge') == 0) {
790 // Will never expire!
791 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
793 // Create nice date string
794 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
797 // Is content an array?
798 if (is_array($content)) {
799 // Add expiration to array, $EXPIRATION is now deprecated!
800 $content['expiration'] = $EXPIRATION;
804 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />");
805 if (($UID > 0) && (is_array($content))) {
806 // If nickname extension is installed, fetch nickname as well
807 if (EXT_IS_ACTIVE('nickname')) {
808 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
810 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email`, `nickname` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
811 array(bigintval($UID)), __FUNCTION__, __LINE__);
813 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
815 $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
816 array(bigintval($UID)), __FUNCTION__, __LINE__);
819 // Fetch and merge data
820 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
821 $content = merge_array($content, SQL_FETCHARRAY($result));
822 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
825 SQL_FREERESULT($result);
828 // Translate M to male or F to female if present
829 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
831 // Overwrite email from data if present
832 if (isset($content['email'])) $email = $content['email'];
834 // Store email for some functions in global data array
835 $DATA['email'] = $email;
838 $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
840 // Check for admin/guest/member templates
841 if (strpos($template, 'admin_') > -1) {
842 // Admin template found
843 $FQFN = $basePath.'admin/' . $template.'.tpl';
844 } elseif (strpos($template, 'guest_') > -1) {
845 // Guest template found
846 $FQFN = $basePath.'guest/' . $template.'.tpl';
847 } elseif (strpos($template, 'member_') > -1) {
848 // Member template found
849 $FQFN = $basePath.'member/' . $template.'.tpl';
851 // Test for extension
852 $test = substr($template, 0, strpos($template, '_'));
853 if (EXT_IS_ACTIVE($test)) {
854 // Set extra path to extension's name
855 $FQFN = $basePath . $test.'/' . $template.'.tpl';
857 // No special filename
858 $FQFN = $basePath . $template.'.tpl';
862 // Does the special template exists?
863 if (!isFileReadable($FQFN)) {
864 // Reset to default template
865 $FQFN = $basePath . $template.'.tpl';
868 // Now does the final template exists?
870 if (isFileReadable($FQFN)) {
871 // The local file does exists so we load it. :)
872 $tmpl_file = readFromFile($FQFN);
873 $tmpl_file = SQL_ESCAPE($tmpl_file);
876 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
878 } elseif (!empty($template)) {
879 // Template file not found!
880 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
881 {--TEMPLATE_CONTENT--}
882 <pre>".print_r($content, true)."</pre>
884 <pre>".print_r($DATA, true)."</pre>
887 // Debug mode not active? Then remove the HTML tags
888 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
890 // No template name supplied!
891 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
894 // Is there some content?
895 if (empty($newContent)) {
897 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $tmpl_file;
898 // Add last error if the required function exists
899 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
902 // Remove content and data
906 // Return compiled content
907 return COMPILE_CODE($newContent);
910 // Generates a timestamp (some wrapper for mktime())
911 function makeTime ($H, $M, $S, $stamp) {
912 // Extract day, month and year from given timestamp
913 $day = date('d', $stamp);
914 $month = date('m', $stamp);
915 $year = date('Y', $stamp);
917 // Create timestamp for wished time which depends on extracted date
918 return mktime($H, $M, $S, $month, $day, $year);
921 // Redirects to an URL and if neccessarry extends it with own base URL
922 function redirectToUrl ($URL) {
923 // Compile out URI codes
924 $URL = compileUriCode($URL);
926 // Check if http(s):// is there
927 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
928 // Make all URLs full-qualified
929 $URL = getConfig('URL') . '/' . $URL;
932 // Three different debug ways...
933 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
934 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
935 //* DEBUG: */ die($URL);
937 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
938 $rel = ' rel="external"';
940 // Do we have internal or external URL?
941 if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
942 // Own (=internal) URL
947 $OUTPUT = ob_get_contents();
949 // Clear it only if there is content
950 if (!empty($OUTPUT)) {
954 // Simple probe for bots/spiders from search engines
955 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
956 // Secure the URL against bad things such als HTML insertions and so on...
957 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
959 // Output new location link as anchor
960 OUTPUT_HTML('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
961 } elseif (!headers_sent()) {
962 // Load URL when headers are not sent
963 //* DEBUG: */ debug_report_bug("URL={$URL}");
964 sendHeader('Location: '.str_replace('&', '&', $URL));
966 // Output error message
967 loadInclude('inc/header.php');
968 LOAD_TEMPLATE('redirect_url', false, str_replace('&', '&', $URL));
969 loadInclude('inc/footer.php');
972 // Shut the mailer down here
976 // Wrapper for redirectToUrl but URL comes from a configuration entry
977 function redirectToConfiguredUrl ($configEntry) {
979 $URL = getConfig($configEntry);
984 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
992 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
993 // Is the code a string?
994 if (!is_string($code)) {
995 // Silently return it
999 // Init replacement-array with full security characters
1000 $secChars = $GLOBALS['security_chars'];
1002 // Select smaller set of chars to replace when we e.g. want to compile URLs
1003 if (!$full) $secChars = $GLOBALS['url_chars'];
1005 // Compile constants
1006 if ($constants === true) {
1007 // BEFORE 0.2.1 : Language and data constants
1008 // WITH 0.2.1+ : Only language constants
1009 $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
1011 // BEFORE 0.2.1 : Not used
1012 // WITH 0.2.1+ : Data constants
1013 $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
1016 // Compile QUOT and other non-HTML codes
1017 foreach ($secChars['to'] as $k => $to) {
1018 // Do the reversed thing as in inc/libs/security_functions.php
1019 $code = str_replace($to, $secChars['from'][$k], $code);
1022 // But shall I keep simple quotes for later use?
1023 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1025 // Find $content[bla][blub] entries
1026 preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1028 // Are some matches found?
1029 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1030 // Replace all matches
1031 $matchesFound = array();
1032 foreach ($matches[0] as $key => $match) {
1033 // Fuzzy look has failed by default
1034 $fuzzyFound = false;
1036 // Fuzzy look on match if already found
1037 foreach ($matchesFound as $found => $set) {
1039 $test = substr($found, 0, strlen($match));
1041 // Does this entry exist?
1042 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
1043 if ($test == $match) {
1045 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
1052 if ($fuzzyFound === true) continue;
1054 // Take all string elements
1055 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1056 // Replace it in the code
1057 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
1058 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1059 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1060 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1061 $matchesFound[$match] = 1;
1062 } elseif (!isset($matchesFound[$match])) {
1063 // Not yet replaced!
1064 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
1065 $code = str_replace($match, "\"." . $match.".\"", $code);
1066 $matchesFound[$match] = 1;
1071 // Compile {?some_var?} to getConfig('some_var')
1072 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
1074 // Some entries found?
1075 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1076 // Replace all matches
1077 foreach ($matches[0] as $key => $match) {
1079 //* DEBUG: */ if ($key == 0) { print '<pre>'; debug_print_backtrace(); print '</pre>'; }
1080 //* DEBUG: */ print htmlentities($match).'['.strlen($match).']='.$matches[1][$key].'='.getConfig($matches[1][$key]).' (key='.$key.',len='.strlen($code).')<br />';
1081 $code = str_replace($match, getConfig($matches[1][$key]), $code);
1082 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die('<pre>'.htmlentities($code).'</pre>');
1086 // Return compiled code
1090 /************************************************************************
1092 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1093 * $a_sort sortiert: *
1095 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1096 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1097 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1098 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1099 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1101 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1102 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1103 * Sie, dass es doch nicht so schwer ist! :-) *
1105 ************************************************************************/
1106 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1108 while ($primary_key < count($a_sort)) {
1109 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1110 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1113 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1114 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1115 } elseif ($key != $key2) {
1116 // Sort numbers (E.g.: 9 < 10)
1117 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1118 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1122 // We have found two different values, so let's sort whole array
1123 foreach ($dummy as $sort_key => $sort_val) {
1124 $t = $dummy[$sort_key][$key];
1125 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1126 $dummy[$sort_key][$key2] = $t;
1137 // Write back sorted array
1142 function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
1145 if ($type == 'yn') {
1146 // This is a yes/no selection only!
1147 if ($id > 0) $prefix .= "[" . $id."]";
1148 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1150 // Begin with regular selection box here
1151 if (!empty($prefix)) $prefix .= "_";
1153 if ($id > 0) $type2 .= "[" . $id."]";
1154 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1159 for ($idx = 1; $idx < 32; $idx++) {
1160 $OUT .= "<option value=\"" . $idx."\"";
1161 if ($default == $idx) $OUT .= ' selected="selected"';
1162 $OUT .= ">" . $idx."</option>\n";
1166 case "month": // Month
1167 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1168 $OUT .= "<option value=\"" . $month."\"";
1169 if ($default == $month) $OUT .= ' selected="selected"';
1170 $OUT .= ">" . $descr."</option>\n";
1174 case "year": // Year
1176 $year = date('Y', time());
1178 // Use configured min age or fixed?
1179 if (GET_EXT_VERSION('other') >= '0.2.1') {
1181 $startYear = $year - getConfig('min_age');
1184 $startYear = $year - 16;
1187 // Calculate earliest year (100 years old people can still enter Internet???)
1188 $minYear = $year - 100;
1190 // Check if the default value is larger than minimum and bigger than actual year
1191 if (($default > $minYear) && ($default >= $year)) {
1192 for ($idx = $year; $idx < ($year + 11); $idx++) {
1193 $OUT .= "<option value=\"" . $idx."\"";
1194 if ($default == $idx) $OUT .= ' selected="selected"';
1195 $OUT .= ">" . $idx."</option>\n";
1197 } elseif ($default == -1) {
1198 // Current year minus 1
1199 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1201 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1204 // Get current year and subtract the configured minimum age
1205 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1206 // Calculate earliest year depending on extension version
1207 if (GET_EXT_VERSION('other') >= '0.2.1') {
1208 // Use configured minimum age
1209 $year = date('Y', time()) - getConfig('min_age');
1211 // Use fixed 16 years age
1212 $year = date('Y', time()) - 16;
1215 // Construct year selection list
1216 for ($idx = $minYear; $idx <= $year; $idx++) {
1217 $OUT .= "<option value=\"" . $idx."\"";
1218 if ($default == $idx) $OUT .= ' selected="selected"';
1219 $OUT .= ">" . $idx."</option>\n";
1226 for ($idx = 0; $idx < 60; $idx+=5) {
1227 if (strlen($idx) == 1) $idx = '0' . $idx;
1228 $OUT .= "<option value=\"" . $idx."\"";
1229 if ($default == $idx) $OUT .= ' selected="selected"';
1230 $OUT .= ">" . $idx."</option>\n";
1235 for ($idx = 0; $idx < 24; $idx++) {
1236 if (strlen($idx) == 1) $idx = '0' . $idx;
1237 $OUT .= "<option value=\"" . $idx."\"";
1238 if ($default == $idx) $OUT .= ' selected="selected"';
1239 $OUT .= ">" . $idx."</option>\n";
1244 $OUT .= "<option value=\"Y\"";
1245 if ($default == 'Y') $OUT .= ' selected="selected"';
1246 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1247 if ($default == 'N') $OUT .= ' selected="selected"';
1248 $OUT .= ">{--NO--}</option>\n";
1251 $OUT .= " </select>\n";
1256 // Deprecated : $length
1259 function generateRandomCode ($length, $code, $uid, $DATA = '') {
1260 // Build server string
1261 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
1264 $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY');
1265 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1266 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1267 $keys .= getConfig('ENCRYPT_SEPERATOR') . date("d-m-Y (l-F-T)", getConfig('patch_ctime'));
1268 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1270 // Build string from misc data
1271 $data = $code.getConfig('ENCRYPT_SEPERATOR') . $uid.getConfig('ENCRYPT_SEPERATOR') . $DATA;
1273 // Add more additional data
1274 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('u_hash');
1275 if (isUserIdSet()) $data .= getConfig('ENCRYPT_SEPERATOR').getUserId();
1276 if (isSessionVariableSet('mxchange_theme')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
1277 if (isSessionVariableSet('mx_lang')) $data .= getConfig('ENCRYPT_SEPERATOR').getLanguage();
1278 if (isset($GLOBALS['refid'])) $data .= getConfig('ENCRYPT_SEPERATOR') . $GLOBALS['refid'];
1280 // Calculate number for generating the code
1281 $a = $code + getConfig('_ADD') - 1;
1283 if (isConfigEntrySet('master_hash')) {
1284 // Generate hash with master salt from modula of number with the prime number and other data
1285 $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'));
1287 // Create number from hash
1288 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1290 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1291 $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, 8));
1293 // Create number from hash
1294 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1297 // At least 10 numbers shall be secure enought!
1298 $len = getConfig('code_length');
1299 if ($len == 0) $len = $length;
1300 if ($len == 0) $len = 10;
1302 // Cut off requested counts of number
1303 $return = substr(str_replace('.', '', $rcode), 0, $len);
1305 // Done building code
1309 // Does only allow numbers
1310 function bigintval ($num, $castValue = true) {
1311 // Filter all numbers out
1312 $ret = preg_replace("/[^0123456789]/", '', $num);
1315 if ($castValue) $ret = (double)$ret;
1317 // Has the whole value changed?
1318 // @TODO Remove this if() block if all is working fine
1319 if ('' . $ret . '' != '' . $num . '') {
1321 //debug_report_bug("{$ret}<>{$num}");
1328 // Insert the code in $img_code into jpeg or PNG image
1329 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1330 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1331 // Stop execution of function here because of over-sized code length
1333 } elseif (!$headerSent) {
1334 // Return in an HTML code code
1335 return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1339 $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
1340 if (isFileReadable($img)) {
1341 // Switch image type
1342 switch (getConfig('img_type'))
1345 // Okay, load image and hide all errors
1346 $image = @imagecreatefromjpeg($img);
1350 // Okay, load image and hide all errors
1351 $image = @imagecreatefrompng($img);
1355 // Exit function here
1356 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1360 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1361 $text_color = imagecolorallocate($image, 0, 0, 0);
1363 // Insert code into image
1364 imagestring($image, 5, 14, 2, $img_code, $text_color);
1366 // Return to browser
1367 sendHeader('Content-Type: image/' . getConfig('img_type'));
1369 // Output image with matching image factory
1370 switch (getConfig('img_type')) {
1371 case 'jpg': imagejpeg($image); break;
1372 case 'png': imagepng($image); break;
1375 // Remove image from memory
1376 imagedestroy($image);
1378 // Create selection box or array of splitted timestamp
1379 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1380 // Calculate 2-seconds timestamp
1381 $stamp = round($timestamp);
1382 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1384 // Do we have a leap year?
1386 $TEST = date('Y', time()) / 4;
1387 $M1 = date('m', time());
1388 $M2 = date('m', (time() + $timestamp));
1390 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1391 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1393 // First of all years...
1394 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1395 //* DEBUG: */ print("Y={$Y}<br />");
1397 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1398 //* DEBUG: */ print("M={$M}<br />");
1400 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1401 //* DEBUG: */ print("W={$W}<br />");
1403 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1404 //* DEBUG: */ print("D={$D}<br />");
1406 $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));
1407 //* DEBUG: */ print("h={$h}<br />");
1409 $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));
1410 //* DEBUG: */ print("m={$m}<br />");
1411 // And at last seconds...
1412 $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));
1413 //* DEBUG: */ print("s={$s}<br />");
1415 // Is seconds zero and time is < 60 seconds?
1416 if (($s == 0) && ($timestamp < 60)) {
1418 $s = round($timestamp);
1422 // Now we convert them in seconds...
1424 if ($return_array) {
1425 // Just put all data in an array for later use
1437 $OUT = "<div align=\"" . $align."\">\n";
1438 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1441 if (ereg('Y', $display) || (empty($display))) {
1442 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1445 if (ereg('M', $display) || (empty($display))) {
1446 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1449 if (ereg("W", $display) || (empty($display))) {
1450 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1453 if (ereg("D", $display) || (empty($display))) {
1454 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1457 if (ereg("h", $display) || (empty($display))) {
1458 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1461 if (ereg('m', $display) || (empty($display))) {
1462 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1465 if (ereg("s", $display) || (empty($display))) {
1466 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1472 if (ereg('Y', $display) || (empty($display))) {
1473 // Generate year selection
1474 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1475 for ($idx = 0; $idx <= 10; $idx++) {
1476 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1477 if ($idx == $Y) $OUT .= ' selected="selected"';
1478 $OUT .= ">" . $idx."</option>\n";
1480 $OUT .= " </select></td>\n";
1482 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1485 if (ereg('M', $display) || (empty($display))) {
1486 // Generate month selection
1487 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1488 for ($idx = 0; $idx <= 11; $idx++)
1490 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1491 if ($idx == $M) $OUT .= ' selected="selected"';
1492 $OUT .= ">" . $idx."</option>\n";
1494 $OUT .= " </select></td>\n";
1496 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1499 if (ereg("W", $display) || (empty($display))) {
1500 // Generate week selection
1501 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1502 for ($idx = 0; $idx <= 4; $idx++) {
1503 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1504 if ($idx == $W) $OUT .= ' selected="selected"';
1505 $OUT .= ">" . $idx."</option>\n";
1507 $OUT .= " </select></td>\n";
1509 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1512 if (ereg("D", $display) || (empty($display))) {
1513 // Generate day selection
1514 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1515 for ($idx = 0; $idx <= 31; $idx++) {
1516 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1517 if ($idx == $D) $OUT .= ' selected="selected"';
1518 $OUT .= ">" . $idx."</option>\n";
1520 $OUT .= " </select></td>\n";
1522 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1525 if (ereg("h", $display) || (empty($display))) {
1526 // Generate hour selection
1527 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1528 for ($idx = 0; $idx <= 23; $idx++) {
1529 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1530 if ($idx == $h) $OUT .= ' selected="selected"';
1531 $OUT .= ">" . $idx."</option>\n";
1533 $OUT .= " </select></td>\n";
1535 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1538 if (ereg('m', $display) || (empty($display))) {
1539 // Generate minute selection
1540 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1541 for ($idx = 0; $idx <= 59; $idx++) {
1542 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1543 if ($idx == $m) $OUT .= ' selected="selected"';
1544 $OUT .= ">" . $idx."</option>\n";
1546 $OUT .= " </select></td>\n";
1548 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1551 if (ereg("s", $display) || (empty($display))) {
1552 // Generate second selection
1553 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1554 for ($idx = 0; $idx <= 59; $idx++) {
1555 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1556 if ($idx == $s) $OUT .= ' selected="selected"';
1557 $OUT .= ">" . $idx."</option>\n";
1559 $OUT .= " </select></td>\n";
1561 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1564 $OUT .= "</table>\n";
1566 // Return generated HTML code
1572 function createTimestampFromSelections ($prefix, $POST) {
1573 // Initial return value
1576 // Do we have a leap year?
1578 $TEST = date('Y', time()) / 4;
1579 $M1 = date('m', time());
1580 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1581 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1582 // First add years...
1583 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1585 $ret += $POST[$prefix."_mo"] * 2628000;
1587 $ret += $POST[$prefix."_we"] * 604800;
1589 $ret += $POST[$prefix."_da"] * 86400;
1591 $ret += $POST[$prefix."_ho"] * 3600;
1593 $ret += $POST[$prefix."_mi"] * 60;
1594 // And at last seconds...
1595 $ret += $POST[$prefix."_se"];
1596 // Return calculated value
1600 // Sends out mail to all administrators
1601 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1602 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1603 // Trim template name
1604 $template = trim($template);
1606 // Load email template
1607 $message = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1609 // Check which admin shall receive this mail
1610 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1611 array($template), __FUNCTION__, __LINE__);
1612 if (SQL_NUMROWS($result) == 0) {
1613 // Create new entry (to all admins)
1614 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1615 array($template), __FUNCTION__, __LINE__);
1617 // Load admin IDs...
1618 // @TODO This can be, somehow, rewritten
1619 $adminIds = array();
1620 while ($content = SQL_FETCHARRAY($result)) {
1621 $adminIds[] = $content['admin_id'];
1625 SQL_FREERESULT($result);
1630 // "implode" IDs and query string
1631 $aid = implode(',', $adminIds);
1633 if (EXT_IS_ACTIVE('events')) {
1634 // Add line to user events
1635 EVENTS_ADD_LINE($subj, $message, $UID);
1637 // Log error for debug
1638 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1644 } elseif ($aid == '0') {
1645 // Select all email adresses
1646 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1647 __FUNCTION__, __LINE__);
1649 // If Admin-ID is not "to-all" select
1650 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1651 array($aid), __FUNCTION__, __LINE__);
1655 // Load email addresses and send away
1656 while ($content = SQL_FETCHARRAY($result)) {
1657 sendEmail($content['email'], $subj, $message);
1661 SQL_FREERESULT($result);
1664 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1665 function createFancyTime ($stamp) {
1666 // Get data array with years/months/weeks/days/...
1667 $data = createTimeSelections($stamp, '', '', '', true);
1669 foreach($data as $k => $v) {
1671 // Value is greater than 0 "eval" data to return string
1672 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1678 // Do we have something there?
1679 if (strlen($ret) > 0) {
1680 // Remove leading commata and space
1681 $ret = substr($ret, 2);
1684 $ret = "0 {--_SECONDS--}";
1687 // Return fancy time string
1692 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1693 $SEP = ''; $TOP = '';
1696 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1700 for ($page = 1; $page <= $PAGES; $page++) {
1701 // Is the page currently selected or shall we generate a link to it?
1702 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1703 // Is currently selected, so only highlight it
1704 $NAV .= "<strong>-";
1706 // Open anchor tag and add base URL
1707 $NAV .= "<a href=\"{?URL?}/modules.php?module=admin&what=" . getWhat()."&page=" . $page."&offset=" . $offset;
1709 // Add userid when we shall show all mails from a single member
1710 if ((REQUEST_ISSET_GET('uid')) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1712 // Close open anchor tag
1716 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1717 // Is currently selected, so only highlight it
1718 $NAV .= "-</strong>";
1724 // Add seperator if we have not yet reached total pages
1725 if ($page < $PAGES) $NAV .= " | ";
1728 // Define constants only once
1729 if (!defined('__NAV_OUTPUT')) {
1730 define('__NAV_OUTPUT' , $NAV);
1731 define('__NAV_COLSPAN', $colspan);
1732 define('__NAV_TOP' , $TOP);
1733 define('__NAV_SEP' , $SEP);
1736 // Load navigation template
1737 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1739 if ($return === true) {
1740 // Return generated HTML-Code
1748 // Extract host from script name
1749 function extractHostnameFromUrl (&$script) {
1750 // Use default SERVER_URL by default... ;) So?
1751 $url = getConfig('SERVER_URL');
1753 // Is this URL valid?
1754 if (substr($script, 0, 7) == 'http://') {
1755 // Use the hostname from script URL as new hostname
1756 $url = substr($script, 7);
1757 $extract = explode('/', $url);
1759 // Done extracting the URL :)
1762 // Extract host name
1763 $host = str_replace('http://', '', $url);
1764 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1766 // Generate relative URL
1767 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1768 if (substr(strtolower($script), 0, 7) == 'http://') {
1769 // But only if http:// is in front!
1770 $script = substr($script, (strlen($url) + 7));
1771 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1773 $script = substr($script, (strlen($url) + 8));
1776 //* DEBUG: */ print("SCRIPT=" . $script."<br />");
1777 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1783 // Send a GET request
1784 function sendGetRequest ($script) {
1785 // Compile the script name
1786 $script = COMPILE_CODE($script);
1788 // Extract host name from script
1789 $host = extractHostnameFromUrl($script);
1791 // Generate GET request header
1792 $request = "GET /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
1793 $request .= "Host: " . $host . getConfig('HTTP_EOL');
1794 $request .= "Referer: " . getConfig('URL') . "/admin.php" . getConfig('HTTP_EOL');
1795 if (isConfigEntrySet('FULL_VERSION')) {
1796 $request .= "User-Agent: " . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1798 $request .= "User-Agent: " . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1800 $request .= "Content-Type: text/plain" . getConfig('HTTP_EOL');
1801 $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
1802 $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1804 // Send the raw request
1805 $response = sendRawRequest($host, $request);
1807 // Return the result to the caller function
1811 // Send a POST request
1812 function sendPostRequest ($script, $postData) {
1813 // Is postData an array?
1814 if (!is_array($postData)) {
1816 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1817 return array('', '', '');
1820 // Compile the script name
1821 $script = COMPILE_CODE($script);
1823 // Extract host name from script
1824 $host = extractHostnameFromUrl($script);
1826 // Construct request
1827 $data = http_build_query($postData, '','&');
1829 // Generate POST request header
1830 $request = "POST /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
1831 $request .= "Host: " . $host . getConfig('HTTP_EOL');
1832 $request .= "Referer: " . getConfig('URL') . "/admin.php" . getConfig('HTTP_EOL');
1833 $request .= "User-Agent: " . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1834 $request .= "Content-type: application/x-www-form-urlencoded" . getConfig('HTTP_EOL');
1835 $request .= "Content-length: " . strlen($data) . getConfig('HTTP_EOL');
1836 $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
1837 $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1840 // Send the raw request
1841 $response = sendRawRequest($host, $request);
1843 // Return the result to the caller function
1847 // Sends a raw request to another host
1848 function sendRawRequest ($host, $request) {
1849 // Init errno and errdesc with 'all fine' values
1850 $errno = 0; $errdesc = '';
1853 $response = array('', '', '');
1855 // Default is not to use proxy
1858 // Are proxy settins set?
1859 if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
1865 //* DEBUG: */ die("SCRIPT=" . $script."<br />");
1866 if ($useProxy === true) {
1867 // Connect to host through proxy connection
1868 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1870 // Connect to host directly
1871 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1875 if (!is_resource($fp)) {
1881 if ($useProxy === true) {
1882 // Generate CONNECT request header
1883 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1884 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1886 // Use login data to proxy? (username at least!)
1887 if (getConfig('proxy_username') != '') {
1889 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . COMPILE_CODE(getConfig('proxy_password')));
1890 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1893 // Add last new-line
1894 $proxyTunnel .= getConfig('HTTP_EOL');
1895 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1898 fputs($fp, $proxyTunnel);
1902 // No response received
1906 // Read the first line
1907 $resp = trim(fgets($fp, 10240));
1908 $respArray = explode(' ', $resp);
1909 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1910 // Invalid response!
1916 fputs($fp, $request);
1919 while (!feof($fp)) {
1920 $response[] = trim(fgets($fp, 1024));
1926 // Skip first empty lines
1928 foreach ($resp as $idx => $line) {
1930 $line = trim($line);
1932 // Is this line empty?
1935 array_shift($response);
1937 // Abort on first non-empty line
1942 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1944 // Proxy agent found?
1945 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1946 // Proxy header detected, so remove two lines
1947 array_shift($response);
1948 array_shift($response);
1951 // Was the request successfull?
1952 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1953 // Not found / access forbidden
1954 $response = array('', '', '');
1961 // Taken from www.php.net eregi() user comments
1962 function isEmailValid ($email) {
1964 $email = COMPILE_CODE($email);
1966 // Check first part of email address
1967 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1970 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1973 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1975 // Return check result
1976 return preg_match($regex, $email);
1979 // Function taken from user comments on www.php.net / function eregi()
1980 function isUrlValid ($URL, $compile=true) {
1981 // Trim URL a little
1982 $URL = trim(urldecode($URL));
1983 //* DEBUG: */ OUTPUT_HTML($URL."<br />");
1985 // Compile some chars out...
1986 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1987 //* DEBUG: */ OUTPUT_HTML($URL."<br />");
1989 // Check for the extension filter
1990 if (EXT_IS_ACTIVE('filter')) {
1991 // Use the extension's filter set
1992 return FILTER_VALIDATE_URL($URL, false);
1995 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1996 // https:// in front of the URLs
1997 return isUrlValidSimple($URL);
2000 // Generate a list of administrative links to a given userid
2001 function generateMemberAdminActionLinks ($uid, $status = '') {
2002 // Define all main targets
2003 $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2005 // Begin of navigation links
2006 $eval = "\$OUT = \"[ ";
2008 foreach ($TARGETS as $tar) {
2009 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{?URL?}/modules.php?module=admin&what=" . $tar."&uid=" . $uid."\\\" title=\\\"{--ADMIN_LINK_";
2010 //* DEBUG: */ OUTPUT_HTML("*" . $tar.'/' . $status."*<br />");
2011 if (($tar == "lock_user") && ($status == 'LOCKED')) {
2012 // Locked accounts shall be unlocked
2013 $eval .= "UNLOCK_USER";
2015 // All other status is fine
2016 $eval .= strtoupper($tar);
2018 $eval .= "_TITLE--}\\\">{--ADMIN_";
2019 if (($tar == "lock_user") && ($status == 'LOCKED')) {
2020 // Locked accounts shall be unlocked
2021 $eval .= "UNLOCK_USER";
2023 // All other status is fine
2024 $eval .= strtoupper($tar);
2026 $eval .= "--}</a></span> | ";
2029 // Finish navigation link
2030 $eval = substr($eval, 0, -7)."]\";";
2037 // Generate an email link
2038 function generateEmailLink ($email, $table = 'admins') {
2039 // Default email link (INSECURE! Spammer can read this by harvester programs)
2040 $EMAIL = 'mailto:' . $email;
2042 // Check for several extensions
2043 if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
2044 // Create email link for contacting admin in guest area
2045 $EMAIL = generateAdminEmailLink($email);
2046 } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
2047 // Create email link for contacting a member within admin area (or later in other areas, too?)
2048 $EMAIL = generateUserEmailLink($email, 'admin');
2049 } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
2050 // Create email link to contact sponsor within admin area (or like the link above?)
2051 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2054 // Shall I close the link when there is no admin?
2055 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2057 // Return email link
2061 // Generate a hash for extra-security for all passwords
2062 function generateHash ($plainText, $salt = '') {
2063 // Is the required extension 'sql_patches' there and a salt is not given?
2064 if (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('sql_patches'))) && (empty($salt))) {
2065 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2066 return md5($plainText);
2069 // Do we miss an arry element here?
2070 if (!isConfigEntrySet('file_hash')) {
2072 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2075 // When the salt is empty build a new one, else use the first x configured characters as the salt
2077 // Build server string (inc/databases.php is no longer updated with every commit)
2078 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
2081 $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');
2084 $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
2086 // Calculate number for generating the code
2087 $a = time() + getConfig('_ADD') - 1;
2089 // Generate SHA1 sum from modula of number and the prime number
2090 $sha1 = sha1(($a % getConfig('_PRIME')) . $server.getConfig('ENCRYPT_SEPERATOR') . $keys.getConfig('ENCRYPT_SEPERATOR') . $data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR') . $a);
2091 //* DEBUG: */ OUTPUT_HTML("SHA1=" . $sha1." (".strlen($sha1).")<br />");
2092 $sha1 = scrambleString($sha1);
2093 //* DEBUG: */ OUTPUT_HTML("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
2094 //* DEBUG: */ $sha1b = descrambleString($sha1);
2095 //* DEBUG: */ OUTPUT_HTML("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
2097 // Generate the password salt string
2098 $salt = substr($sha1, 0, getConfig('salt_length'));
2099 //* DEBUG: */ OUTPUT_HTML($salt." (".strlen($salt).")<br />");
2102 $salt = substr($salt, 0, getConfig('salt_length'));
2103 //* DEBUG: */ OUTPUT_HTML("GIVEN={$salt}<br />");
2107 return $salt.sha1($salt . $plainText);
2110 // Scramble a string
2111 function scrambleString($str) {
2115 // Final check, in case of failture it will return unscrambled string
2116 if (strlen($str) > 40) {
2117 // The string is to long
2119 } elseif (strlen($str) == 40) {
2121 $scrambleNums = explode(':', getConfig('pass_scramble'));
2123 // Generate new numbers
2124 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2127 // Scramble string here
2128 //* DEBUG: */ OUTPUT_HTML("***Original=" . $str."***<br />");
2129 for ($idx = 0; $idx < strlen($str); $idx++) {
2130 // Get char on scrambled position
2131 $char = substr($str, $scrambleNums[$idx], 1);
2133 // Add it to final output string
2134 $scrambled .= $char;
2137 // Return scrambled string
2138 //* DEBUG: */ OUTPUT_HTML("***Scrambled=" . $scrambled."***<br />");
2142 // De-scramble a string scrambled by scrambleString()
2143 function descrambleString($str) {
2144 // Scramble only 40 chars long strings
2145 if (strlen($str) != 40) return $str;
2147 // Load numbers from config
2148 $scrambleNums = explode(':', getConfig('pass_scramble'));
2151 if (count($scrambleNums) != 40) return $str;
2153 // Begin descrambling
2154 $orig = str_repeat(' ', 40);
2155 //* DEBUG: */ OUTPUT_HTML("+++Scrambled=" . $str."+++<br />");
2156 for ($idx = 0; $idx < 40; $idx++) {
2157 $char = substr($str, $idx, 1);
2158 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2161 // Return scrambled string
2162 //* DEBUG: */ OUTPUT_HTML("+++Original=" . $orig."+++<br />");
2166 // Generated a "string" for scrambling
2167 function genScrambleString ($len) {
2168 // Prepare array for the numbers
2169 $scrambleNumbers = array();
2171 // First we need to setup randomized numbers from 0 to 31
2172 for ($idx = 0; $idx < $len; $idx++) {
2174 $rand = mt_rand(0, ($len -1));
2176 // Check for it by creating more numbers
2177 while (array_key_exists($rand, $scrambleNumbers)) {
2178 $rand = mt_rand(0, ($len -1));
2182 $scrambleNumbers[$rand] = $rand;
2185 // So let's create the string for storing it in database
2186 $scrambleString = implode(':', $scrambleNumbers);
2187 return $scrambleString;
2190 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2191 function generatePassString ($passHash) {
2192 // Return vanilla password hash
2195 // Is a secret key and master salt already initialized?
2196 if ((getConfig('secret_key') != '') && (getConfig('master_salt') != '')) {
2197 // Only calculate when the secret key is generated
2198 $newHash = ''; $start = 9;
2199 for ($idx = 0; $idx < 10; $idx++) {
2200 $part1 = hexdec(substr($passHash, $start, 4));
2201 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2202 $mod = dechex($idx);
2203 if ($part1 > $part2) {
2204 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2205 } elseif ($part2 > $part1) {
2206 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2208 $mod = substr(round($mod), 0, 4);
2209 $mod = str_repeat('0', 4-strlen($mod)) . $mod;
2210 //* DEBUG: */ OUTPUT_HTML("*" . $start.'=' . $mod."*<br />");
2215 //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
2216 $ret = generateHash($newHash, getConfig('master_salt'));
2217 //* DEBUG: */ print($ret."<br />");
2220 //* DEBUG: */ OUTPUT_HTML("--" . $passHash."--<br />");
2221 $ret = md5($passHash);
2222 //* DEBUG: */ OUTPUT_HTML("++" . $ret."++<br />");
2229 // Fix "deleted" cookies
2230 function fixDeletedCookies ($cookies) {
2231 // Is this an array with entries?
2232 if ((is_array($cookies)) && (count($cookies) > 0)) {
2233 // Then check all cookies if they are marked as deleted!
2234 foreach ($cookies as $cookieName) {
2235 // Is the cookie set to "deleted"?
2236 if (getSession($cookieName) == 'deleted') {
2237 setSession($cookieName, '');
2243 // Output error messages in a fasioned way and die...
2244 function app_die ($F, $L, $message) {
2245 // Check if Script is already dieing and not let it kill itself another 1000 times
2246 if (!isset($GLOBALS['app_died'])) {
2247 // Make sure, that the script realy realy diese here and now
2248 $GLOBALS['app_died'] = true;
2251 loadIncludeOnce('inc/header.php');
2253 // Rewrite message for output
2254 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2256 // Better log this message away
2257 DEBUG_LOG($F, $L, $message);
2259 // Load the message template
2260 LOAD_TEMPLATE('admin_settings_saved', false, $message);
2263 loadIncludeOnce('inc/footer.php');
2265 // Script tried to kill itself twice
2266 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2270 // Display parsing time and number of SQL queries in footer
2271 function displayParsingTime() {
2272 // Is the timer started?
2273 if (!isset($GLOBALS['startTime'])) {
2279 $endTime = microtime(true);
2281 // "Explode" both times
2282 $start = explode(' ', $GLOBALS['startTime']);
2283 $end = explode(' ', $endTime);
2284 $runTime = $end[0] - $start[0];
2285 if ($runTime < 0) $runTime = 0;
2286 $runTime = translateComma($runTime);
2290 'runtime' => $runTime,
2291 'numSQLs' => (getConfig('sql_count') + 1),
2292 'numTemplates' => (getConfig('num_templates') + 1)
2295 // Load the template
2296 LOAD_TEMPLATE('show_timings', false, $content);
2299 // Check wether a boolean constant is set
2300 // Taken from user comments in PHP documentation for function constant()
2301 function isBooleanConstantAndTrue ($constName) { // : Boolean
2302 // Failed by default
2306 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2308 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2309 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2312 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2313 if (defined($constName)) {
2315 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2316 $res = (constant($constName) === true);
2320 $GLOBALS['cache_array']['const'][$constName] = $res;
2322 //* DEBUG: */ var_dump($res);
2328 // Checks if a given apache module is loaded
2329 function isApacheModuleLoaded ($apacheModule) {
2330 // Check it and return result
2331 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2334 // Get current theme name
2335 function getCurrentTheme() {
2336 // The default theme is 'default'... ;-)
2339 // Load default theme if not empty from configuration
2340 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2342 if (!isSessionVariableSet('mxchange_theme')) {
2343 // Set default theme
2344 setSession('mxchange_theme', $ret);
2345 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
2346 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2347 // Get theme from cookie
2348 $ret = getSession('mxchange_theme');
2351 if (getThemeId($ret) == 0) {
2352 // Fix it to default
2355 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
2356 // Prepare FQFN for checking
2357 $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), REQUEST_GET('theme'));
2359 // Installation mode active
2360 if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
2361 // Set cookie from URL data
2362 setSession('mxchange_theme', REQUEST_GET('theme'));
2363 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2364 // Set cookie from posted data
2365 setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2369 $ret = getSession('mxchange_theme');
2371 // Invalid design, reset cookie
2372 setSession('mxchange_theme', $ret);
2375 // Add (maybe) found theme.php file to inclusion list
2376 $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2378 // Try to load the requested include file
2379 if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
2381 // Return theme value
2385 // Get id from theme
2386 function getThemeId ($name) {
2387 // Is the extension 'theme' installed?
2388 if (!EXT_IS_ACTIVE('theme')) {
2396 // Is the cache entry there?
2397 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2398 // Get the version from cache
2399 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2402 incrementConfigEntry('cache_hits');
2403 } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
2404 // Check if current theme is already imported or not
2405 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2406 array($name), __FUNCTION__, __LINE__);
2409 if (SQL_NUMROWS($result) == 1) {
2411 list($id) = SQL_FETCHROW($result);
2415 SQL_FREERESULT($result);
2422 // Generates an error code from given account status
2423 function generateErrorCodeFromUserStatus ($status) {
2424 // @TODO The status should never be empty
2425 if (empty($status)) {
2426 // Something really bad happend here
2427 debug_report_bug(__FUNCTION__ . ': status is empty.');
2430 // Default error code if unknown account status
2431 $errorCode = getCode('UNKNOWN_STATUS');
2433 // Generate constant name
2434 $constantName = sprintf("ID_%s", $status);
2436 // Is the constant there?
2437 if (isCodeSet($constantName)) {
2439 $errorCode = getCode($constantName);
2442 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2445 // Return error code
2449 // Function to search for the last modifified file
2450 function searchDirsRecursive ($dir, &$last_changed) {
2452 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />");
2453 // Does it match what we are looking for? (We skip a lot files already!)
2454 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2455 $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2456 $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2457 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />");
2459 // Walk through all entries
2460 foreach ($ds as $d) {
2461 // Generate proper FQFN
2462 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2464 // Is it a file and readable?
2465 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2466 if (isDirectory($FQFN)) {
2467 // $FQFN is a directory so also crawl into this directory
2469 if (!empty($dir)) $newDir = $dir . '/'. $d;
2470 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />");
2471 searchDirsRecursive($newDir, $last_changed);
2472 } elseif (isFileReadable($FQFN)) {
2473 // $FQFN is a filename and no directory
2474 $time = filemtime($FQFN);
2475 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2476 if ($last_changed['time'] < $time) {
2477 // This file is newer as the file before
2478 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2479 $last_changed['path_name'] = $FQFN;
2480 $last_changed['time'] = $time;
2486 // "Getter" for revision/version data
2487 function getActualVersion ($type = 'Revision') {
2488 // By default nothing is new... ;-)
2491 if (EXT_IS_ACTIVE('cache')) {
2492 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2493 if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') {
2494 // Force rebuild by URL parameter
2497 !isset($GLOBALS['cache_array']['revision'][$type])
2499 count($GLOBALS['cache_array']['revision']) < 3
2501 !$GLOBALS['cache_instance']->loadCacheFile('revision')
2507 // Is the cache file outdated/invalid?
2508 if ($new === true) {
2509 // Reload the cache file
2510 $GLOBALS['cache_instance']->loadCacheFile('revision');
2512 // Destroy cache file
2513 $GLOBALS['cache_instance']->destroyCacheFile(false, true);
2515 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2516 unset($GLOBALS['cache_array']['revision']);
2518 // Reload load_cach-revison.php
2519 loadInclude('inc/loader/load_cache-revision.php');
2525 // Return found value
2526 return $GLOBALS['cache_array']['revision'][$type][0];
2528 // Old Version without ext-cache active (deprecated ?)
2530 // FQFN of revision file
2531 $FQFN = sprintf("%sinc/cache/.revision", getConfig('PATH'));
2533 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2534 if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
2535 // Forced rebuild of .revision file
2538 // Check for revision file
2539 if (!isFileReadable($FQFN)) {
2540 // Not found, so we need to create it
2543 // Revision file found
2544 $ins_vers = explode("\n", readFromFile($FQFN));
2546 // Get array for mapping information
2547 $mapper = array_flip(getSearchFor());
2548 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2550 // Is the content valid?
2551 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
2552 // File needs update!
2555 // Return found value
2556 return trim($ins_vers[$mapper[$type]]);
2561 // Has it been updated?
2562 if ($new === true) {
2563 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2568 // Repares an array we are looking for
2569 // The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
2570 function getSearchFor () {
2571 // Add Revision, Date, Tag and Author
2572 $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2574 // Return the created array
2578 // @TODO Please describe this function
2579 function getArrayFromActualVersion () {
2583 // Directory to start with search
2584 $last_changed = array(
2589 // Init return array
2590 $akt_vers = array();
2592 // Init value for counting the founded keywords
2595 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2596 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2599 $last_file = readFromFile($last_changed['path_name']);
2601 // Get all the keywords to search for
2602 $searchFor = getSearchFor();
2604 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2605 foreach ($searchFor as $search) {
2606 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2607 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2608 // This trimms the search-result and puts it in the $akt_vers-return array
2609 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2612 // Save the last-changed filename for debugging
2613 $akt_vers['File'] = $last_changed['path_name'];
2615 // at least 3 keyword-Tags are needed for propper values
2616 if ($res && $res >= 3
2617 && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
2618 && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
2619 && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
2620 // Prepare content witch need special treadment
2622 // Prepare timestamp for date
2623 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2624 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2626 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2627 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2628 $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2632 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2633 $version = sendGetRequest('check-updates3.php');
2636 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2637 if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
2638 if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
2639 if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
2640 if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
2643 // Return prepared array
2647 // Back-ported from the new ship-simu engine. :-)
2648 function debug_get_printable_backtrace () {
2650 $backtrace = "<ol>\n";
2652 // Get and prepare backtrace for output
2653 $backtraceArray = debug_backtrace();
2654 foreach ($backtraceArray as $key => $trace) {
2655 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2656 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2657 if (!isset($trace['args'])) $trace['args'] = array();
2658 $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";
2662 $backtrace .= "</ol>\n";
2664 // Return the backtrace
2668 // Output a debug backtrace to the user
2669 function debug_report_bug ($message = '') {
2672 // Is the optional message set?
2673 if (!empty($message)) {
2675 $debug = sprintf("Note: %s<br />\n",
2679 // @TODO Add a little more infos here
2680 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2684 $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a> and include the logfile from <strong>inc/cache/debug.log</strong> in your report (you can now attach files):<pre>";
2685 $debug .= debug_get_printable_backtrace();
2686 $debug .= "</pre>\nRequest-URI: " . $_SERVER['REQUEST_URI']."<br />\n";
2687 $debug .= "Thank you for finding bugs.";
2690 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2694 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2695 function generateSeed () {
2696 list($usec, $sec) = explode(' ', microtime());
2697 $microTime = (((float)$sec + (float)$usec)) * 100000;
2701 // Converts a message code to a human-readable message
2702 function convertCodeToMessage ($code) {
2705 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2706 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2707 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2708 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2709 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2710 case getCode('USER_404') : $message = getMessage('USER_NOT_FOUND'); break;
2711 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2712 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2714 case getCode('ERROR_MAILID'):
2715 if (EXT_IS_ACTIVE($ext, true)) {
2716 $message = getMessage('ERROR_CONFIRMING_MAIL');
2718 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2722 case getCode('EXTENSION_PROBLEM'):
2723 if (REQUEST_ISSET_GET('ext')) {
2724 $message = generateExtensionInactiveNotInstalledMessage(REQUEST_GET('ext'));
2726 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2730 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2731 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2732 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2733 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2736 // Missing/invalid code
2737 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2740 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2744 // Return the message
2748 // Generate a "link" for the given admin id (aid)
2749 function generateAdminLink ($aid) {
2750 // No assigned admin is default
2751 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2753 // Zero? = Not assigned
2754 if (bigintval($aid) > 0) {
2755 // Load admin's login
2756 $login = getAdminLogin($aid);
2758 // Is the login valid?
2759 if ($login != '***') {
2760 // Is the extension there?
2761 if (EXT_IS_ACTIVE('admins')) {
2763 $admin = "<a href=\"".generateEmailLink(getAdminEmail($aid), 'admins')."\">" . $login."</a>";
2765 // Extension not found
2766 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2770 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2778 // Compile characters which are allowed in URLs
2779 function compileUriCode ($code, $simple = true) {
2780 // Compile constants
2781 if (!$simple) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2783 // Compile QUOT and other non-HTML codes
2784 $code = str_replace('{DOT}', '.',
2785 str_replace('{SLASH}', '/',
2786 str_replace('{QUOT}', "'",
2787 str_replace('{DOLLAR}', '$',
2788 str_replace('{OPEN_ANCHOR}', '(',
2789 str_replace('{CLOSE_ANCHOR}', ')',
2790 str_replace('{OPEN_SQR}', '[',
2791 str_replace('{CLOSE_SQR}', ']',
2792 str_replace('{PER}', '%',
2796 // Return compiled code
2800 // Function taken from user comments on www.php.net / function eregi()
2801 function isUrlValidSimple ($url) {
2803 $url = strip_tags(str_replace("\\", '', COMPILE_CODE(urldecode($url))));
2805 // Allows http and https
2806 $http = "(http|https)+(:\/\/)";
2808 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2809 // Test double-domains (e.g. .de.vu)
2810 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2812 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2814 $dir = "((/)+([-_\.[:alnum:]])+)*";
2816 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2817 // ... and the string after and including question character
2818 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2819 // Pattern for URLs like http://url/dir/doc.html?var=value
2820 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2821 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2822 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2823 // Pattern for URLs like http://url/dir/?var=value
2824 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2825 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2826 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2827 // Pattern for URLs like http://url/dir/page.ext
2828 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2829 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2830 $pattern['ipdp'] = $http . $ip . $dir . $page;
2831 // Pattern for URLs like http://url/dir
2832 $pattern['d1d'] = $http . $domain1 . $dir;
2833 $pattern['d2d'] = $http . $domain2 . $dir;
2834 $pattern['ipd'] = $http . $ip . $dir;
2835 // Pattern for URLs like http://url/?var=value
2836 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2837 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2838 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2839 // Pattern for URLs like http://url?var=value
2840 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2841 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2842 $pattern['ipg12'] = $http . $ip . $getstring1;
2843 // Test all patterns
2845 foreach ($pattern as $key => $pat) {
2847 if (isDebugRegExpressionEnabled()) {
2848 // @TODO Are these convertions still required?
2849 $pat = str_replace('.', "\.", $pat);
2850 $pat = str_replace('@', "\@", $pat);
2851 //* DEBUG: */ OUTPUT_HTML($key."= " . $pat . "<br />");
2854 // Check if expression matches
2855 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2858 if ($reg === true) break;
2861 // Return true/false
2865 // Wtites data to a config.php-style file
2866 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2867 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2868 // Initialize some variables
2874 // Is the file there and read-/write-able?
2875 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2876 $search = 'CFG: ' . $comment;
2877 $tmp = $FQFN . '.tmp';
2879 // Open the source file
2880 $fp = fopen($FQFN, 'r') or OUTPUT_HTML('<strong>READ:</strong> ' . $FQFN . '<br />');
2882 // Is the resource valid?
2883 if (is_resource($fp)) {
2884 // Open temporary file
2885 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('<strong>WRITE:</strong> ' . $tmp . '<br />');
2887 // Is the resource again valid?
2888 if (is_resource($fp_tmp)) {
2889 while (!feof($fp)) {
2890 // Read from source file
2891 $line = fgets ($fp, 1024);
2893 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2896 if ($next === $seek) {
2898 $line = $prefix . $DATA . $suffix . "\n";
2904 // Write to temp file
2905 fputs($fp_tmp, $line);
2911 // Finished writing tmp file
2915 // Close source file
2918 if (($done === true) && ($found === true)) {
2919 // Copy back tmp file and delete tmp :-)
2920 copyFileVerified($tmp, $FQFN, 0644);
2921 return removeFile($tmp);
2922 } elseif ($found === false) {
2923 OUTPUT_HTML('<strong>CHANGE:</strong> 404!');
2925 OUTPUT_HTML('<strong>TMP:</strong> UNDONE!');
2929 // File not found, not readable or writeable
2930 OUTPUT_HTML('<strong>404:</strong> ' . $FQFN . '<br />');
2933 // An error was detected!
2936 // Send notification to admin
2937 function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
2938 if (GET_EXT_VERSION('admins') >= '0.4.1') {
2940 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2942 // Send out out-dated way
2943 $message = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2944 SEND_ADMIN_EMAILS($subject, $message);
2948 // Debug message logger
2949 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
2950 // Is debug mode enabled?
2951 if ((isDebugModeEnabled()) || ($force === true)) {
2953 $message = str_replace("\r", '', str_replace("\n", '', $message));
2955 // Log this message away, we better don't call app_die() here to prevent an endless loop
2956 $fp = fopen(getConfig('PATH') . 'inc/cache/debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2957 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule() . '|' . basename($funcFile) . '|' . $line . '|' . strip_tags($message) . "\n");
2962 // Load more reset scripts
2963 function runResetIncludes () {
2964 // Is the reset set or old sql_patches?
2965 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
2967 DEBUG_LOG(__FUNCTION__, __LINE__, 'Cannot run reset! Please report this bug. Thanks');
2970 // Get more daily reset scripts
2971 SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
2974 if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
2976 // Is the config entry set?
2977 if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
2978 // Create current week mark
2979 $currWeek = date('W', time());
2982 if (getConfig('last_week') != $currWeek) {
2983 // Include weekly reset scripts
2984 MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
2987 if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
2990 // Create current month mark
2991 $currMonth = date('m', time());
2994 if (getConfig('last_month') != $currMonth) {
2995 // Include monthly reset scripts
2996 MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
2999 if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
3004 runFilterChain('load_includes');
3007 // Handle extra values
3008 function handleExtraValues ($filterFunction, $value, $extraValue) {
3009 // Default is the value itself
3012 // Do we have a special filter function?
3013 if (!empty($filterFunction)) {
3014 // Does the filter function exist?
3015 if (function_exists($filterFunction)) {
3016 // Do we have extra parameters here?
3017 if (!empty($extraValue)) {
3018 // Put both parameters in one new array by default
3019 $args = array($value, $extraValue);
3021 // If we have an array simply use it and pre-extend it with our value
3022 if (is_array($extraValue)) {
3023 // Make the new args array
3024 $args = merge_array(array($value), $extraValue);
3027 // Call the multi-parameter call-back
3028 $ret = call_user_func_array($filterFunction, $args);
3030 // One parameter call
3031 $ret = call_user_func($filterFunction, $value);
3040 // Converts timestamp selections into a timestamp
3041 function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
3042 // Init test variable
3045 // Get last three chars
3046 $test = substr($id, -3);
3048 // Improved way of checking! :-)
3049 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3050 // Found a multi-selection for timings?
3051 $test = substr($id, 0, -3);
3052 if ((isset($POST[$test.'_ye'])) && (isset($POST[$test.'_mo'])) && (isset($POST[$test.'_we'])) && (isset($POST[$test.'_da'])) && (isset($POST[$test.'_ho'])) && (isset($POST[$test.'_mi'])) && (isset($POST[$test.'_se'])) && ($test != $test2)) {
3053 // Generate timestamp
3054 $POST[$test] = createTimestampFromSelections($test, $POST);
3055 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3057 // Remove data from array
3058 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3059 unset($POST[$test.'_' . $rem]);
3063 unset($id); $skip = true; $test2 = $test;
3066 // Process this entry
3072 // Reverts the german decimal comma into Computer decimal dot
3073 function convertCommaToDot ($str) {
3074 // Default float is not a float... ;-)
3077 // Which language is selected?
3078 switch (getLanguage()) {
3079 case 'de': // German language
3080 // Remove german thousand dots first
3081 $str = str_replace('.', '', $str);
3083 // Replace german commata with decimal dot and cast it
3084 $float = (float)str_replace(',', '.', $str);
3087 default: // US and so on
3088 // Remove thousand dots first and cast
3089 $float = (float)str_replace(',', '', $str);
3097 // Handle menu-depending failed logins and return the rendered content
3098 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3099 // Default output is empty ;-)
3102 // Is the session data set?
3103 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3104 // Ignore zero values
3105 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3106 // Non-guest has login failures found, get both data and prepare it for template
3107 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
3109 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3110 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), '2')
3114 $OUT = LOAD_TEMPLATE('login_failures', true, $content);
3117 // Reset session data
3118 setSession('mxchange_' . $accessLevel.'_failures', '');
3119 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3122 // Return rendered content
3127 function rebuildCacheFiles ($cache, $inc = '') {
3128 // Shall I remove the cache file?
3129 if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
3131 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3133 $GLOBALS['cache_instance']->destroyCacheFile();
3136 // Include file given?
3139 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3141 // Is the include there?
3142 if (isIncludeReadable($INC)) {
3143 // And rebuild it from scratch
3144 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3147 // Include not found!
3148 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3154 // Purge admin menu cache
3155 function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
3156 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3157 if (!EXT_IS_ACTIVE('cache')) {
3158 // Cache extension not active
3160 } elseif (!isCacheInstanceValid()) {
3161 // No cache instance!
3162 DEBUG_LOG(__FUNCTION__, __LINE__, 'No cache instance found.');
3164 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
3165 // Caching disabled (currently experiemental!)
3169 // Experiemental feature!
3170 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3173 // Determines the real remote address
3174 function determineRealRemoteAddress () {
3175 // Is a proxy in use?
3176 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
3178 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3179 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
3180 // Yet, another proxy
3181 $address = $_SERVER['HTTP_CLIENT_IP'];
3183 // The regular address when no proxy was used
3184 $address = $_SERVER['REMOTE_ADDR'];
3187 // This strips out the real address from proxy output
3188 if (strstr($address, ',')){
3189 $addressArray = explode(',', $address);
3190 $address = $addressArray[0];
3193 // Return the result
3197 // Adds a bonus mail to the queue
3198 // This is a high-level function!
3199 function addNewBonusMail ($data, $mode = '', $output=true) {
3200 // Use mode from data if not set and availble ;-)
3201 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3203 // Generate receiver list
3204 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3207 if (!empty($RECEIVER)) {
3208 // Add bonus mail to queue
3209 addBonusMailToQueue(
3221 // Mail inserted into bonus pool
3222 if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3223 } elseif ($output) {
3224 // More entered than can be reached!
3225 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3228 DEBUG_LOG(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3232 // Determines referal id and sets it
3233 function DETERMINE_REFID () {
3234 // Check if refid is set
3235 if ((REQUEST_ISSET_GET('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3236 // The variable user comes from the click-counter script click.php and we only accept this here
3237 $GLOBALS['refid'] = bigintval(REQUEST_GET('user'));
3238 } elseif (REQUEST_ISSET_POST('refid')) {
3239 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3240 $GLOBALS['refid'] = strip_tags(REQUEST_POST('refid'));
3241 } elseif (REQUEST_ISSET_GET('refid')) {
3242 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3243 $GLOBALS['refid'] = strip_tags(REQUEST_GET('refid'));
3244 } elseif (REQUEST_ISSET_GET('ref')) {
3245 // Set refid=ref (the referal link uses such variable)
3246 $GLOBALS['refid'] = strip_tags(REQUEST_GET('ref'));
3247 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3248 // Set session refid als global
3249 $GLOBALS['refid'] = bigintval(getSession('refid'));
3250 } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
3251 // Select a random user which has confirmed enougth mails
3252 $GLOBALS['refid'] = determineRandomReferalId();
3253 } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
3254 // Set default refid as refid in URL
3255 $GLOBALS['refid'] = getConfig('def_refid');
3257 // No default ID when sql_patches is not installed or none set
3258 $GLOBALS['refid'] = 0;
3261 // Set cookie when default refid > 0
3262 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3264 setSession('refid', $GLOBALS['refid']);
3267 // Return determined refid
3268 return $GLOBALS['refid'];
3271 // Enables the reset mode. Only call this function if you really want the
3273 function enableResetMode () {
3274 // Enable the reset mode
3275 $GLOBALS['reset_enabled'] = true;
3278 runFilterChain('reset_enabled');
3281 // Our shutdown-function
3282 function shutdown () {
3283 // Call the filter chain 'shutdown'
3284 runFilterChain('shutdown', null, false);
3286 if (SQL_IS_LINK_UP()) {
3288 SQL_CLOSE(__FILE__, __LINE__);
3289 } elseif ((!isInstalling()) && (isInstalled())) {
3291 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3294 // Stop executing here
3298 // Setter for userid
3299 function setUserId ($userid) {
3300 $GLOBALS['userid'] = bigintval($userid);
3303 // Getter for userid or returns zero
3304 function getUserId () {
3308 // Is the userid set?
3309 if (isUserIdSet()) {
3311 $userid = $GLOBALS['userid'];
3318 // Checks ether the userid is set
3319 function isUserIdSet () {
3320 return (isset($GLOBALS['userid']));
3323 // Handle message codes from URL
3324 function handleCodeMessage () {
3325 if (REQUEST_ISSET_GET('msg')) {
3326 // Default extension is 'unknown'
3329 // Is extension given?
3330 if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
3332 // Convert the 'msg' parameter from URL to a human-readable message
3333 $message = convertCodeToMessage(REQUEST_GET('msg'));
3335 // Load message template
3336 LOAD_TEMPLATE('message', false, $message);
3340 // Setter for extra title
3341 function setExtraTitle ($extraTitle) {
3342 $GLOBALS['extra_title'] = $extraTitle;
3345 // Getter for extra title
3346 function getExtraTitle () {
3347 // Is the extra title set?
3348 if (!isExtraTitleSet()) {
3349 // No, then abort here
3350 debug_report_bug('extra_title is not set!');
3354 return $GLOBALS['extra_title'];
3357 // Checks if the extra title is set
3358 function isExtraTitleSet () {
3359 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3362 // Generates a 'extension foo inactive' message
3363 function generateExtensionInactiveMessage ($ext_name) {
3364 // Is the extension empty?
3365 if (empty($ext_name)) {
3366 // This should not happen
3367 trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3371 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3373 // Is an admin logged in?
3375 // Then output admin message
3376 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3379 // Return prepared message
3383 // Generates a 'extension foo not installed' message
3384 function generateExtensionNotInstalledMessage ($ext_name) {
3385 // Is the extension empty?
3386 if (empty($ext_name)) {
3387 // This should not happen
3388 trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3392 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3394 // Is an admin logged in?
3396 // Then output admin message
3397 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3400 // Return prepared message
3404 // Generates a message depending on if the extension is not installed or not
3406 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3410 // Is the extension not installed or just deactivated?
3411 switch (isExtensionInstalled($ext_name)) {
3412 case true; // Deactivated!
3413 $message = generateExtensionInactiveMessage($ext_name);
3416 case false; // Not installed!
3417 $message = generateExtensionNotInstalledMessage($ext_name);
3420 default: // Should not happen!
3421 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3422 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3426 // Return the message
3430 // Reads a directory recursively by default and searches for files not matching
3431 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3432 // a whole directory.
3433 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
3434 // Add default entries we should exclude
3435 $excludeArray[] = '.';
3436 $excludeArray[] = '..';
3437 $excludeArray[] = '.svn';
3438 $excludeArray[] = '.htaccess';
3440 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3445 $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3448 while ($baseFile = readdir($dirPointer)) {
3449 // Exclude '.', '..' and entries in $excludeArray automatically
3450 if (in_array($baseFile, $excludeArray, true)) {
3452 //* DEBUG: */ OUTPUT_HTML('excluded=' . $baseFile . "<br />");
3456 // Construct include filename and FQFN
3457 $fileName = $baseDir . '/' . $baseFile;
3458 $FQFN = getConfig('PATH') . $fileName;
3460 // Remove double slashes
3461 $FQFN = str_replace('//', '/', $FQFN);
3463 // Check if the base filename matches an exclusion pattern and if the pattern is not empty
3464 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3465 // These Lines are only for debugging!!
3466 //* DEBUG: */ OUTPUT_HTML('baseDir:' . $baseDir . "<br />");
3467 //* DEBUG: */ OUTPUT_HTML('baseFile:' . $baseFile . "<br />");
3468 //* DEBUG: */ OUTPUT_HTML('FQFN:' . $FQFN . "<br />");
3474 // Skip also files with non-matching prefix genericly
3475 if (($recursive === true) && (isDirectory($FQFN))) {
3476 // Is a redirectory so read it as well
3477 $files = merge_array($files, getArrayFromDirectory ($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3479 // And skip further processing
3481 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3483 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3485 } elseif (!isFileReadable($FQFN)) {
3486 // Not readable so skip it
3487 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3491 // Is the file a PHP script or other?
3492 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3493 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3494 // Is this a valid include file?
3495 if ($extension == '.php') {
3496 // Remove both for extension name
3497 $extName = substr($baseFile, strlen($prefix), -4);
3500 $extId = GET_EXT_ID($extName);
3502 // Is the extension valid and active?
3503 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
3504 // Then add this file
3505 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3506 $files[] = $fileName;
3507 } elseif ($extId == 0) {
3508 // Add non-extension files as well
3509 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3510 if ($addBaseDir === true) {
3511 $files[] = $fileName;
3513 $files[] = $baseFile;
3517 // We found .php file but should not search for them, why?
3518 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3521 // Other, generic file found
3522 $files[] = $fileName;
3527 closedir($dirPointer);
3532 // Return array with include files
3533 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, '- Left!');
3537 //////////////////////////////////////////////////
3538 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3539 //////////////////////////////////////////////////
3541 if (!function_exists('html_entity_decode')) {
3542 // Taken from documentation on www.php.net
3543 function html_entity_decode ($string) {
3544 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3545 $trans_tbl = array_flip($trans_tbl);
3546 return strtr($string, $trans_tbl);