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
49 // Do we have HTML-Code here?
51 // Yes, so we handle it as you have configured
52 switch (getConfig('OUTPUT_MODE'))
55 // That's why you don't need any \n at the end of your HTML code... :-)
56 if (constant('_OB_CACHING') == 'on') {
57 // Output into PHP's internal buffer
60 // That's why you don't need any \n at the end of your HTML code... :-)
61 if ($newLine) echo "\n";
63 // Render mode for old or lame servers...
66 // That's why you don't need any \n at the end of your HTML code... :-)
67 if ($newLine) $OUTPUT .= "\n";
72 // If we are switching from render to direct output rendered code
73 if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != 'on')) { outputRawCode($OUTPUT); $OUTPUT = ''; }
75 // The same as above... ^
77 if ($newLine) echo "\n";
81 // Huh, something goes wrong or maybe you have edited config.php ???
82 app_die(__FUNCTION__, __LINE__, "<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
85 } elseif ((constant('_OB_CACHING') == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
86 // Headers already sent?
89 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
91 // Trigger an user error
92 debug_report_bug("Headers are already sent!");
95 // Output cached HTML code
96 $OUTPUT = ob_get_contents();
98 // Clear output buffer for later output if output is found
99 if (!empty($OUTPUT)) {
104 sendHeader('HTTP/1.1 200');
107 $now = gmdate('D, d M Y H:i:s') . ' GMT';
109 // General headers for no caching
110 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
111 sendHeader('Last-Modified: ' . $now);
112 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
113 sendHeader('Pragma: no-cache'); // HTTP/1.0
114 sendHeader('Connection: Close');
116 // Extension 'rewrite' installed?
117 if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
118 $OUTPUT = rewriteLinksInCode($OUTPUT);
121 // Compile and run finished rendered HTML code
122 while (strpos($OUTPUT, '{!') > 0) {
123 // Replace _MYSQL_PREFIX
124 $OUTPUT = str_replace("{!_MYSQL_PREFIX!}", getConfig('_MYSQL_PREFIX'), $OUTPUT);
126 // Prepare the content and eval() it...
128 $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
131 // Was that eval okay?
132 if (empty($newContent)) {
133 // Something went wrong!
134 app_die(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . htmlentities($eval) . '</pre>');
136 $OUTPUT = $newContent;
139 // Output code here, DO NOT REMOVE! ;-)
140 outputRawCode($OUTPUT);
141 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($OUTPUT))) {
142 // Rewrite links when rewrite extension is active
143 if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
144 $OUTPUT = rewriteLinksInCode($OUTPUT);
147 // Compile and run finished rendered HTML code
148 while (strpos($OUTPUT, '{!') > 0) {
149 $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
153 // Output code here, DO NOT REMOVE! ;-)
154 outputRawCode($OUTPUT);
158 // Output the raw HTML code
159 function outputRawCode ($HTML) {
160 // Output stripped HTML code to avoid broken JavaScript code, etc.
161 echo stripslashes(stripslashes($HTML));
163 // Flush the output if only constant('_OB_CACHING') is not 'on'
164 if (constant('_OB_CACHING') != 'on') {
170 // Init fatal message array
171 function initFatalMessages () {
172 $GLOBALS['fatal_messages'] = array();
175 // Getter for whole fatal error messages
176 function getFatalArray () {
177 return $GLOBALS['fatal_messages'];
180 // Add a fatal error message to the queue array
181 function addFatalMessage ($F, $L, $message, $extra='') {
182 if (is_array($extra)) {
183 // Multiple extras for a message with masks
184 $message = call_user_func_array('sprintf', $extra);
185 } elseif (!empty($extra)) {
186 // $message is text with a mask plus extras to insert into the text
187 $message = sprintf($message, $extra);
190 // Add message to $GLOBALS['fatal_messages']
191 $GLOBALS['fatal_messages'][] = $message;
193 // Log fatal messages away
194 DEBUG_LOG($F, $L, " message={$message}");
197 // Getter for total fatal message count
198 function getTotalFatalErrors () {
202 // Do we have at least the first entry?
203 if (!empty($GLOBALS['fatal_messages'][0])) {
205 $count = count($GLOBALS['fatal_messages']);
212 // Load a template file and return it's content (only it's name; do not use ' or ")
213 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
214 // @TODO Remove this sanity-check if all is fine
215 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
217 // Add more variables which you want to use in your template files
218 global $DATA, $username;
220 // Get whole config array
221 $_CONFIG = getConfigArray();
223 // Make all template names lowercase
224 $template = strtolower($template);
226 // Count the template load
227 incrementConfigEntry('num_templates');
229 // Prepare IP number and User Agent
230 $REMOTE_ADDR = detectRemoteAddr();
231 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
232 $HTTP_USER_AGENT = detectUserAgent();
236 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
238 // @DEPRECATED Try to rewrite the if() condition
239 if ($template == 'member_support_form') {
240 // Support request of a member
241 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
242 array(getUserId()), __FUNCTION__, __LINE__);
244 // Is content an array?
245 if (is_array($content)) {
247 $content = merge_array($content, SQL_FETCHARRAY($result));
250 $content['gender'] = translateGender($content['gender']);
253 // @TODO Fine all templates which are using these direct variables and rewrite them.
254 // @TODO After this step is done, this else-block is history
255 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
258 $gender = translateGender($gender);
259 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
263 SQL_FREERESULT($result);
266 // Generate date/time string
267 $date_time = generateDateTime(time(), '1');
270 $basePath = sprintf("%stemplates/%s/html/", constant('PATH'), getLanguage());
273 // Check for admin/guest/member templates
274 if (strpos($template, 'admin_') > -1) {
275 // Admin template found
277 } elseif (strpos($template, 'guest_') > -1) {
278 // Guest template found
280 } elseif (strpos($template, 'member_') > -1) {
281 // Member template found
283 } elseif (strpos($template, 'install_') > -1) {
284 // Installation template found
286 } elseif (strpos($template, 'ext_') > -1) {
287 // Extension template found
289 } elseif (strpos($template, 'la_') > -1) {
290 // 'Logical-area' template found
292 } elseif (strpos($template, 'js_') > -1) {
293 // JavaScript template found
296 // Test for extension
297 $test = substr($template, 0, strpos($template, '_'));
298 if (EXT_IS_ACTIVE($test)) {
299 // Set extra path to extension's name
304 ////////////////////////
305 // Generate file name //
306 ////////////////////////
307 $FQFN = $basePath . $mode . $template . '.tpl';
309 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
310 // Select what depended header/footer template file for admin/guest/member area
311 $file2 = sprintf("%s%s%s_%s.tpl",
319 if (isFileReadable($file2)) $FQFN = $file2;
321 // Remove variable from memory
325 // Does the special template exists?
326 if (!isFileReadable($FQFN)) {
327 // Reset to default template
328 $FQFN = $basePath . $template . '.tpl';
331 // Now does the final template exists?
332 if (isFileReadable($FQFN)) {
333 // The local file does exists so we load it. :)
334 $tmpl_file = readFromFile($FQFN);
336 // Replace ' to our own chars to preventing them being quoted
337 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
339 // Do we have to compile the code?
341 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
343 $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
346 // Simply return loaded code
350 // Add surrounding HTML comments to help finding bugs faster
351 $ret = "<!-- Template " . $template . " - Start -->\n" . $ret . "<!-- Template " . $template . " - End -->\n";
352 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
353 // Only admins shall see this warning or when installation mode is active
354 $ret = "<br /><span class=\"guest_failed\">{--TEMPLATE_404--}</span><br />
355 (".basename($FQFN).")<br />
357 {--TEMPLATE_CONTENT--}
358 <pre>".print_r($content, true)."</pre>
360 <pre>".print_r($DATA, true)."</pre>
364 // Remove content and data
368 // Do we have some content to output or return?
370 // Not empty so let's put it out! ;)
371 if ($return === true) {
372 // Return the HTML code
378 } elseif (isDebugModeEnabled()) {
379 // Warning, empty output!
380 return "E:" . $template."<br />\n";
384 // Send mail out to an email address
385 function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '') {
386 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />\n";
388 // Compile subject line (for POINTS constant etc.)
389 $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
393 if ((!eregi("@", $toEmail)) && ($toEmail > 0)) {
394 // Value detected, is the message extension installed?
395 if (EXT_IS_ACTIVE("msg")) {
396 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
399 // Load email address
400 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($toEmail)), __FUNCTION__, __LINE__);
401 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
403 // Does the user exist?
404 if (SQL_NUMROWS($result_email)) {
405 // Load email address
406 list($toEmail) = SQL_FETCHROW($result_email);
409 $toEmail = constant('WEBMASTER');
413 SQL_FREERESULT($result_email);
415 } elseif ($toEmail == '0') {
417 $toEmail = constant('WEBMASTER');
419 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
421 // Check for PHPMailer or debug-mode
422 if (!checkPhpMailerUsage()) {
423 // Not in PHPMailer-Mode
424 if (empty($mailHeader)) {
425 // Load email header template
426 $mailHeader = LOAD_EMAIL_TEMPLATE('header');
429 $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
431 } elseif (isDebugModeEnabled()) {
432 if (empty($mailHeader)) {
433 // Load email header template
434 $mailHeader = LOAD_EMAIL_TEMPLATE('header');
437 $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
442 $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
446 $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
449 // Fix HTML parameter (default is no!)
450 if (empty($HTML)) $HTML = 'N';
451 if (isDebugModeEnabled()) {
452 // In debug mode we want to display the mail instead of sending it away so we can debug this part
454 ".htmlentities(trim($mailHeader))."
456 Subject : " . $subject."
457 Message : " . $message."
459 } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE('html_mail'))) {
460 // Send mail as HTML away
461 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
462 } elseif (!empty($toEmail)) {
464 sendRawEmail($toEmail, $subject, $message, $mailHeader);
465 } elseif ($HTML == 'N') {
467 sendRawEmail(constant('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
471 // Check if legacy or PHPMailer command
472 // @TODO Rewrite this to an extension 'smtp'
474 function checkPhpMailerUsage() {
475 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
478 // Send out a raw email with PHPMailer class or legacy mail() command
479 function sendRawEmail ($toEmail, $subject, $message, $from) {
480 // Shall we use PHPMailer class or legacy mode?
481 if (checkPhpMailerUsage()) {
482 // Use PHPMailer class with SMTP enabled
483 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
484 loadIncludeOnce('inc/phpmailer/class.smtp.php');
487 $mail = new PHPMailer();
488 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
491 $mail->SMTPAuth = true;
492 $mail->Host = getConfig('SMTP_HOSTNAME');
494 $mail->Username = getConfig('SMTP_USER');
495 $mail->Password = getConfig('SMTP_PASSWORD');
497 $mail->From = constant('WEBMASTER');
501 $mail->FromName = constant('MAIN_TITLE');
502 $mail->Subject = $subject;
503 if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($message) != $message)) {
504 $mail->Body = $message;
505 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
506 $mail->WordWrap = 70;
509 $mail->Body = decodeEntities($message);
511 $mail->AddAddress($toEmail, '');
512 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
513 $mail->AddCustomHeader('Errors-To:' . constant('WEBMASTER'));
514 $mail->AddCustomHeader('X-Loop:' . constant('WEBMASTER'));
517 // Use legacy mail() command
518 mail($toEmail, $subject, decodeEntities($message), $from);
522 // Generate a password in a specified length or use default password length
523 function generatePassword ($length = 0) {
524 // Auto-fix invalid length of zero
525 if ($length == 0) $length = getConfig('pass_len');
527 // Initialize array with all allowed chars
528 $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,-,+,_,/,.');
530 // Start creating password
532 for ($i = 0; $i < $length; $i++) {
533 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
536 // When the size is below 40 we can also add additional security by scrambling
537 // it. Otherwise we may corrupt hashes
538 if (strlen($PASS) <= 40) {
539 // Also scramble the password
540 $PASS = scrambleString($PASS);
543 // Return the password
547 // Generates a human-readable timestamp from the Uni* stamp
548 function generateDateTime ($time, $mode = '0') {
549 // Filter out numbers
550 $time = bigintval($time);
552 // If the stamp is zero it mostly didn't "happen"
555 return getMessage('NEVER_HAPPENED');
558 switch (getLanguage())
560 case 'de': // German date / time format
562 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
563 case '1': $ret = strtolower(date("d.m.Y - H:i", $time)); break;
564 case '2': $ret = date("d.m.Y|H:i", $time); break;
565 case '3': $ret = date("d.m.Y", $time); break;
567 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
572 default: // Default is the US date / time format!
574 case '0': $ret = date("r", $time); break;
575 case '1': $ret = date("Y-m-d - g:i A", $time); break;
576 case '2': $ret = date("y-m-d|H:i", $time); break;
577 case '3': $ret = date("y-m-d", $time); break;
579 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
586 // Translates Y/N to yes/no
587 function translateYesNo ($yn) {
589 $translated = "??? (" . $yn.')';
591 case 'Y': $translated = getMessage('YES'); break;
592 case 'N': $translated = getMessage('NO'); break;
595 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
603 // Translates the "pool type" into human-readable
604 function translatePoolType ($type) {
605 // Default?type is unknown
606 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
609 $constName = sprintf("POOL_TYPE_%s", $type);
612 if (defined($constName)) {
614 $translated = getMessage($constName);
617 // Return "translation"
621 // Translates the american decimal dot into a german comma
622 function translateComma ($dotted, $cut = true, $max = 0) {
623 // Default is 3 you can change this in admin area "Misc -> Misc Options"
624 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
626 // Use from config is default
627 $maxComma = getConfig('max_comma');
629 // Use from parameter?
630 if ($max > 0) $maxComma = $max;
633 if (($cut) && ($max == 0)) {
634 // Test for commata if in cut-mode
635 $com = explode('.', $dotted);
636 if (count($com) < 2) {
637 // Don't display commatas even if there are none... ;-)
643 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
646 switch (getLanguage()) {
648 $dotted = number_format($dotted, $maxComma, ',', '.');
652 $dotted = number_format($dotted, $maxComma, '.', ',');
656 // Return translated value
660 // Translate Uni*-like gender to human-readable
661 function translateGender ($gender) {
663 $ret = '!' . $gender . '!';
665 // Male/female or company?
667 case 'M': $ret = getMessage('GENDER_M'); break;
668 case 'F': $ret = getMessage('GENDER_F'); break;
669 case 'C': $ret = getMessage('GENDER_C'); break;
671 // Log unknown gender
672 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
676 // Return translated gender
680 // "Translates" the user status
681 function translateUserStatus ($status) {
687 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
692 $ret = getMessage('ACCOUNT_DELETED');
696 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
697 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
705 // Generates an URL for the dereferer
706 function DEREFERER ($URL) {
707 // Don't de-refer our own links!
708 if (substr($URL, 0, strlen(constant('URL'))) != constant('URL')) {
709 // De-refer this link
710 $URL = 'modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
717 // Generates an URL for the frametester
718 function FRAMETESTER ($URL) {
719 // Prepare frametester URL
720 $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&url=%s",
721 encodeString(compileUriCode($URL))
723 return $frametesterUrl;
726 // Count entries from e.g. a selection box
727 function countSelection ($array) {
729 if (is_array($array)) {
730 foreach ($array as $key => $selected) {
731 if (!empty($selected)) $ret++;
737 // Generate XHTML code for the CAPTCHA
738 function generateCaptchaCode ($code, $type, $DATA, $uid) {
739 return '<IMG border="0" alt="Code" src="{!URL!}/mailid_top.php?uid=' . $uid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
742 // Loads an email template and compiles it
743 function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
746 // Our configuration is kept non-global here
747 $_CONFIG = getConfigArray();
749 // Make sure all template names are lowercase!
750 $template = strtolower($template);
752 // Default 'nickname' if extension is not installed
755 // Prepare IP number and User Agent
756 $REMOTE_ADDR = detectRemoteAddr();
757 $HTTP_USER_AGENT = detectUserAgent();
760 $ADMIN = constant('MAIN_TITLE');
762 // Is the admin logged in?
765 $aid = getCurrentAdminId();
768 $ADMIN = getAdminEmail($aid);
771 // Neutral email address is default
772 $email = constant('WEBMASTER');
774 // Expiration in a nice output format
775 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
776 if (getConfig('auto_purge') == 0) {
777 // Will never expire!
778 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
780 // Create nice date string
781 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
784 // Is content an array?
785 if (is_array($content)) {
786 // Add expiration to array, $EXPIRATION is now deprecated!
787 $content['expiration'] = $EXPIRATION;
791 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
792 if (($UID > 0) && (is_array($content))) {
793 // If nickname extension is installed, fetch nickname as well
794 if (EXT_IS_ACTIVE('nickname')) {
795 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
797 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
798 array(bigintval($UID)), __FUNCTION__, __LINE__);
800 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
802 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
803 array(bigintval($UID)), __FUNCTION__, __LINE__);
806 // Fetch and merge data
807 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
808 $content = merge_array($content, SQL_FETCHARRAY($result));
809 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
812 SQL_FREERESULT($result);
815 // Translate M to male or F to female if present
816 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
818 // Overwrite email from data if present
819 if (isset($content['email'])) $email = $content['email'];
821 // Store email for some functions in global data array
822 $DATA['email'] = $email;
825 $basePath = sprintf("%stemplates/%s/emails/", constant('PATH'), getLanguage());
827 // Check for admin/guest/member templates
828 if (strpos($template, 'admin_') > -1) {
829 // Admin template found
830 $FQFN = $basePath.'admin/' . $template.'.tpl';
831 } elseif (strpos($template, 'guest_') > -1) {
832 // Guest template found
833 $FQFN = $basePath.'guest/' . $template.'.tpl';
834 } elseif (strpos($template, 'member_') > -1) {
835 // Member template found
836 $FQFN = $basePath.'member/' . $template.'.tpl';
838 // Test for extension
839 $test = substr($template, 0, strpos($template, '_'));
840 if (EXT_IS_ACTIVE($test)) {
841 // Set extra path to extension's name
842 $FQFN = $basePath . $test.'/' . $template.'.tpl';
844 // No special filename
845 $FQFN = $basePath . $template.'.tpl';
849 // Does the special template exists?
850 if (!isFileReadable($FQFN)) {
851 // Reset to default template
852 $FQFN = $basePath . $template.'.tpl';
855 // Now does the final template exists?
857 if (isFileReadable($FQFN)) {
858 // The local file does exists so we load it. :)
859 $tmpl_file = readFromFile($FQFN);
860 $tmpl_file = SQL_ESCAPE($tmpl_file);
863 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
865 } elseif (!empty($template)) {
866 // Template file not found!
867 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
868 {--TEMPLATE_CONTENT--}
869 <pre>".print_r($content, true)."</pre>
871 <pre>".print_r($DATA, true)."</pre>
874 // Debug mode not active? Then remove the HTML tags
875 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
877 // No template name supplied!
878 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
881 // Is there some content?
882 if (empty($newContent)) {
884 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $tmpl_file;
885 // Add last error if the required function exists
886 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
889 // Remove content and data
893 // Return compiled content
894 return COMPILE_CODE($newContent);
897 // Generates a timestamp (some wrapper for mktime())
898 function makeTime ($H, $M, $S, $stamp) {
899 // Extract day, month and year from given timestamp
900 $day = date('d', $stamp);
901 $month = date('m', $stamp);
902 $year = date('Y', $stamp);
904 // Create timestamp for wished time which depends on extracted date
905 return mktime($H, $M, $S, $month, $day, $year);
908 // Redirects to an URL and if neccessarry extends it with own base URL
909 function redirectToUrl ($URL) {
910 // Compile out URI codes
911 $URL = compileUriCode($URL);
913 // Check if http(s):// is there
914 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
915 // Make all URLs full-qualified
916 $URL = constant('URL') . '/' . $URL;
919 // Three different debug ways...
920 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
921 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
922 //* DEBUG: */ die($URL);
924 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
925 $rel = ' rel="external"';
927 // Do we have internal or external URL?
928 if (substr($URL, 0, strlen(constant('URL'))) == constant('URL')) {
929 // Own (=internal) URL
934 $OUTPUT = ob_get_contents();
936 // Clear it only if there is content
937 if (!empty($OUTPUT)) {
941 // Simple probe for bots/spiders from search engines
942 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
943 // Secure the URL against bad things such als HTML insertions and so on...
944 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
946 // Output new location link as anchor
947 OUTPUT_HTML('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
948 } elseif (!headers_sent()) {
949 // Load URL when headers are not sent
950 //* DEBUG: */ debug_report_bug("URL={$URL}");
951 sendHeader('Location: '.str_replace('&', '&', $URL));
953 // Output error message
954 loadInclude('inc/header.php');
955 LOAD_TEMPLATE('redirect_url', false, str_replace('&', '&', $URL));
956 loadInclude('inc/footer.php');
959 // Shut the mailer down here
963 // Wrapper for redirectToUrl but URL comes from a configuration entry
964 function redirectToConfiguredUrl ($configEntry) {
966 $URL = getConfig($configEntry);
971 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
979 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
980 // Is the code a string?
981 if (!is_string($code)) {
982 // Silently return it
986 // Init replacement-array with full security characters
987 $secChars = $GLOBALS['security_chars'];
989 // Select smaller set of chars to replace when we e.g. want to compile URLs
990 if (!$full) $secChars = $GLOBALS['url_chars'];
993 if ($constants === true) {
994 // BEFORE 0.2.1 : Language and data constants
995 // WITH 0.2.1+ : Only language constants
996 $code = str_replace('{--','".', str_replace('--}','."', $code));
998 // BEFORE 0.2.1 : Not used
999 // WITH 0.2.1+ : Data constants
1000 $code = str_replace('{!','".', str_replace("!}", '."', $code));
1003 // Compile QUOT and other non-HTML codes
1004 foreach ($secChars['to'] as $k => $to) {
1005 // Do the reversed thing as in inc/libs/security_functions.php
1006 $code = str_replace($to, $secChars['from'][$k], $code);
1009 // But shall I keep simple quotes for later use?
1010 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1012 // Find $content[bla][blub] entries
1013 preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1015 // Are some matches found?
1016 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1017 // Replace all matches
1018 $matchesFound = array();
1019 foreach ($matches[0] as $key => $match) {
1020 // Fuzzy look has failed by default
1021 $fuzzyFound = false;
1023 // Fuzzy look on match if already found
1024 foreach ($matchesFound as $found => $set) {
1026 $test = substr($found, 0, strlen($match));
1028 // Does this entry exist?
1029 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1030 if ($test == $match) {
1032 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1039 if ($fuzzyFound) continue;
1041 // Take all string elements
1042 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1043 // Replace it in the code
1044 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1045 $newMatch = str_replace("[" . $matches[4][$key]."]", "['" . $matches[4][$key]."']", $match);
1046 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1047 $matchesFound[$key."_" . $matches[4][$key]] = 1;
1048 $matchesFound[$match] = 1;
1049 } elseif (!isset($matchesFound[$match])) {
1050 // Not yet replaced!
1051 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1052 $code = str_replace($match, "\"." . $match.".\"", $code);
1053 $matchesFound[$match] = 1;
1058 // Return compiled code
1062 /************************************************************************
1064 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1065 * $a_sort sortiert: *
1067 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1068 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1069 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1070 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1071 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1073 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1074 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1075 * Sie, dass es doch nicht so schwer ist! :-) *
1077 ************************************************************************/
1078 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1080 while ($primary_key < count($a_sort)) {
1081 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1082 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1085 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1086 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1087 } elseif ($key != $key2) {
1088 // Sort numbers (E.g.: 9 < 10)
1089 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1090 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1094 // We have found two different values, so let's sort whole array
1095 foreach ($dummy as $sort_key => $sort_val) {
1096 $t = $dummy[$sort_key][$key];
1097 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1098 $dummy[$sort_key][$key2] = $t;
1109 // Write back sorted array
1114 function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
1117 if ($type == 'yn') {
1118 // This is a yes/no selection only!
1119 if ($id > 0) $prefix .= "[" . $id."]";
1120 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1122 // Begin with regular selection box here
1123 if (!empty($prefix)) $prefix .= "_";
1125 if ($id > 0) $type2 .= "[" . $id."]";
1126 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1131 for ($idx = 1; $idx < 32; $idx++) {
1132 $OUT .= "<option value=\"" . $idx."\"";
1133 if ($default == $idx) $OUT .= ' selected="selected"';
1134 $OUT .= ">" . $idx."</option>\n";
1138 case "month": // Month
1139 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1140 $OUT .= "<option value=\"" . $month."\"";
1141 if ($default == $month) $OUT .= ' selected="selected"';
1142 $OUT .= ">" . $descr."</option>\n";
1146 case "year": // Year
1148 $year = date('Y', time());
1150 // Use configured min age or fixed?
1151 if (GET_EXT_VERSION('other') >= '0.2.1') {
1153 $startYear = $year - getConfig('min_age');
1156 $startYear = $year - 16;
1159 // Calculate earliest year (100 years old people can still enter Internet???)
1160 $minYear = $year - 100;
1162 // Check if the default value is larger than minimum and bigger than actual year
1163 if (($default > $minYear) && ($default >= $year)) {
1164 for ($idx = $year; $idx < ($year + 11); $idx++) {
1165 $OUT .= "<option value=\"" . $idx."\"";
1166 if ($default == $idx) $OUT .= ' selected="selected"';
1167 $OUT .= ">" . $idx."</option>\n";
1169 } elseif ($default == -1) {
1170 // Current year minus 1
1171 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1173 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1176 // Get current year and subtract the configured minimum age
1177 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1178 // Calculate earliest year depending on extension version
1179 if (GET_EXT_VERSION('other') >= '0.2.1') {
1180 // Use configured minimum age
1181 $year = date('Y', time()) - getConfig('min_age');
1183 // Use fixed 16 years age
1184 $year = date('Y', time()) - 16;
1187 // Construct year selection list
1188 for ($idx = $minYear; $idx <= $year; $idx++) {
1189 $OUT .= "<option value=\"" . $idx."\"";
1190 if ($default == $idx) $OUT .= ' selected="selected"';
1191 $OUT .= ">" . $idx."</option>\n";
1198 for ($idx = 0; $idx < 60; $idx+=5) {
1199 if (strlen($idx) == 1) $idx = '0' . $idx;
1200 $OUT .= "<option value=\"" . $idx."\"";
1201 if ($default == $idx) $OUT .= ' selected="selected"';
1202 $OUT .= ">" . $idx."</option>\n";
1207 for ($idx = 0; $idx < 24; $idx++) {
1208 if (strlen($idx) == 1) $idx = '0' . $idx;
1209 $OUT .= "<option value=\"" . $idx."\"";
1210 if ($default == $idx) $OUT .= ' selected="selected"';
1211 $OUT .= ">" . $idx."</option>\n";
1216 $OUT .= "<option value=\"Y\"";
1217 if ($default == 'Y') $OUT .= ' selected="selected"';
1218 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1219 if ($default == 'N') $OUT .= ' selected="selected"';
1220 $OUT .= ">{--NO--}</option>\n";
1223 $OUT .= " </select>\n";
1228 // Deprecated : $length
1231 function generateRandomCode ($length, $code, $uid, $DATA = '') {
1232 // Fix missing _MAX constant
1233 // @TODO Rewrite this unnice code
1234 if (!defined('_MAX')) define('_MAX', 15235);
1236 // Build server string
1237 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH').'inc/databases.php');
1240 $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY');
1241 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1242 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1243 $keys .= getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1244 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1246 // Build string from misc data
1247 $data = $code.getConfig('ENCRYPT_SEPERATOR') . $uid.getConfig('ENCRYPT_SEPERATOR') . $DATA;
1249 // Add more additional data
1250 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('u_hash');
1251 if (isUserIdSet()) $data .= getConfig('ENCRYPT_SEPERATOR').getUserId();
1252 if (isSessionVariableSet('mxchange_theme')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
1253 if (isSessionVariableSet('mx_lang')) $data .= getConfig('ENCRYPT_SEPERATOR').getLanguage();
1254 if (isset($GLOBALS['refid'])) $data .= getConfig('ENCRYPT_SEPERATOR') . $GLOBALS['refid'];
1256 // Calculate number for generating the code
1257 $a = $code + getConfig('_ADD') - 1;
1259 if (isConfigEntrySet('master_hash')) {
1260 // Generate hash with master salt from modula of number with the prime number and other data
1261 $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'));
1263 // Create number from hash
1264 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1266 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1267 $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));
1269 // Create number from hash
1270 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1273 // At least 10 numbers shall be secure enought!
1274 $len = getConfig('code_length');
1275 if ($len == 0) $len = $length;
1276 if ($len == 0) $len = 10;
1278 // Cut off requested counts of number
1279 $return = substr(str_replace('.', '', $rcode), 0, $len);
1281 // Done building code
1285 // Does only allow numbers
1286 function bigintval ($num, $castValue = true) {
1287 // Filter all numbers out
1288 $ret = preg_replace("/[^0123456789]/", '', $num);
1291 if ($castValue) $ret = (double)$ret;
1293 // Has the whole value changed?
1294 // @TODO Remove this if() block if all is working fine
1295 if ('' . $ret . '' != '' . $num . '') {
1297 //debug_report_bug("{$ret}<>{$num}");
1304 // Insert the code in $img_code into jpeg or PNG image
1305 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1306 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1307 // Stop execution of function here because of over-sized code length
1309 } elseif (!$headerSent) {
1310 // Return in an HTML code code
1311 return "<img src=\"{!URL!}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1315 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), getCurrentTheme(), getConfig('img_type'));
1316 if (isFileReadable($img)) {
1317 // Switch image type
1318 switch (getConfig('img_type'))
1321 // Okay, load image and hide all errors
1322 $image = @imagecreatefromjpeg($img);
1326 // Okay, load image and hide all errors
1327 $image = @imagecreatefrompng($img);
1331 // Exit function here
1332 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1336 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1337 $text_color = imagecolorallocate($image, 0, 0, 0);
1339 // Insert code into image
1340 imagestring($image, 5, 14, 2, $img_code, $text_color);
1342 // Return to browser
1343 sendHeader('Content-Type: image/' . getConfig('img_type'));
1345 // Output image with matching image factory
1346 switch (getConfig('img_type')) {
1347 case 'jpg': imagejpeg($image); break;
1348 case 'png': imagepng($image); break;
1351 // Remove image from memory
1352 imagedestroy($image);
1354 // Create selection box or array of splitted timestamp
1355 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1356 // Calculate 2-seconds timestamp
1357 $stamp = round($timestamp);
1358 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1360 // Do we have a leap year?
1362 $TEST = date('Y', time()) / 4;
1363 $M1 = date('m', time());
1364 $M2 = date('m', (time() + $timestamp));
1366 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1367 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1369 // First of all years...
1370 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1371 //* DEBUG: */ print("Y={$Y}<br />\n");
1373 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1374 //* DEBUG: */ print("M={$M}<br />\n");
1376 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1377 //* DEBUG: */ print("W={$W}<br />\n");
1379 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1380 //* DEBUG: */ print("D={$D}<br />\n");
1382 $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));
1383 //* DEBUG: */ print("h={$h}<br />\n");
1385 $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));
1386 //* DEBUG: */ print("m={$m}<br />\n");
1387 // And at last seconds...
1388 $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));
1389 //* DEBUG: */ print("s={$s}<br />\n");
1391 // Is seconds zero and time is < 60 seconds?
1392 if (($s == 0) && ($timestamp < 60)) {
1394 $s = round($timestamp);
1398 // Now we convert them in seconds...
1400 if ($return_array) {
1401 // Just put all data in an array for later use
1413 $OUT = "<div align=\"" . $align."\">\n";
1414 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1417 if (ereg('Y', $display) || (empty($display))) {
1418 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1421 if (ereg("M", $display) || (empty($display))) {
1422 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1425 if (ereg("W", $display) || (empty($display))) {
1426 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1429 if (ereg("D", $display) || (empty($display))) {
1430 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1433 if (ereg("h", $display) || (empty($display))) {
1434 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1437 if (ereg('m', $display) || (empty($display))) {
1438 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1441 if (ereg("s", $display) || (empty($display))) {
1442 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1448 if (ereg('Y', $display) || (empty($display))) {
1449 // Generate year selection
1450 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1451 for ($idx = 0; $idx <= 10; $idx++) {
1452 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1453 if ($idx == $Y) $OUT .= ' selected="selected"';
1454 $OUT .= ">" . $idx."</option>\n";
1456 $OUT .= " </select></td>\n";
1458 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1461 if (ereg("M", $display) || (empty($display))) {
1462 // Generate month selection
1463 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1464 for ($idx = 0; $idx <= 11; $idx++)
1466 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1467 if ($idx == $M) $OUT .= ' selected="selected"';
1468 $OUT .= ">" . $idx."</option>\n";
1470 $OUT .= " </select></td>\n";
1472 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1475 if (ereg("W", $display) || (empty($display))) {
1476 // Generate week selection
1477 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1478 for ($idx = 0; $idx <= 4; $idx++) {
1479 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1480 if ($idx == $W) $OUT .= ' selected="selected"';
1481 $OUT .= ">" . $idx."</option>\n";
1483 $OUT .= " </select></td>\n";
1485 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1488 if (ereg("D", $display) || (empty($display))) {
1489 // Generate day selection
1490 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1491 for ($idx = 0; $idx <= 31; $idx++) {
1492 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1493 if ($idx == $D) $OUT .= ' selected="selected"';
1494 $OUT .= ">" . $idx."</option>\n";
1496 $OUT .= " </select></td>\n";
1498 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1501 if (ereg("h", $display) || (empty($display))) {
1502 // Generate hour selection
1503 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1504 for ($idx = 0; $idx <= 23; $idx++) {
1505 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1506 if ($idx == $h) $OUT .= ' selected="selected"';
1507 $OUT .= ">" . $idx."</option>\n";
1509 $OUT .= " </select></td>\n";
1511 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1514 if (ereg('m', $display) || (empty($display))) {
1515 // Generate minute selection
1516 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1517 for ($idx = 0; $idx <= 59; $idx++) {
1518 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1519 if ($idx == $m) $OUT .= ' selected="selected"';
1520 $OUT .= ">" . $idx."</option>\n";
1522 $OUT .= " </select></td>\n";
1524 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1527 if (ereg("s", $display) || (empty($display))) {
1528 // Generate second selection
1529 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1530 for ($idx = 0; $idx <= 59; $idx++) {
1531 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1532 if ($idx == $s) $OUT .= ' selected="selected"';
1533 $OUT .= ">" . $idx."</option>\n";
1535 $OUT .= " </select></td>\n";
1537 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1540 $OUT .= "</table>\n";
1542 // Return generated HTML code
1548 function createTimestampFromSelections ($prefix, $POST) {
1549 // Initial return value
1552 // Do we have a leap year?
1554 $TEST = date('Y', time()) / 4;
1555 $M1 = date('m', time());
1556 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1557 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1558 // First add years...
1559 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1561 $ret += $POST[$prefix."_mo"] * 2628000;
1563 $ret += $POST[$prefix."_we"] * 604800;
1565 $ret += $POST[$prefix."_da"] * 86400;
1567 $ret += $POST[$prefix."_ho"] * 3600;
1569 $ret += $POST[$prefix."_mi"] * 60;
1570 // And at last seconds...
1571 $ret += $POST[$prefix."_se"];
1572 // Return calculated value
1576 // Sends out mail to all administrators
1577 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1578 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1579 // Trim template name
1580 $template = trim($template);
1582 // Load email template
1583 $message = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1585 // Check which admin shall receive this mail
1586 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1587 array($template), __FUNCTION__, __LINE__);
1588 if (SQL_NUMROWS($result) == 0) {
1589 // Create new entry (to all admins)
1590 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1591 array($template), __FUNCTION__, __LINE__);
1593 // Load admin IDs...
1594 // @TODO This can be, somehow, rewritten
1595 $adminIds = array();
1596 while ($content = SQL_FETCHARRAY($result)) {
1597 $adminIds[] = $content['admin_id'];
1601 SQL_FREERESULT($result);
1606 // "implode" IDs and query string
1607 $aid = implode(',', $adminIds);
1609 if (EXT_IS_ACTIVE('events')) {
1610 // Add line to user events
1611 EVENTS_ADD_LINE($subj, $message, $UID);
1613 // Log error for debug
1614 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1620 } elseif ($aid == '0') {
1621 // Select all email adresses
1622 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1623 __FUNCTION__, __LINE__);
1625 // If Admin-ID is not "to-all" select
1626 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1627 array($aid), __FUNCTION__, __LINE__);
1631 // Load email addresses and send away
1632 while ($content = SQL_FETCHARRAY($result)) {
1633 sendEmail($content['email'], $subj, $message);
1637 SQL_FREERESULT($result);
1640 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1641 function createFancyTime ($stamp) {
1642 // Get data array with years/months/weeks/days/...
1643 $data = createTimeSelections($stamp, '', '', '', true);
1645 foreach($data as $k => $v) {
1647 // Value is greater than 0 "eval" data to return string
1648 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1654 // Do we have something there?
1655 if (strlen($ret) > 0) {
1656 // Remove leading commata and space
1657 $ret = substr($ret, 2);
1660 $ret = "0 {--_SECONDS--}";
1663 // Return fancy time string
1668 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1669 $SEP = ''; $TOP = '';
1672 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1676 for ($page = 1; $page <= $PAGES; $page++) {
1677 // Is the page currently selected or shall we generate a link to it?
1678 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1679 // Is currently selected, so only highlight it
1680 $NAV .= "<strong>-";
1682 // Open anchor tag and add base URL
1683 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=" . getWhat()."&page=" . $page."&offset=" . $offset;
1685 // Add userid when we shall show all mails from a single member
1686 if ((REQUEST_ISSET_GET('uid')) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1688 // Close open anchor tag
1692 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1693 // Is currently selected, so only highlight it
1694 $NAV .= "-</strong>";
1700 // Add seperator if we have not yet reached total pages
1701 if ($page < $PAGES) $NAV .= " | ";
1704 // Define constants only once
1705 if (!defined('__NAV_OUTPUT')) {
1706 define('__NAV_OUTPUT' , $NAV);
1707 define('__NAV_COLSPAN', $colspan);
1708 define('__NAV_TOP' , $TOP);
1709 define('__NAV_SEP' , $SEP);
1712 // Load navigation template
1713 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1715 if ($return === true) {
1716 // Return generated HTML-Code
1724 // Extract host from script name
1725 function extractHostnameFromUrl (&$script) {
1726 // Use default SERVER_URL by default... ;) So?
1727 $url = constant('SERVER_URL');
1729 // Is this URL valid?
1730 if (substr($script, 0, 7) == 'http://') {
1731 // Use the hostname from script URL as new hostname
1732 $url = substr($script, 7);
1733 $extract = explode('/', $url);
1735 // Done extracting the URL :)
1738 // Extract host name
1739 $host = str_replace('http://', '', $url);
1740 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1742 // Generate relative URL
1743 //* DEBUG: */ print("SCRIPT=" . $script."<br />\n");
1744 if (substr(strtolower($script), 0, 7) == 'http://') {
1745 // But only if http:// is in front!
1746 $script = substr($script, (strlen($url) + 7));
1747 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1749 $script = substr($script, (strlen($url) + 8));
1752 //* DEBUG: */ print("SCRIPT=" . $script."<br />\n");
1753 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1759 // Send a GET request
1760 function sendGetRequest ($script) {
1761 // Compile the script name
1762 $script = COMPILE_CODE($script);
1764 // Extract host name from script
1765 $host = extractHostnameFromUrl($script);
1767 // Generate GET request header
1768 $request = "GET /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
1769 $request .= "Host: " . $host . getConfig('HTTP_EOL');
1770 $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
1771 if (defined('FULL_VERSION')) {
1772 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
1774 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?" . getConfig('HTTP_EOL');
1776 $request .= "Content-Type: text/plain" . getConfig('HTTP_EOL');
1777 $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
1778 $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1780 // Send the raw request
1781 $response = sendRawRequest($host, $request);
1783 // Return the result to the caller function
1787 // Send a POST request
1788 function sendPostRequest ($script, $postData) {
1789 // Is postData an array?
1790 if (!is_array($postData)) {
1792 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1793 return array('', '', '');
1796 // Compile the script name
1797 $script = COMPILE_CODE($script);
1799 // Extract host name from script
1800 $host = extractHostnameFromUrl($script);
1802 // Construct request
1803 $data = http_build_query($postData, '','&');
1805 // Generate POST request header
1806 $request = "POST /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
1807 $request .= "Host: " . $host . getConfig('HTTP_EOL');
1808 $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
1809 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
1810 $request .= "Content-type: application/x-www-form-urlencoded" . getConfig('HTTP_EOL');
1811 $request .= "Content-length: " . strlen($data) . getConfig('HTTP_EOL');
1812 $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
1813 $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1816 // Send the raw request
1817 $response = sendRawRequest($host, $request);
1819 // Return the result to the caller function
1823 // Sends a raw request to another host
1824 function sendRawRequest ($host, $request) {
1825 // Init errno and errdesc with 'all fine' values
1826 $errno = 0; $errdesc = '';
1829 $response = array('', '', '');
1831 // Default is not to use proxy
1834 // Are proxy settins set?
1835 if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
1841 //* DEBUG: */ die("SCRIPT=" . $script."<br />\n");
1842 if ($useProxy === true) {
1843 // Connect to host through proxy connection
1844 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1846 // Connect to host directly
1847 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1851 if (!is_resource($fp)) {
1857 if ($useProxy === true) {
1858 // Generate CONNECT request header
1859 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1860 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1862 // Use login data to proxy? (username at least!)
1863 if (getConfig('proxy_username') != '') {
1865 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . COMPILE_CODE(getConfig('proxy_password')));
1866 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1869 // Add last new-line
1870 $proxyTunnel .= getConfig('HTTP_EOL');
1871 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1874 fputs($fp, $proxyTunnel);
1878 // No response received
1882 // Read the first line
1883 $resp = trim(fgets($fp, 10240));
1884 $respArray = explode(' ', $resp);
1885 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1886 // Invalid response!
1892 fputs($fp, $request);
1895 while (!feof($fp)) {
1896 $response[] = trim(fgets($fp, 1024));
1902 // Skip first empty lines
1904 foreach ($resp as $idx => $line) {
1906 $line = trim($line);
1908 // Is this line empty?
1911 array_shift($response);
1913 // Abort on first non-empty line
1918 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1920 // Proxy agent found?
1921 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1922 // Proxy header detected, so remove two lines
1923 array_shift($response);
1924 array_shift($response);
1927 // Was the request successfull?
1928 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1929 // Not found / access forbidden
1930 $response = array('', '', '');
1937 // Taken from www.php.net eregi() user comments
1938 function isEmailValid ($email) {
1940 $email = COMPILE_CODE($email);
1942 // Check first part of email address
1943 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1946 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1949 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1951 // Return check result
1952 // @NOTE altered the regex-pattern and added modificator i (match both upper and lower case letters) and U (PCRE_UNGREEDY) to work with preg_match the same way as eregi
1953 return preg_match($regex, $email);
1956 // Function taken from user comments on www.php.net / function eregi()
1957 function isUrlValid ($URL, $compile=true) {
1958 // Trim URL a little
1959 $URL = trim(urldecode($URL));
1960 //* DEBUG: */ echo $URL."<br />";
1962 // Compile some chars out...
1963 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1964 //* DEBUG: */ echo $URL."<br />";
1966 // Check for the extension filter
1967 if (EXT_IS_ACTIVE('filter')) {
1968 // Use the extension's filter set
1969 return FILTER_VALIDATE_URL($URL, false);
1972 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1973 // https:// in front of the URLs
1974 return isUrlValidSimple($URL);
1977 // Generate a list of administrative links to a given userid
1978 function generateMemberAdminActionLinks ($uid, $status = '') {
1979 // Define all main targets
1980 $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1982 // Begin of navigation links
1983 $eval = "\$OUT = \"[ ";
1985 foreach ($TARGETS as $tar) {
1986 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=" . $tar."&uid=" . $uid."\\\" title=\\\"{--ADMIN_LINK_";
1987 //* DEBUG: */ echo "*" . $tar.'/' . $status."*<br />\n";
1988 if (($tar == "lock_user") && ($status == 'LOCKED')) {
1989 // Locked accounts shall be unlocked
1990 $eval .= "UNLOCK_USER";
1992 // All other status is fine
1993 $eval .= strtoupper($tar);
1995 $eval .= "_TITLE--}\\\">{--ADMIN_";
1996 if (($tar == "lock_user") && ($status == 'LOCKED')) {
1997 // Locked accounts shall be unlocked
1998 $eval .= "UNLOCK_USER";
2000 // All other status is fine
2001 $eval .= strtoupper($tar);
2003 $eval .= "--}</a></span> | ";
2006 // Finish navigation link
2007 $eval = substr($eval, 0, -7)."]\";";
2014 // Generate an email link
2015 function generateMemberEmailLink ($email, $table = 'admins') {
2016 // Default email link (INSECURE! Spammer can read this by harvester programs)
2017 $EMAIL = 'mailto:' . $email;
2019 // Check for several extensions
2020 if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
2021 // Create email link for contacting admin in guest area
2022 $EMAIL = adminsCreateEmailLink($email);
2023 } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
2024 // Create email link for contacting a member within admin area (or later in other areas, too?)
2025 $EMAIL = USER_generateMemberEmailLink($email);
2026 } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
2027 // Create email link to contact sponsor within admin area (or like the link above?)
2028 $EMAIL = SPONSOR_generateMemberEmailLink($email);
2031 // Shall I close the link when there is no admin?
2032 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2034 // Return email link
2038 // Generate a hash for extra-security for all passwords
2039 function generateHash ($plainText, $salt = '') {
2040 // Is the required extension 'sql_patches' there and a salt is not given?
2041 if (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('sql_patches'))) && (empty($salt))) {
2042 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2043 return md5($plainText);
2046 // Do we miss an arry element here?
2047 if (!isConfigEntrySet('file_hash')) {
2049 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2052 // When the salt is empty build a new one, else use the first x configured characters as the salt
2054 // Build server string (inc/databases.php is no longer updated with every commit)
2055 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
2058 $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');
2061 $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
2063 // Calculate number for generating the code
2064 $a = time() + getConfig('_ADD') - 1;
2066 // Generate SHA1 sum from modula of number and the prime number
2067 $sha1 = sha1(($a % getConfig('_PRIME')) . $server.getConfig('ENCRYPT_SEPERATOR') . $keys.getConfig('ENCRYPT_SEPERATOR') . $data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR') . $a);
2068 //* DEBUG: */ echo "SHA1=" . $sha1." (".strlen($sha1).")<br />";
2069 $sha1 = scrambleString($sha1);
2070 //* DEBUG: */ echo "Scrambled=" . $sha1." (".strlen($sha1).")<br />";
2071 //* DEBUG: */ $sha1b = descrambleString($sha1);
2072 //* DEBUG: */ echo "Descrambled=" . $sha1b." (".strlen($sha1b).")<br />";
2074 // Generate the password salt string
2075 $salt = substr($sha1, 0, getConfig('salt_length'));
2076 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2079 $salt = substr($salt, 0, getConfig('salt_length'));
2080 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2084 return $salt.sha1($salt . $plainText);
2087 // Scramble a string
2088 function scrambleString($str) {
2092 // Final check, in case of failture it will return unscrambled string
2093 if (strlen($str) > 40) {
2094 // The string is to long
2096 } elseif (strlen($str) == 40) {
2098 $scrambleNums = explode(':', getConfig('pass_scramble'));
2100 // Generate new numbers
2101 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2104 // Scramble string here
2105 //* DEBUG: */ echo "***Original=" . $str."***<br />";
2106 for ($idx = 0; $idx < strlen($str); $idx++) {
2107 // Get char on scrambled position
2108 $char = substr($str, $scrambleNums[$idx], 1);
2110 // Add it to final output string
2111 $scrambled .= $char;
2114 // Return scrambled string
2115 //* DEBUG: */ echo "***Scrambled=" . $scrambled."***<br />";
2119 // De-scramble a string scrambled by scrambleString()
2120 function descrambleString($str) {
2121 // Scramble only 40 chars long strings
2122 if (strlen($str) != 40) return $str;
2124 // Load numbers from config
2125 $scrambleNums = explode(':', getConfig('pass_scramble'));
2128 if (count($scrambleNums) != 40) return $str;
2130 // Begin descrambling
2131 $orig = str_repeat(" ", 40);
2132 //* DEBUG: */ echo "+++Scrambled=" . $str."+++<br />";
2133 for ($idx = 0; $idx < 40; $idx++) {
2134 $char = substr($str, $idx, 1);
2135 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2138 // Return scrambled string
2139 //* DEBUG: */ echo "+++Original=" . $orig."+++<br />";
2143 // Generated a "string" for scrambling
2144 function genScrambleString ($len) {
2145 // Prepare array for the numbers
2146 $scrambleNumbers = array();
2148 // First we need to setup randomized numbers from 0 to 31
2149 for ($idx = 0; $idx < $len; $idx++) {
2151 $rand = mt_rand(0, ($len -1));
2153 // Check for it by creating more numbers
2154 while (array_key_exists($rand, $scrambleNumbers)) {
2155 $rand = mt_rand(0, ($len -1));
2159 $scrambleNumbers[$rand] = $rand;
2162 // So let's create the string for storing it in database
2163 $scrambleString = implode(':', $scrambleNumbers);
2164 return $scrambleString;
2167 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2168 function generatePassString ($passHash) {
2169 // Return vanilla password hash
2172 // Is a secret key and master salt already initialized?
2173 if ((getConfig('secret_key') != '') && (getConfig('master_salt') != '')) {
2174 // Only calculate when the secret key is generated
2175 $newHash = ''; $start = 9;
2176 for ($idx = 0; $idx < 10; $idx++) {
2177 $part1 = hexdec(substr($passHash, $start, 4));
2178 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2179 $mod = dechex($idx);
2180 if ($part1 > $part2) {
2181 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2182 } elseif ($part2 > $part1) {
2183 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2185 $mod = substr(round($mod), 0, 4);
2186 $mod = str_repeat('0', 4-strlen($mod)) . $mod;
2187 //* DEBUG: */ echo "*" . $start.'=' . $mod."*<br />";
2192 //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
2193 $ret = generateHash($newHash, getConfig('master_salt'));
2194 //* DEBUG: */ print($ret."<br />\n");
2197 //* DEBUG: */ echo "--" . $passHash."--<br />\n";
2198 $ret = md5($passHash);
2199 //* DEBUG: */ echo "++" . $ret."++<br />\n";
2206 // Fix "deleted" cookies
2207 function fixDeletedCookies ($cookies) {
2208 // Is this an array with entries?
2209 if ((is_array($cookies)) && (count($cookies) > 0)) {
2210 // Then check all cookies if they are marked as deleted!
2211 foreach ($cookies as $cookieName) {
2212 // Is the cookie set to "deleted"?
2213 if (getSession($cookieName) == 'deleted') {
2214 setSession($cookieName, '');
2220 // Output error messages in a fasioned way and die...
2221 function app_die ($F, $L, $message) {
2222 // Check if Script is already dieing and not let it kill itself another 1000 times
2223 if (!isset($GLOBALS['app_died'])) {
2224 // Make sure, that the script realy realy diese here and now
2225 $GLOBALS['app_died'] = true;
2228 loadIncludeOnce('inc/header.php');
2230 // Rewrite message for output
2231 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2233 // Better log this message away
2234 DEBUG_LOG($F, $L, $message);
2236 // Load the message template
2237 LOAD_TEMPLATE('admin_settings_saved', false, $message);
2240 loadIncludeOnce('inc/footer.php');
2242 // Script tried to kill itself twice
2243 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2247 // Display parsing time and number of SQL queries in footer
2248 function displayParsingTime() {
2249 // Is the timer started?
2250 if (!isset($GLOBALS['startTime'])) {
2256 $endTime = microtime(true);
2258 // "Explode" both times
2259 $start = explode(' ', $GLOBALS['startTime']);
2260 $end = explode(' ', $endTime);
2261 $runTime = $end[0] - $start[0];
2262 if ($runTime < 0) $runTime = 0;
2263 $runTime = translateComma($runTime);
2267 'runtime' => $runTime,
2268 'numSQLs' => (getConfig('sql_count') + 1),
2269 'numTemplates' => (getConfig('num_templates') + 1)
2272 // Load the template
2273 LOAD_TEMPLATE('show_timings', false, $content);
2276 // Check wether a boolean constant is set
2277 // Taken from user comments in PHP documentation for function constant()
2278 function isBooleanConstantAndTrue ($constName) { // : Boolean
2279 // Failed by default
2283 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2285 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />\n";
2286 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2289 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />\n";
2290 if (defined($constName)) {
2292 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />\n";
2293 $res = (constant($constName) === true);
2297 $GLOBALS['cache_array']['const'][$constName] = $res;
2299 //* DEBUG: */ var_dump($res);
2305 // Checks if a given apache module is loaded
2306 function isApacheModuleLoaded ($apacheModule) {
2307 // Check it and return result
2308 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2311 // Get current theme name
2312 function getCurrentTheme() {
2313 // The default theme is 'default'... ;-)
2316 // Load default theme if not empty from configuration
2317 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2319 if (!isSessionVariableSet('mxchange_theme')) {
2320 // Set default theme
2321 setSession('mxchange_theme', $ret);
2322 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
2323 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2324 // Get theme from cookie
2325 $ret = getSession('mxchange_theme');
2328 if (getThemeId($ret) == 0) {
2329 // Fix it to default
2332 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
2333 // Prepare FQFN for checking
2334 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
2336 // Installation mode active
2337 if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
2338 // Set cookie from URL data
2339 setSession('mxchange_theme', REQUEST_GET('theme'));
2340 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2341 // Set cookie from posted data
2342 setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2346 $ret = getSession('mxchange_theme');
2348 // Invalid design, reset cookie
2349 setSession('mxchange_theme', $ret);
2352 // Add (maybe) found theme.php file to inclusion list
2353 $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2355 // Try to load the requested include file
2356 if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
2358 // Return theme value
2362 // Get id from theme
2363 function getThemeId ($name) {
2364 // Is the extension 'theme' installed?
2365 if (!EXT_IS_ACTIVE('theme')) {
2373 // Is the cache entry there?
2374 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2375 // Get the version from cache
2376 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2379 incrementConfigEntry('cache_hits');
2380 } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
2381 // Check if current theme is already imported or not
2382 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2383 array($name), __FUNCTION__, __LINE__);
2386 if (SQL_NUMROWS($result) == 1) {
2388 list($id) = SQL_FETCHROW($result);
2392 SQL_FREERESULT($result);
2399 // Generates an error code from given account status
2400 function generateErrorCodeFromUserStatus ($status) {
2401 // @TODO The status should never be empty
2402 if (empty($status)) {
2403 // Something really bad happend here
2404 debug_report_bug(__FUNCTION__ . ': status is empty.');
2407 // Default error code if unknown account status
2408 $errorCode = getCode('UNKNOWN_STATUS');
2410 // Generate constant name
2411 $constantName = sprintf("ID_%s", $status);
2413 // Is the constant there?
2414 if (isCodeSet($constantName)) {
2416 $errorCode = getCode($constantName);
2419 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2422 // Return error code
2426 // Function to search for the last modifified file
2427 function searchDirsRecursive ($dir, &$last_changed) {
2429 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />\n";
2430 // Does it match what we are looking for? (We skip a lot files already!)
2431 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2432 $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2433 $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
2434 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2436 // Walk through all entries
2437 foreach ($ds as $d) {
2438 // Generate proper FQFN
2439 $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
2441 // Is it a file and readable?
2442 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2443 if (isDirectory($FQFN)) {
2444 // $FQFN is a directory so also crawl into this directory
2446 if (!empty($dir)) $newDir = $dir . '/'. $d;
2447 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />\n";
2448 searchDirsRecursive($newDir, $last_changed);
2449 } elseif (isFileReadable($FQFN)) {
2450 // $FQFN is a filename and no directory
2451 $time = filemtime($FQFN);
2452 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />\n";
2453 if ($last_changed['time'] < $time) {
2454 // This file is newer as the file before
2455 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2456 $last_changed['path_name'] = $FQFN;
2457 $last_changed['time'] = $time;
2463 // "Getter" for revision/version data
2464 function getActualVersion ($type = 'Revision') {
2465 // By default nothing is new... ;-)
2468 if (EXT_IS_ACTIVE('cache')) {
2469 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2470 if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') {
2471 // Force rebuild by URL parameter
2474 !isset($GLOBALS['cache_array']['revision'][$type])
2476 count($GLOBALS['cache_array']['revision']) < 3
2478 !$GLOBALS['cache_instance']->loadCacheFile('revision')
2484 // Is the cache file outdated/invalid?
2486 // Destroy cache file
2487 $GLOBALS['cache_instance']->destroyCacheFile();
2489 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2490 unset($GLOBALS['cache_array']['revision']);
2492 // Reload load_cach-revison.php
2493 loadInclude('inc/loader/load_cache-revision.php');
2499 // Return found value
2500 return $GLOBALS['cache_array']['revision'][$type][0];
2502 // Old Version without ext-cache active (deprecated ?)
2504 // FQFN of revision file
2505 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2507 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2508 if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
2509 // Forced rebuild of .revision file
2512 // Check for revision file
2513 if (!isFileReadable($FQFN)) {
2514 // Not found, so we need to create it
2517 // Revision file found
2518 $ins_vers = explode("\n", readFromFile($FQFN));
2520 // Get array for mapping information
2521 $mapper = array_flip(getSearchFor());
2522 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2524 // Is the content valid?
2525 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
2526 // File needs update!
2529 // Return found value
2530 return trim($ins_vers[$mapper[$type]]);
2535 // Has it been updated?
2536 if ($new === true) {
2537 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2542 // Repares an array we are looking for
2543 // 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
2544 function getSearchFor () {
2545 // Add Revision, Date, Tag and Author
2546 $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2548 // Return the created array
2552 // @TODO Please describe this function
2553 function getArrayFromActualVersion () {
2555 $next_dir = ''; // Directory to start with search
2556 $last_changed = array(
2560 $akt_vers = array(); // Init return array
2561 $res = 0; // Init value for counting the founded keywords
2563 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2564 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2567 $last_file = readFromFile($last_changed['path_name']);
2569 // Get all the keywords to search for
2570 $searchFor = getSearchFor();
2572 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2573 foreach ($searchFor as $search) {
2574 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2575 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2576 // This trimms the search-result and puts it in the $akt_vers-return array
2577 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2580 // Save the last-changed filename for debugging
2581 $akt_vers['File'] = $last_changed['path_name'];
2583 // at least 3 keyword-Tags are needed for propper values
2584 if ($res && $res >= 3
2585 && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
2586 && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
2587 && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
2588 // Prepare content witch need special treadment
2590 // Prepare timestamp for date
2591 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2592 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2594 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2595 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2596 $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2600 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2601 $version = sendGetRequest('check-updates3.php');
2604 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2605 if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
2606 if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
2607 if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
2608 if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
2611 // Return prepared array
2615 // Back-ported from the new ship-simu engine. :-)
2616 function debug_get_printable_backtrace () {
2618 $backtrace = "<ol>\n";
2620 // Get and prepare backtrace for output
2621 $backtraceArray = debug_backtrace();
2622 foreach ($backtraceArray as $key => $trace) {
2623 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2624 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2625 if (!isset($trace['args'])) $trace['args'] = array();
2626 $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";
2630 $backtrace .= "</ol>\n";
2632 // Return the backtrace
2636 // Output a debug backtrace to the user
2637 function debug_report_bug ($message = '') {
2640 // Is the optional message set?
2641 if (!empty($message)) {
2643 $debug = sprintf("Note: %s<br />\n",
2647 // @TODO Add a little more infos here
2648 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2652 $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>";
2653 $debug .= debug_get_printable_backtrace();
2654 $debug .= "</pre>\nRequest-URI: " . $_SERVER['REQUEST_URI']."<br />\n";
2655 $debug .= "Thank you for finding bugs.";
2658 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2662 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2663 function generateSeed () {
2664 list($usec, $sec) = explode(' ', microtime());
2665 $microTime = (((float)$sec + (float)$usec)) * 100000;
2669 // Converts a message code to a human-readable message
2670 function convertCodeToMessage ($code) {
2673 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2674 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2675 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2676 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2677 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2678 case getCode('USER_404') : $message = getMessage('USER_NOT_FOUND'); break;
2679 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2680 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2682 case getCode('ERROR_MAILID'):
2683 if (EXT_IS_ACTIVE($ext, true)) {
2684 $message = getMessage('ERROR_CONFIRMING_MAIL');
2686 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2690 case getCode('EXTENSION_PROBLEM'):
2691 if (REQUEST_ISSET_GET('ext')) {
2692 $message = generateExtensionInactiveNotInstalledMessage(REQUEST_GET('ext'));
2694 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2698 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2699 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2700 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2701 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2704 // Missing/invalid code
2705 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2708 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2712 // Return the message
2716 // Generate a "link" for the given admin id (aid)
2717 function generateAdminLink ($aid) {
2718 // No assigned admin is default
2719 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2721 // Zero? = Not assigned
2722 if (bigintval($aid) > 0) {
2723 // Load admin's login
2724 $login = getAdminLogin($aid);
2726 // Is the login valid?
2727 if ($login != '***') {
2728 // Is the extension there?
2729 if (EXT_IS_ACTIVE('admins')) {
2731 $admin = "<a href=\"".adminsCreateEmailLink(getAdminEmail($aid))."\">" . $login."</a>";
2733 // Extension not found
2734 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2738 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2746 // Compile characters which are allowed in URLs
2747 function compileUriCode ($code, $simple=true) {
2748 // Compile constants
2749 if (!$simple) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2751 // Compile QUOT and other non-HTML codes
2752 $code = str_replace('{DOT}', '.',
2753 str_replace('{SLASH}', '/',
2754 str_replace('{QUOT}', "'",
2755 str_replace('{DOLLAR}', '$',
2756 str_replace('{OPEN_ANCHOR}', '(',
2757 str_replace('{CLOSE_ANCHOR}', ')',
2758 str_replace('{OPEN_SQR}', '[',
2759 str_replace('{CLOSE_SQR}', ']',
2760 str_replace('{PER}', '%',
2764 // Return compiled code
2768 // Function taken from user comments on www.php.net / function eregi()
2769 function isUrlValidSimple ($url) {
2771 $url = strip_tags(str_replace("\\", '', COMPILE_CODE(urldecode($url))));
2773 // Allows http and https
2774 $http = "(http|https)+(:\/\/)";
2776 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2777 // Test double-domains (e.g. .de.vu)
2778 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2780 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2782 $dir = "((/)+([-_\.[:alnum:]])+)*";
2784 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2785 // ... and the string after and including question character
2786 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2787 // Pattern for URLs like http://url/dir/doc.html?var=value
2788 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2789 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2790 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2791 // Pattern for URLs like http://url/dir/?var=value
2792 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2793 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2794 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2795 // Pattern for URLs like http://url/dir/page.ext
2796 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2797 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2798 $pattern['ipdp'] = $http . $ip . $dir . $page;
2799 // Pattern for URLs like http://url/dir
2800 $pattern['d1d'] = $http . $domain1 . $dir;
2801 $pattern['d2d'] = $http . $domain2 . $dir;
2802 $pattern['ipd'] = $http . $ip . $dir;
2803 // Pattern for URLs like http://url/?var=value
2804 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2805 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2806 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2807 // Pattern for URLs like http://url?var=value
2808 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2809 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2810 $pattern['ipg12'] = $http . $ip . $getstring1;
2811 // Test all patterns
2813 foreach ($pattern as $key => $pat) {
2815 if (isDebugRegExpressionEnabled()) {
2816 // @TODO Are these convertions still required?
2817 $pat = str_replace('.', "\.", $pat);
2818 $pat = str_replace('@', "\@", $pat);
2819 echo $key."= " . $pat . "<br />";
2822 // Check if expression matches
2823 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2826 if ($reg === true) break;
2829 // Return true/false
2833 // Wtites data to a config.php-style file
2834 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2835 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2836 // Initialize some variables
2842 // Is the file there and read-/write-able?
2843 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2844 $search = 'CFG: ' . $comment;
2845 $tmp = $FQFN . '.tmp';
2847 // Open the source file
2848 $fp = fopen($FQFN, 'r') or OUTPUT_HTML('<strong>READ:</strong> ' . $FQFN . "<br />\n");
2850 // Is the resource valid?
2851 if (is_resource($fp)) {
2852 // Open temporary file
2853 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('<strong>WRITE:</strong> ' . $tmp . "<br />\n");
2855 // Is the resource again valid?
2856 if (is_resource($fp_tmp)) {
2857 while (!feof($fp)) {
2858 // Read from source file
2859 $line = fgets ($fp, 1024);
2861 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2864 if ($next === $seek) {
2866 $line = $prefix . $DATA . $suffix . "\n";
2872 // Write to temp file
2873 fputs($fp_tmp, $line);
2879 // Finished writing tmp file
2883 // Close source file
2886 if (($done === true) && ($found === true)) {
2887 // Copy back tmp file and delete tmp :-)
2888 copyFileVerified($tmp, $FQFN, 0644);
2889 return removeFile($tmp);
2890 } elseif ($found === false) {
2891 OUTPUT_HTML('<strong>CHANGE:</strong> 404!');
2893 OUTPUT_HTML('<strong>TMP:</strong> UNDONE!');
2897 // File not found, not readable or writeable
2898 OUTPUT_HTML('<strong>404:</strong> ' . $FQFN . '<br />');
2901 // An error was detected!
2904 // Send notification to admin
2905 function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
2906 if (GET_EXT_VERSION('admins') >= '0.4.1') {
2908 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2910 // Send out out-dated way
2911 $message = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2912 SEND_ADMIN_EMAILS($subject, $message);
2916 // Debug message logger
2917 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
2918 // Is debug mode enabled?
2919 if ((isDebugModeEnabled()) || ($force === true)) {
2921 $message = str_replace("\r", '', str_replace("\n", '', $message));
2923 // Log this message away
2924 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
2925 fwrite($fp, date("d.m.Y|H:i:s", time())."|" . getModule()."|".basename($funcFile)."|" . $line."|".strip_tags($message)."\n");
2930 // Load more reset scripts
2931 function runResetIncludes () {
2932 // Is the reset set or old sql_patches?
2933 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
2935 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
2938 // Get more daily reset scripts
2939 SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
2942 if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
2944 // Is the config entry set?
2945 if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
2946 // Create current week mark
2947 $currWeek = date('W', time());
2950 if (getConfig('last_week') != $currWeek) {
2951 // Include weekly reset scripts
2952 MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
2955 if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
2958 // Create current month mark
2959 $currMonth = date('m', time());
2962 if (getConfig('last_month') != $currMonth) {
2963 // Include monthly reset scripts
2964 MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
2967 if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
2972 runFilterChain('load_includes');
2975 // Handle extra values
2976 function handleExtraValues ($filterFunction, $value, $extraValue) {
2977 // Default is the value itself
2980 // Do we have a special filter function?
2981 if (!empty($filterFunction)) {
2982 // Does the filter function exist?
2983 if (function_exists($filterFunction)) {
2984 // Do we have extra parameters here?
2985 if (!empty($extraValue)) {
2986 // Put both parameters in one new array by default
2987 $args = array($value, $extraValue);
2989 // If we have an array simply use it and pre-extend it with our value
2990 if (is_array($extraValue)) {
2991 // Make the new args array
2992 $args = merge_array(array($value), $extraValue);
2995 // Call the multi-parameter call-back
2996 $ret = call_user_func_array($filterFunction, $args);
2998 // One parameter call
2999 $ret = call_user_func($filterFunction, $value);
3008 // Converts timestamp selections into a timestamp
3009 function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
3010 // Init test variable
3013 // Get last three chars
3014 $test = substr($id, -3);
3016 // Improved way of checking! :-)
3017 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3018 // Found a multi-selection for timings?
3019 $test = substr($id, 0, -3);
3020 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)) {
3021 // Generate timestamp
3022 $POST[$test] = createTimestampFromSelections($test, $POST);
3023 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3025 // Remove data from array
3026 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3027 unset($POST[$test.'_' . $rem]);
3031 unset($id); $skip = true; $test2 = $test;
3034 // Process this entry
3040 // Reverts the german decimal comma into Computer decimal dot
3041 function convertCommaToDot ($str) {
3042 // Default float is not a float... ;-)
3045 // Which language is selected?
3046 switch (getLanguage()) {
3047 case 'de': // German language
3048 // Remove german thousand dots first
3049 $str = str_replace('.', '', $str);
3051 // Replace german commata with decimal dot and cast it
3052 $float = (float)str_replace(',', '.', $str);
3055 default: // US and so on
3056 // Remove thousand dots first and cast
3057 $float = (float)str_replace(',', '', $str);
3065 // Handle menu-depending failed logins and return the rendered content
3066 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3067 // Default output is empty ;-)
3070 // Is the session data set?
3071 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3072 // Ignore zero values
3073 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3074 // Non-guest has login failures found, get both data and prepare it for template
3075 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3077 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3078 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), '2')
3082 $OUT = LOAD_TEMPLATE('login_failures', true, $content);
3085 // Reset session data
3086 setSession('mxchange_' . $accessLevel.'_failures', '');
3087 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3090 // Return rendered content
3095 function rebuildCacheFiles ($cache, $inc = '') {
3096 // Shall I remove the cache file?
3097 if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
3099 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3101 $GLOBALS['cache_instance']->destroyCacheFile();
3104 // Include file given?
3107 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3109 // Is the include there?
3110 if (isIncludeReadable($INC)) {
3111 // And rebuild it from scratch
3112 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3115 // Include not found!
3116 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3122 // Purge admin menu cache
3123 function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
3124 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3125 if (!EXT_IS_ACTIVE('cache')) {
3126 // Cache extension not active
3128 } elseif (!isCacheInstanceValid()) {
3129 // No cache instance!
3130 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3132 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
3133 // Caching disabled (currently experiemental!)
3137 // Experiemental feature!
3138 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3141 // Determines the real remote address
3142 function determineRealRemoteAddress () {
3143 // Is a proxy in use?
3144 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
3146 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3147 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
3148 // Yet, another proxy
3149 $address = $_SERVER['HTTP_CLIENT_IP'];
3151 // The regular address when no proxy was used
3152 $address = $_SERVER['REMOTE_ADDR'];
3155 // This strips out the real address from proxy output
3156 if (strstr($address, ',')){
3157 $addressArray = explode(',', $address);
3158 $address = $addressArray[0];
3161 // Return the result
3165 // Adds a bonus mail to the queue
3166 // This is a high-level function!
3167 function addNewBonusMail ($data, $mode = '', $output=true) {
3168 // Use mode from data if not set and availble ;-)
3169 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3171 // Generate receiver list
3172 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3175 if (!empty($RECEIVER)) {
3176 // Add bonus mail to queue
3177 addBonusMailToQueue(
3189 // Mail inserted into bonus pool
3190 if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3191 } elseif ($output) {
3192 // More entered than can be reached!
3193 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3196 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3200 // Determines referal id and sets it
3201 function DETERMINE_REFID () {
3202 // Check if refid is set
3203 if ((REQUEST_ISSET_GET('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3204 // The variable user comes from the click-counter script click.php and we only accept this here
3205 $GLOBALS['refid'] = bigintval(REQUEST_GET('user'));
3206 } elseif (REQUEST_ISSET_POST('refid')) {
3207 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3208 $GLOBALS['refid'] = strip_tags(REQUEST_POST('refid'));
3209 } elseif (REQUEST_ISSET_GET('refid')) {
3210 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3211 $GLOBALS['refid'] = strip_tags(REQUEST_GET('refid'));
3212 } elseif (REQUEST_ISSET_GET('ref')) {
3213 // Set refid=ref (the referal link uses such variable)
3214 $GLOBALS['refid'] = strip_tags(REQUEST_GET('ref'));
3215 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3216 // Set session refid als global
3217 $GLOBALS['refid'] = bigintval(getSession('refid'));
3218 } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
3219 // Set default refid as refid in URL
3220 $GLOBALS['refid'] = getConfig(('def_refid'));
3221 } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
3222 // Select a random user which has confirmed enougth mails
3223 $GLOBALS['refid'] = determineRandomReferalId();
3225 // No default ID when sql_patches is not installed or none set
3226 $GLOBALS['refid'] = 0;
3229 // Set cookie when default refid > 0
3230 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3232 setSession('refid', $GLOBALS['refid']);
3235 // Return determined refid
3236 return $GLOBALS['refid'];
3239 // Enables the reset mode. Only call this function if you really want the
3241 function enableResetMode () {
3242 // Enable the reset mode
3243 $GLOBALS['reset_enabled'] = true;
3246 runFilterChain('reset_enabled');
3249 // Our shutdown-function
3250 function shutdown () {
3251 // Call the filter chain 'shutdown'
3252 runFilterChain('shutdown', null, false);
3254 if (SQL_IS_LINK_UP()) {
3256 SQL_CLOSE(__FILE__, __LINE__);
3257 } elseif ((!isInstalling()) && (isInstalled())) {
3259 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3262 // Stop executing here
3266 // Setter for userid
3267 function setUserId ($userid) {
3268 $GLOBALS['userid'] = bigintval($userid);
3271 // Getter for userid or returns zero
3272 function getUserId () {
3276 // Is the userid set?
3277 if (isUserIdSet()) {
3279 $userid = $GLOBALS['userid'];
3286 // Checks ether the userid is set
3287 function isUserIdSet () {
3288 return (isset($GLOBALS['userid']));
3291 // Handle message codes from URL
3292 function handleCodeMessage () {
3293 if (REQUEST_ISSET_GET('msg')) {
3294 // Default extension is 'unknown'
3297 // Is extension given?
3298 if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
3300 // Convert the 'msg' parameter from URL to a human-readable message
3301 $message = convertCodeToMessage(REQUEST_GET('msg'));
3303 // Load message template
3304 LOAD_TEMPLATE('message', false, $message);
3308 // Setter for extra title
3309 function setExtraTitle ($extraTitle) {
3310 $GLOBALS['extra_title'] = $extraTitle;
3313 // Getter for extra title
3314 function getExtraTitle () {
3315 // Is the extra title set?
3316 if (!isExtraTitleSet()) {
3317 // No, then abort here
3318 debug_report_bug('extra_title is not set!');
3322 return $GLOBALS['extra_title'];
3325 // Checks if the extra title is set
3326 function isExtraTitleSet () {
3327 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3330 // Generates a 'extension foo inactive' message
3331 function generateExtensionInactiveMessage ($ext_name) {
3332 // Is the extension empty?
3333 if (empty($ext_name)) {
3334 // This should not happen
3335 trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3339 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3341 // Is an admin logged in?
3343 // Then output admin message
3344 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3347 // Return prepared message
3351 // Generates a 'extension foo not installed' message
3352 function generateExtensionNotInstalledMessage ($ext_name) {
3353 // Is the extension empty?
3354 if (empty($ext_name)) {
3355 // This should not happen
3356 trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3360 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3362 // Is an admin logged in?
3364 // Then output admin message
3365 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3368 // Return prepared message
3372 // Generates a message depending on if the extension is not installed or not
3374 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3378 // Is the extension not installed or just deactivated?
3379 switch (isExtensionInstalled($ext_name)) {
3380 case true; // Deactivated!
3381 $message = generateExtensionInactiveMessage($ext_name);
3384 case false; // Not installed!
3385 $message = generateExtensionNotInstalledMessage($ext_name);
3388 default: // Should not happen!
3389 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3390 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3394 // Return the message
3398 //////////////////////////////////////////////////
3399 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3400 //////////////////////////////////////////////////
3402 if (!function_exists('html_entity_decode')) {
3403 // Taken from documentation on www.php.net
3404 function html_entity_decode ($string) {
3405 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3406 $trans_tbl = array_flip($trans_tbl);
3407 return strtr($string, $trans_tbl);