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 // Prepare the content and eval() it...
125 $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
128 // Was that eval okay?
129 if (empty($newContent)) {
130 // Something went wrong!
131 app_die(__FUNCTION__, __LINE__, "Evaluation error:<pre>".htmlentities($eval)."</pre>");
133 $OUTPUT = $newContent;
136 // Output code here, DO NOT REMOVE! ;-)
137 outputRawCode($OUTPUT);
138 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($OUTPUT))) {
139 // Rewrite links when rewrite extension is active
140 if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
141 $OUTPUT = rewriteLinksInCode($OUTPUT);
144 // Compile and run finished rendered HTML code
145 while (strpos($OUTPUT, '{!') > 0) {
146 $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
150 // Output code here, DO NOT REMOVE! ;-)
151 outputRawCode($OUTPUT);
155 // Output the raw HTML code
156 function outputRawCode ($HTML) {
157 // Output stripped HTML code to avoid broken JavaScript code, etc.
158 echo stripslashes(stripslashes($HTML));
160 // Flush the output if only constant('_OB_CACHING') is not 'on'
161 if (constant('_OB_CACHING') != 'on') {
167 // Init fatal message array
168 function initFatalMessages () {
169 $GLOBALS['fatal_messages'] = array();
172 // Getter for whole fatal error messages
173 function getFatalArray () {
174 return $GLOBALS['fatal_messages'];
177 // Add a fatal error message to the queue array
178 function addFatalMessage ($F, $L, $message, $extra='') {
179 if (is_array($extra)) {
180 // Multiple extras for a message with masks
181 $message = call_user_func_array('sprintf', $extra);
182 } elseif (!empty($extra)) {
183 // $message is text with a mask plus extras to insert into the text
184 $message = sprintf($message, $extra);
187 // Add message to $GLOBALS['fatal_messages']
188 $GLOBALS['fatal_messages'][] = $message;
190 // Log fatal messages away
191 DEBUG_LOG($F, $L, " message={$message}");
194 // Getter for total fatal message count
195 function getTotalFatalErrors () {
199 // Do we have at least the first entry?
200 if (!empty($GLOBALS['fatal_messages'][0])) {
202 $count = count($GLOBALS['fatal_messages']);
209 // Load a template file and return it's content (only it's name; do not use ' or ")
210 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
211 // @TODO Remove this sanity-check if all is fine
212 if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
214 // Add more variables which you want to use in your template files
215 global $DATA, $username;
217 // Get whole config array
218 $_CONFIG = getConfigArray();
220 // Make all template names lowercase
221 $template = strtolower($template);
223 // Count the template load
224 incrementConfigEntry('num_templates');
226 // Prepare IP number and User Agent
227 $REMOTE_ADDR = detectRemoteAddr();
228 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
229 $HTTP_USER_AGENT = detectUserAgent();
233 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
235 // @DEPRECATED Try to rewrite the if() condition
236 if ($template == 'member_support_form') {
237 // Support request of a member
238 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
239 array(getUserId()), __FUNCTION__, __LINE__);
241 // Is content an array?
242 if (is_array($content)) {
244 $content = merge_array($content, SQL_FETCHARRAY($result));
247 $content['gender'] = translateGender($content['gender']);
250 // @TODO Fine all templates which are using these direct variables and rewrite them.
251 // @TODO After this step is done, this else-block is history
252 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
255 $gender = translateGender($gender);
256 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
260 SQL_FREERESULT($result);
263 // Generate date/time string
264 $date_time = generateDateTime(time(), '1');
267 $basePath = sprintf("%stemplates/%s/html/", constant('PATH'), getLanguage());
270 // Check for admin/guest/member templates
271 if (strpos($template, 'admin_') > -1) {
272 // Admin template found
274 } elseif (strpos($template, 'guest_') > -1) {
275 // Guest template found
277 } elseif (strpos($template, 'member_') > -1) {
278 // Member template found
280 } elseif (strpos($template, 'install_') > -1) {
281 // Installation template found
283 } elseif (strpos($template, 'ext_') > -1) {
284 // Extension template found
286 } elseif (strpos($template, 'la_') > -1) {
287 // 'Logical-area' template found
290 // Test for extension
291 $test = substr($template, 0, strpos($template, '_'));
292 if (EXT_IS_ACTIVE($test)) {
293 // Set extra path to extension's name
298 ////////////////////////
299 // Generate file name //
300 ////////////////////////
301 $FQFN = $basePath . $mode . $template . '.tpl';
303 if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
304 // Select what depended header/footer template file for admin/guest/member area
305 $file2 = sprintf("%s%s%s_%s.tpl",
313 if (isFileReadable($file2)) $FQFN = $file2;
315 // Remove variable from memory
319 // Does the special template exists?
320 if (!isFileReadable($FQFN)) {
321 // Reset to default template
322 $FQFN = $basePath . $template . '.tpl';
325 // Now does the final template exists?
326 if (isFileReadable($FQFN)) {
327 // The local file does exists so we load it. :)
328 $tmpl_file = readFromFile($FQFN);
330 // Replace ' to our own chars to preventing them being quoted
331 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
333 // Do we have to compile the code?
335 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
337 $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
340 // Simply return loaded code
344 // Add surrounding HTML comments to help finding bugs faster
345 $ret = "<!-- Template " . $template . " - Start -->\n" . $ret . "<!-- Template " . $template . " - End -->\n";
346 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
347 // Only admins shall see this warning or when installation mode is active
348 $ret = "<br /><span class=\"guest_failed\">{--TEMPLATE_404--}</span><br />
349 (".basename($FQFN).")<br />
351 {--TEMPLATE_CONTENT--}
352 <pre>".print_r($content, true)."</pre>
354 <pre>".print_r($DATA, true)."</pre>
358 // Remove content and data
362 // Do we have some content to output or return?
364 // Not empty so let's put it out! ;)
365 if ($return === true) {
366 // Return the HTML code
372 } elseif (isDebugModeEnabled()) {
373 // Warning, empty output!
374 return "E:" . $template."<br />\n";
378 // Send mail out to an email address
379 function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '') {
380 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />\n";
382 // Compile subject line (for POINTS constant etc.)
383 $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
387 if ((!eregi("@", $toEmail)) && ($toEmail > 0)) {
388 // Value detected, is the message extension installed?
389 if (EXT_IS_ACTIVE("msg")) {
390 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
393 // Load email address
394 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($toEmail)), __FUNCTION__, __LINE__);
395 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
397 // Does the user exist?
398 if (SQL_NUMROWS($result_email)) {
399 // Load email address
400 list($toEmail) = SQL_FETCHROW($result_email);
403 $toEmail = constant('WEBMASTER');
407 SQL_FREERESULT($result_email);
409 } elseif ($toEmail == '0') {
411 $toEmail = constant('WEBMASTER');
413 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
415 // Check for PHPMailer or debug-mode
416 if (!checkPhpMailerUsage()) {
417 // Not in PHPMailer-Mode
418 if (empty($mailHeader)) {
419 // Load email header template
420 $mailHeader = LOAD_EMAIL_TEMPLATE('header');
423 $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
425 } elseif (isDebugModeEnabled()) {
426 if (empty($mailHeader)) {
427 // Load email header template
428 $mailHeader = LOAD_EMAIL_TEMPLATE('header');
431 $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
436 $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
440 $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
443 // Fix HTML parameter (default is no!)
444 if (empty($HTML)) $HTML = 'N';
445 if (isDebugModeEnabled()) {
446 // In debug mode we want to display the mail instead of sending it away so we can debug this part
448 ".htmlentities(trim($mailHeader))."
450 Subject : " . $subject."
451 Message : " . $message."
453 } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE('html_mail'))) {
454 // Send mail as HTML away
455 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
456 } elseif (!empty($toEmail)) {
458 sendRawEmail($toEmail, $subject, $message, $mailHeader);
459 } elseif ($HTML == 'N') {
461 sendRawEmail(constant('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
465 // Check if legacy or PHPMailer command
466 // @TODO Rewrite this to an extension 'smtp'
468 function checkPhpMailerUsage() {
469 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
472 // Send out a raw email with PHPMailer class or legacy mail() command
473 function sendRawEmail ($toEmail, $subject, $message, $from) {
474 // Shall we use PHPMailer class or legacy mode?
475 if (checkPhpMailerUsage()) {
476 // Use PHPMailer class with SMTP enabled
477 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
478 loadIncludeOnce('inc/phpmailer/class.smtp.php');
481 $mail = new PHPMailer();
482 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
485 $mail->SMTPAuth = true;
486 $mail->Host = getConfig('SMTP_HOSTNAME');
488 $mail->Username = getConfig('SMTP_USER');
489 $mail->Password = getConfig('SMTP_PASSWORD');
491 $mail->From = constant('WEBMASTER');
495 $mail->FromName = constant('MAIN_TITLE');
496 $mail->Subject = $subject;
497 if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($message) != $message)) {
498 $mail->Body = $message;
499 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
500 $mail->WordWrap = 70;
503 $mail->Body = decodeEntities($message);
505 $mail->AddAddress($toEmail, '');
506 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
507 $mail->AddCustomHeader('Errors-To:' . constant('WEBMASTER'));
508 $mail->AddCustomHeader('X-Loop:' . constant('WEBMASTER'));
511 // Use legacy mail() command
512 mail($toEmail, $subject, decodeEntities($message), $from);
516 // Generate a password in a specified length or use default password length
517 function generatePassword ($LEN = 0) {
518 // Auto-fix invalid length of zero
519 if ($LEN == 0) $LEN = getConfig('pass_len');
521 // Initialize array with all allowed chars
522 $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,-,+,_,/');
524 // Start creating password
526 for ($i = 0; $i < $LEN; $i++) {
527 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
530 // When the size is below 40 we can also add additional security by scrambling
531 // it. Otherwise we may corrupt hashes
532 if (strlen($PASS) <= 40) {
533 // Also scramble the password
534 $PASS = scrambleString($PASS);
537 // Return the password
541 // Generates a human-readable timestamp from the Uni* stamp
542 function generateDateTime ($time, $mode = '0') {
543 // Filter out numbers
544 $time = bigintval($time);
546 // If the stamp is zero it mostly didn't "happen"
549 return getMessage('NEVER_HAPPENED');
552 switch (getLanguage())
554 case 'de': // German date / time format
556 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
557 case '1': $ret = strtolower(date("d.m.Y - H:i", $time)); break;
558 case '2': $ret = date("d.m.Y|H:i", $time); break;
559 case '3': $ret = date("d.m.Y", $time); break;
561 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
566 default: // Default is the US date / time format!
568 case '0': $ret = date("r", $time); break;
569 case '1': $ret = date("Y-m-d - g:i A", $time); break;
570 case '2': $ret = date("y-m-d|H:i", $time); break;
571 case '3': $ret = date("y-m-d", $time); break;
573 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
580 // Translates Y/N to yes/no
581 function translateYesNo ($yn) {
583 $translated = "??? (" . $yn.')';
585 case 'Y': $translated = getMessage('YES'); break;
586 case 'N': $translated = getMessage('NO'); break;
589 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
597 // Translates the "pool type" into human-readable
598 function translatePoolType ($type) {
599 // Default?type is unknown
600 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
603 $constName = sprintf("POOL_TYPE_%s", $type);
606 if (defined($constName)) {
608 $translated = getMessage($constName);
611 // Return "translation"
615 // Translates the american decimal dot into a german comma
616 function translateComma ($dotted, $cut = true, $max = 0) {
617 // Default is 3 you can change this in admin area "Misc -> Misc Options"
618 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
620 // Use from config is default
621 $maxComma = getConfig('max_comma');
623 // Use from parameter?
624 if ($max > 0) $maxComma = $max;
627 if (($cut) && ($max == 0)) {
628 // Test for commata if in cut-mode
629 $com = explode('.', $dotted);
630 if (count($com) < 2) {
631 // Don't display commatas even if there are none... ;-)
637 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
640 switch (getLanguage()) {
642 $dotted = number_format($dotted, $maxComma, ',', '.');
646 $dotted = number_format($dotted, $maxComma, '.', ',');
650 // Return translated value
654 // Translate Uni*-like gender to human-readable
655 function translateGender ($gender) {
657 $ret = '!' . $gender . '!';
659 // Male/female or company?
661 case 'M': $ret = getMessage('GENDER_M'); break;
662 case 'F': $ret = getMessage('GENDER_F'); break;
663 case 'C': $ret = getMessage('GENDER_C'); break;
665 // Log unknown gender
666 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
670 // Return translated gender
674 // "Translates" the user status
675 function translateUserStatus ($status) {
681 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
686 $ret = getMessage('ACCOUNT_DELETED');
690 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
691 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
699 // Generates an URL for the dereferer
700 function DEREFERER ($URL) {
701 // Don't de-refer our own links!
702 if (substr($URL, 0, strlen(constant('URL'))) != constant('URL')) {
703 // De-refer this link
704 $URL = 'modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
711 // Generates an URL for the frametester
712 function FRAMETESTER ($URL) {
713 // Prepare frametester URL
714 $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&url=%s",
715 encodeString(compileUriCode($URL))
717 return $frametesterUrl;
720 // Count entries from e.g. a selection box
721 function countSelection ($array) {
723 if (is_array($array)) {
724 foreach ($array as $key => $selected) {
725 if (!empty($selected)) $ret++;
731 // Generate XHTML code for the CAPTCHA
732 function generateCaptchaCode ($code, $type, $DATA, $uid) {
733 return '<IMG border="0" alt="Code" src="{!URL!}/mailid_top.php?uid=' . $uid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
736 // Loads an email template and compiles it
737 function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
740 // Our configuration is kept non-global here
741 $_CONFIG = getConfigArray();
743 // Make sure all template names are lowercase!
744 $template = strtolower($template);
746 // Default 'nickname' if extension is not installed
749 // Prepare IP number and User Agent
750 $REMOTE_ADDR = detectRemoteAddr();
751 $HTTP_USER_AGENT = detectUserAgent();
754 $ADMIN = constant('MAIN_TITLE');
756 // Is the admin logged in?
759 $aid = getCurrentAdminId();
762 $ADMIN = getAdminEmail($aid);
765 // Neutral email address is default
766 $email = constant('WEBMASTER');
768 // Expiration in a nice output format
769 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
770 if (getConfig('auto_purge') == 0) {
771 // Will never expire!
772 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
774 // Create nice date string
775 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
778 // Is content an array?
779 if (is_array($content)) {
780 // Add expiration to array, $EXPIRATION is now deprecated!
781 $content['expiration'] = $EXPIRATION;
785 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
786 if (($UID > 0) && (is_array($content))) {
787 // If nickname extension is installed, fetch nickname as well
788 if (EXT_IS_ACTIVE('nickname')) {
789 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
791 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
792 array(bigintval($UID)), __FUNCTION__, __LINE__);
794 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
796 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
797 array(bigintval($UID)), __FUNCTION__, __LINE__);
800 // Fetch and merge data
801 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
802 $content = merge_array($content, SQL_FETCHARRAY($result));
803 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
806 SQL_FREERESULT($result);
809 // Translate M to male or F to female if present
810 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
812 // Overwrite email from data if present
813 if (isset($content['email'])) $email = $content['email'];
815 // Store email for some functions in global data array
816 $DATA['email'] = $email;
819 $basePath = sprintf("%stemplates/%s/emails/", constant('PATH'), getLanguage());
821 // Check for admin/guest/member templates
822 if (strpos($template, 'admin_') > -1) {
823 // Admin template found
824 $FQFN = $basePath.'admin/' . $template.'.tpl';
825 } elseif (strpos($template, 'guest_') > -1) {
826 // Guest template found
827 $FQFN = $basePath.'guest/' . $template.'.tpl';
828 } elseif (strpos($template, 'member_') > -1) {
829 // Member template found
830 $FQFN = $basePath.'member/' . $template.'.tpl';
832 // Test for extension
833 $test = substr($template, 0, strpos($template, '_'));
834 if (EXT_IS_ACTIVE($test)) {
835 // Set extra path to extension's name
836 $FQFN = $basePath . $test.'/' . $template.'.tpl';
838 // No special filename
839 $FQFN = $basePath . $template.'.tpl';
843 // Does the special template exists?
844 if (!isFileReadable($FQFN)) {
845 // Reset to default template
846 $FQFN = $basePath . $template.'.tpl';
849 // Now does the final template exists?
851 if (isFileReadable($FQFN)) {
852 // The local file does exists so we load it. :)
853 $tmpl_file = readFromFile($FQFN);
854 $tmpl_file = SQL_ESCAPE($tmpl_file);
857 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
859 } elseif (!empty($template)) {
860 // Template file not found!
861 $newContent = "{--TEMPLATE_404--}: " . $template."<br />
862 {--TEMPLATE_CONTENT--}
863 <pre>".print_r($content, true)."</pre>
865 <pre>".print_r($DATA, true)."</pre>
868 // Debug mode not active? Then remove the HTML tags
869 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
871 // No template name supplied!
872 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
875 // Is there some content?
876 if (empty($newContent)) {
878 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $tmpl_file;
879 // Add last error if the required function exists
880 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
883 // Remove content and data
887 // Return compiled content
888 return COMPILE_CODE($newContent);
891 // Generates a timestamp (some wrapper for mktime())
892 function makeTime ($H, $M, $S, $stamp) {
893 // Extract day, month and year from given timestamp
894 $day = date('d', $stamp);
895 $month = date('m', $stamp);
896 $year = date('Y', $stamp);
898 // Create timestamp for wished time which depends on extracted date
899 return mktime($H, $M, $S, $month, $day, $year);
902 // Redirects to an URL and if neccessarry extends it with own base URL
903 function redirectToUrl ($URL) {
904 // Compile out URI codes
905 $URL = compileUriCode($URL);
907 // Check if http(s):// is there
908 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
909 // Make all URLs full-qualified
910 $URL = constant('URL') . '/' . $URL;
913 // Three different debug ways...
914 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
915 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
916 //* DEBUG: */ die($URL);
918 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
919 $rel = ' rel="external"';
921 // Do we have internal or external URL?
922 if (substr($URL, 0, strlen(constant('URL'))) == constant('URL')) {
923 // Own (=internal) URL
928 $OUTPUT = ob_get_contents();
930 // Clear it only if there is content
931 if (!empty($OUTPUT)) {
935 // Simple probe for bots/spiders from search engines
936 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
937 // Secure the URL against bad things such als HTML insertions and so on...
938 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
940 // Output new location link as anchor
941 OUTPUT_HTML('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
942 } elseif (!headers_sent()) {
943 // Load URL when headers are not sent
944 //* DEBUG: */ debug_report_bug("URL={$URL}");
945 sendHeader('Location: '.str_replace('&', '&', $URL));
947 // Output error message
948 loadInclude('inc/header.php');
949 LOAD_TEMPLATE('redirect_url', false, str_replace('&', '&', $URL));
950 loadInclude('inc/footer.php');
953 // Shut the mailer down here
957 // Wrapper for redirectToUrl but URL comes from a configuration entry
958 function redirectToConfiguredUrl ($configEntry) {
960 $URL = getConfig($configEntry);
965 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
973 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
974 // Is the code a string?
975 if (!is_string($code)) {
976 // Silently return it
980 // Init replacement-array with full security characters
981 $secChars = $GLOBALS['security_chars'];
983 // Select smaller set of chars to replace when we e.g. want to compile URLs
984 if (!$full) $secChars = $GLOBALS['url_chars'];
987 if ($constants === true) {
988 // BEFORE 0.2.1 : Language and data constants
989 // WITH 0.2.1+ : Only language constants
990 $code = str_replace('{--','".', str_replace('--}','."', $code));
992 // BEFORE 0.2.1 : Not used
993 // WITH 0.2.1+ : Data constants
994 $code = str_replace('{!','".', str_replace("!}", '."', $code));
997 // Compile QUOT and other non-HTML codes
998 foreach ($secChars['to'] as $k => $to) {
999 // Do the reversed thing as in inc/libs/security_functions.php
1000 $code = str_replace($to, $secChars['from'][$k], $code);
1003 // But shall I keep simple quotes for later use?
1004 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1006 // Find $content[bla][blub] entries
1007 preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1009 // Are some matches found?
1010 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1011 // Replace all matches
1012 $matchesFound = array();
1013 foreach ($matches[0] as $key => $match) {
1014 // Fuzzy look has failed by default
1015 $fuzzyFound = false;
1017 // Fuzzy look on match if already found
1018 foreach ($matchesFound as $found => $set) {
1020 $test = substr($found, 0, strlen($match));
1022 // Does this entry exist?
1023 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1024 if ($test == $match) {
1026 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1033 if ($fuzzyFound) continue;
1035 // Take all string elements
1036 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1037 // Replace it in the code
1038 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1039 $newMatch = str_replace("[" . $matches[4][$key]."]", "['" . $matches[4][$key]."']", $match);
1040 $code = str_replace($match, "\"." . $newMatch.".\"", $code);
1041 $matchesFound[$key."_" . $matches[4][$key]] = 1;
1042 $matchesFound[$match] = 1;
1043 } elseif (!isset($matchesFound[$match])) {
1044 // Not yet replaced!
1045 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1046 $code = str_replace($match, "\"." . $match.".\"", $code);
1047 $matchesFound[$match] = 1;
1052 // Return compiled code
1056 /************************************************************************
1058 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1059 * $a_sort sortiert: *
1061 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1062 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1063 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1064 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1065 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1067 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1068 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1069 * Sie, dass es doch nicht so schwer ist! :-) *
1071 ************************************************************************/
1072 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1074 while ($primary_key < count($a_sort)) {
1075 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1076 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1079 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1080 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1081 } elseif ($key != $key2) {
1082 // Sort numbers (E.g.: 9 < 10)
1083 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1084 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1088 // We have found two different values, so let's sort whole array
1089 foreach ($dummy as $sort_key => $sort_val) {
1090 $t = $dummy[$sort_key][$key];
1091 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1092 $dummy[$sort_key][$key2] = $t;
1103 // Write back sorted array
1108 function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
1111 if ($type == 'yn') {
1112 // This is a yes/no selection only!
1113 if ($id > 0) $prefix .= "[" . $id."]";
1114 $OUT .= " <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
1116 // Begin with regular selection box here
1117 if (!empty($prefix)) $prefix .= "_";
1119 if ($id > 0) $type2 .= "[" . $id."]";
1120 $OUT .= " <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
1125 for ($idx = 1; $idx < 32; $idx++) {
1126 $OUT .= "<option value=\"" . $idx."\"";
1127 if ($default == $idx) $OUT .= ' selected="selected"';
1128 $OUT .= ">" . $idx."</option>\n";
1132 case "month": // Month
1133 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1134 $OUT .= "<option value=\"" . $month."\"";
1135 if ($default == $month) $OUT .= ' selected="selected"';
1136 $OUT .= ">" . $descr."</option>\n";
1140 case "year": // Year
1142 $year = date('Y', time());
1144 // Use configured min age or fixed?
1145 if (GET_EXT_VERSION('other') >= '0.2.1') {
1147 $startYear = $year - getConfig('min_age');
1150 $startYear = $year - 16;
1153 // Calculate earliest year (100 years old people can still enter Internet???)
1154 $minYear = $year - 100;
1156 // Check if the default value is larger than minimum and bigger than actual year
1157 if (($default > $minYear) && ($default >= $year)) {
1158 for ($idx = $year; $idx < ($year + 11); $idx++) {
1159 $OUT .= "<option value=\"" . $idx."\"";
1160 if ($default == $idx) $OUT .= ' selected="selected"';
1161 $OUT .= ">" . $idx."</option>\n";
1163 } elseif ($default == -1) {
1164 // Current year minus 1
1165 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1167 $OUT .= "<option value=\"" . $idx."\">" . $idx."</option>\n";
1170 // Get current year and subtract the configured minimum age
1171 $OUT .= "<option value=\"".($minYear - 1)."\"><" . $minYear."</option>\n";
1172 // Calculate earliest year depending on extension version
1173 if (GET_EXT_VERSION('other') >= '0.2.1') {
1174 // Use configured minimum age
1175 $year = date('Y', time()) - getConfig('min_age');
1177 // Use fixed 16 years age
1178 $year = date('Y', time()) - 16;
1181 // Construct year selection list
1182 for ($idx = $minYear; $idx <= $year; $idx++) {
1183 $OUT .= "<option value=\"" . $idx."\"";
1184 if ($default == $idx) $OUT .= ' selected="selected"';
1185 $OUT .= ">" . $idx."</option>\n";
1192 for ($idx = 0; $idx < 60; $idx+=5) {
1193 if (strlen($idx) == 1) $idx = '0' . $idx;
1194 $OUT .= "<option value=\"" . $idx."\"";
1195 if ($default == $idx) $OUT .= ' selected="selected"';
1196 $OUT .= ">" . $idx."</option>\n";
1201 for ($idx = 0; $idx < 24; $idx++) {
1202 if (strlen($idx) == 1) $idx = '0' . $idx;
1203 $OUT .= "<option value=\"" . $idx."\"";
1204 if ($default == $idx) $OUT .= ' selected="selected"';
1205 $OUT .= ">" . $idx."</option>\n";
1210 $OUT .= "<option value=\"Y\"";
1211 if ($default == 'Y') $OUT .= ' selected="selected"';
1212 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1213 if ($default == 'N') $OUT .= ' selected="selected"';
1214 $OUT .= ">{--NO--}</option>\n";
1217 $OUT .= " </select>\n";
1222 // Deprecated : $length
1225 function generateRandomCode ($length, $code, $uid, $DATA = '') {
1226 // Fix missing _MAX constant
1227 // @TODO Rewrite this unnice code
1228 if (!defined('_MAX')) define('_MAX', 15235);
1230 // Build server string
1231 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH').'inc/databases.php');
1234 $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY');
1235 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1236 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1237 $keys .= getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1238 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1240 // Build string from misc data
1241 $data = $code.getConfig('ENCRYPT_SEPERATOR') . $uid.getConfig('ENCRYPT_SEPERATOR') . $DATA;
1243 // Add more additional data
1244 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('u_hash');
1245 if (isUserIdSet()) $data .= getConfig('ENCRYPT_SEPERATOR').getUserId();
1246 if (isSessionVariableSet('mxchange_theme')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
1247 if (isSessionVariableSet('mx_lang')) $data .= getConfig('ENCRYPT_SEPERATOR').getLanguage();
1248 if (isset($GLOBALS['refid'])) $data .= getConfig('ENCRYPT_SEPERATOR') . $GLOBALS['refid'];
1250 // Calculate number for generating the code
1251 $a = $code + getConfig('_ADD') - 1;
1253 if (isConfigEntrySet('master_hash')) {
1254 // Generate hash with master salt from modula of number with the prime number and other data
1255 $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'));
1257 // Create number from hash
1258 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1260 // Generate hash with "hash of site key" 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, substr(sha1(getConfig('SITE_KEY')), 0, 8));
1263 // Create number from hash
1264 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1267 // At least 10 numbers shall be secure enought!
1268 $len = getConfig('code_length');
1269 if ($len == 0) $len = $length;
1270 if ($len == 0) $len = 10;
1272 // Cut off requested counts of number
1273 $return = substr(str_replace('.', '', $rcode), 0, $len);
1275 // Done building code
1279 // Does only allow numbers
1280 function bigintval ($num, $castValue = true) {
1281 // Filter all numbers out
1282 $ret = preg_replace("/[^0123456789]/", '', $num);
1285 if ($castValue) $ret = (double)$ret;
1287 // Has the whole value changed?
1288 // @TODO Remove this if() block if all is working fine
1289 if ("" . $ret."" != '' . $num."") {
1291 debug_report_bug("{$ret}<>{$num}");
1298 // Insert the code in $img_code into jpeg or PNG image
1299 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1300 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1301 // Stop execution of function here because of over-sized code length
1303 } elseif (!$headerSent) {
1304 // Return in an HTML code code
1305 return "<img src=\"{!URL!}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
1309 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), getCurrentTheme(), getConfig('img_type'));
1310 if (isFileReadable($img)) {
1311 // Switch image type
1312 switch (getConfig('img_type'))
1315 // Okay, load image and hide all errors
1316 $image = @imagecreatefromjpeg($img);
1320 // Okay, load image and hide all errors
1321 $image = @imagecreatefrompng($img);
1325 // Exit function here
1326 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1330 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1331 $text_color = imagecolorallocate($image, 0, 0, 0);
1333 // Insert code into image
1334 imagestring($image, 5, 14, 2, $img_code, $text_color);
1336 // Return to browser
1337 sendHeader('Content-Type: image/' . getConfig('img_type'));
1339 // Output image with matching image factory
1340 switch (getConfig('img_type')) {
1341 case 'jpg': imagejpeg($image); break;
1342 case 'png': imagepng($image); break;
1345 // Remove image from memory
1346 imagedestroy($image);
1348 // Create selection box or array of splitted timestamp
1349 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1350 // Calculate 2-seconds timestamp
1351 $stamp = round($timestamp);
1352 //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1354 // Do we have a leap year?
1356 $TEST = date('Y', time()) / 4;
1357 $M1 = date('m', time());
1358 $M2 = date('m', (time() + $timestamp));
1360 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1361 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1363 // First of all years...
1364 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1365 //* DEBUG: */ print("Y={$Y}<br />\n");
1367 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1368 //* DEBUG: */ print("M={$M}<br />\n");
1370 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1371 //* DEBUG: */ print("W={$W}<br />\n");
1373 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1374 //* DEBUG: */ print("D={$D}<br />\n");
1376 $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));
1377 //* DEBUG: */ print("h={$h}<br />\n");
1379 $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));
1380 //* DEBUG: */ print("m={$m}<br />\n");
1381 // And at last seconds...
1382 $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));
1383 //* DEBUG: */ print("s={$s}<br />\n");
1385 // Is seconds zero and time is < 60 seconds?
1386 if (($s == 0) && ($timestamp < 60)) {
1388 $s = round($timestamp);
1392 // Now we convert them in seconds...
1394 if ($return_array) {
1395 // Just put all data in an array for later use
1407 $OUT = "<div align=\"" . $align."\">\n";
1408 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1411 if (ereg('Y', $display) || (empty($display))) {
1412 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1415 if (ereg("M", $display) || (empty($display))) {
1416 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1419 if (ereg("W", $display) || (empty($display))) {
1420 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1423 if (ereg("D", $display) || (empty($display))) {
1424 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1427 if (ereg("h", $display) || (empty($display))) {
1428 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1431 if (ereg('m', $display) || (empty($display))) {
1432 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1435 if (ereg("s", $display) || (empty($display))) {
1436 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1442 if (ereg('Y', $display) || (empty($display))) {
1443 // Generate year selection
1444 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
1445 for ($idx = 0; $idx <= 10; $idx++) {
1446 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1447 if ($idx == $Y) $OUT .= ' selected="selected"';
1448 $OUT .= ">" . $idx."</option>\n";
1450 $OUT .= " </select></td>\n";
1452 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
1455 if (ereg("M", $display) || (empty($display))) {
1456 // Generate month selection
1457 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
1458 for ($idx = 0; $idx <= 11; $idx++)
1460 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1461 if ($idx == $M) $OUT .= ' selected="selected"';
1462 $OUT .= ">" . $idx."</option>\n";
1464 $OUT .= " </select></td>\n";
1466 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
1469 if (ereg("W", $display) || (empty($display))) {
1470 // Generate week selection
1471 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
1472 for ($idx = 0; $idx <= 4; $idx++) {
1473 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1474 if ($idx == $W) $OUT .= ' selected="selected"';
1475 $OUT .= ">" . $idx."</option>\n";
1477 $OUT .= " </select></td>\n";
1479 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
1482 if (ereg("D", $display) || (empty($display))) {
1483 // Generate day selection
1484 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
1485 for ($idx = 0; $idx <= 31; $idx++) {
1486 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1487 if ($idx == $D) $OUT .= ' selected="selected"';
1488 $OUT .= ">" . $idx."</option>\n";
1490 $OUT .= " </select></td>\n";
1492 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\">\n";
1495 if (ereg("h", $display) || (empty($display))) {
1496 // Generate hour selection
1497 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
1498 for ($idx = 0; $idx <= 23; $idx++) {
1499 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1500 if ($idx == $h) $OUT .= ' selected="selected"';
1501 $OUT .= ">" . $idx."</option>\n";
1503 $OUT .= " </select></td>\n";
1505 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\">\n";
1508 if (ereg('m', $display) || (empty($display))) {
1509 // Generate minute selection
1510 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
1511 for ($idx = 0; $idx <= 59; $idx++) {
1512 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1513 if ($idx == $m) $OUT .= ' selected="selected"';
1514 $OUT .= ">" . $idx."</option>\n";
1516 $OUT .= " </select></td>\n";
1518 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\">\n";
1521 if (ereg("s", $display) || (empty($display))) {
1522 // Generate second selection
1523 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
1524 for ($idx = 0; $idx <= 59; $idx++) {
1525 $OUT .= " <option class=\"mini_select\" value=\"" . $idx."\"";
1526 if ($idx == $s) $OUT .= ' selected="selected"';
1527 $OUT .= ">" . $idx."</option>\n";
1529 $OUT .= " </select></td>\n";
1531 $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\">\n";
1534 $OUT .= "</table>\n";
1536 // Return generated HTML code
1542 function createTimestampFromSelections ($prefix, $POST) {
1543 // Initial return value
1546 // Do we have a leap year?
1548 $TEST = date('Y', time()) / 4;
1549 $M1 = date('m', time());
1550 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1551 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1552 // First add years...
1553 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1555 $ret += $POST[$prefix."_mo"] * 2628000;
1557 $ret += $POST[$prefix."_we"] * 604800;
1559 $ret += $POST[$prefix."_da"] * 86400;
1561 $ret += $POST[$prefix."_ho"] * 3600;
1563 $ret += $POST[$prefix."_mi"] * 60;
1564 // And at last seconds...
1565 $ret += $POST[$prefix."_se"];
1566 // Return calculated value
1570 // Sends out mail to all administrators
1571 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1572 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1573 // Trim template name
1574 $template = trim($template);
1576 // Load email template
1577 $message = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1579 // Check which admin shall receive this mail
1580 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1581 array($template), __FUNCTION__, __LINE__);
1582 if (SQL_NUMROWS($result) == 0) {
1583 // Create new entry (to all admins)
1584 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1585 array($template), __FUNCTION__, __LINE__);
1587 // Load admin IDs...
1588 // @TODO This can be, somehow, rewritten
1589 $adminIds = array();
1590 while ($content = SQL_FETCHARRAY($result)) {
1591 $adminIds[] = $content['admin_id'];
1595 SQL_FREERESULT($result);
1600 // "implode" IDs and query string
1601 $aid = implode(',', $adminIds);
1603 if (EXT_IS_ACTIVE('events')) {
1604 // Add line to user events
1605 EVENTS_ADD_LINE($subj, $message, $UID);
1607 // Log error for debug
1608 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1614 } elseif ($aid == '0') {
1615 // Select all email adresses
1616 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1617 __FUNCTION__, __LINE__);
1619 // If Admin-ID is not "to-all" select
1620 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1621 array($aid), __FUNCTION__, __LINE__);
1625 // Load email addresses and send away
1626 while ($content = SQL_FETCHARRAY($result)) {
1627 sendEmail($content['email'], $subj, $message);
1631 SQL_FREERESULT($result);
1634 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1635 function createFancyTime ($stamp) {
1636 // Get data array with years/months/weeks/days/...
1637 $data = createTimeSelections($stamp, '', '', '', true);
1639 foreach($data as $k => $v) {
1641 // Value is greater than 0 "eval" data to return string
1642 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1648 // Do we have something there?
1649 if (strlen($ret) > 0) {
1650 // Remove leading commata and space
1651 $ret = substr($ret, 2);
1654 $ret = "0 {--_SECONDS--}";
1657 // Return fancy time string
1662 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1663 $SEP = ''; $TOP = '';
1666 $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\"> </td></tr>";
1670 for ($page = 1; $page <= $PAGES; $page++) {
1671 // Is the page currently selected or shall we generate a link to it?
1672 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1673 // Is currently selected, so only highlight it
1674 $NAV .= "<strong>-";
1676 // Open anchor tag and add base URL
1677 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=" . getWhat()."&page=" . $page."&offset=" . $offset;
1679 // Add userid when we shall show all mails from a single member
1680 if ((REQUEST_ISSET_GET('uid')) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1682 // Close open anchor tag
1686 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1687 // Is currently selected, so only highlight it
1688 $NAV .= "-</strong>";
1694 // Add seperator if we have not yet reached total pages
1695 if ($page < $PAGES) $NAV .= " | ";
1698 // Define constants only once
1699 if (!defined('__NAV_OUTPUT')) {
1700 define('__NAV_OUTPUT' , $NAV);
1701 define('__NAV_COLSPAN', $colspan);
1702 define('__NAV_TOP' , $TOP);
1703 define('__NAV_SEP' , $SEP);
1706 // Load navigation template
1707 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1709 if ($return === true) {
1710 // Return generated HTML-Code
1718 // Extract host from script name
1719 function extractHostnameFromUrl (&$script) {
1720 // Use default SERVER_URL by default... ;) So?
1721 $url = constant('SERVER_URL');
1723 // Is this URL valid?
1724 if (substr($script, 0, 7) == 'http://') {
1725 // Use the hostname from script URL as new hostname
1726 $url = substr($script, 7);
1727 $extract = explode('/', $url);
1729 // Done extracting the URL :)
1732 // Extract host name
1733 $host = str_replace('http://', '', $url);
1734 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1736 // Generate relative URL
1737 //* DEBUG: */ print("SCRIPT=" . $script."<br />\n");
1738 if (substr(strtolower($script), 0, 7) == 'http://') {
1739 // But only if http:// is in front!
1740 $script = substr($script, (strlen($url) + 7));
1741 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1743 $script = substr($script, (strlen($url) + 8));
1746 //* DEBUG: */ print("SCRIPT=" . $script."<br />\n");
1747 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1753 // Send a GET request
1754 function sendGetRequest ($script) {
1755 // Compile the script name
1756 $script = COMPILE_CODE($script);
1758 // Extract host name from script
1759 $host = extractHostnameFromUrl($script);
1761 // Generate GET request header
1762 $request = "GET /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
1763 $request .= "Host: " . $host . getConfig('HTTP_EOL');
1764 $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
1765 if (defined('FULL_VERSION')) {
1766 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
1768 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?" . getConfig('HTTP_EOL');
1770 $request .= "Content-Type: text/plain" . getConfig('HTTP_EOL');
1771 $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
1772 $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1774 // Send the raw request
1775 $response = sendRawRequest($host, $request);
1777 // Return the result to the caller function
1781 // Send a POST request
1782 function sendPostRequest ($script, $postData) {
1783 // Is postData an array?
1784 if (!is_array($postData)) {
1786 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1787 return array('', '', '');
1790 // Compile the script name
1791 $script = COMPILE_CODE($script);
1793 // Extract host name from script
1794 $host = extractHostnameFromUrl($script);
1796 // Construct request
1797 $data = http_build_query($postData, '','&');
1799 // Generate POST request header
1800 $request = "POST /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
1801 $request .= "Host: " . $host . getConfig('HTTP_EOL');
1802 $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
1803 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
1804 $request .= "Content-type: application/x-www-form-urlencoded" . getConfig('HTTP_EOL');
1805 $request .= "Content-length: " . strlen($data) . getConfig('HTTP_EOL');
1806 $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
1807 $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1810 // Send the raw request
1811 $response = sendRawRequest($host, $request);
1813 // Return the result to the caller function
1817 // Sends a raw request to another host
1818 function sendRawRequest ($host, $request) {
1819 // Init errno and errdesc with 'all fine' values
1820 $errno = 0; $errdesc = '';
1823 $response = array('', '', '');
1825 // Default is not to use proxy
1828 // Are proxy settins set?
1829 if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
1835 //* DEBUG: */ die("SCRIPT=" . $script."<br />\n");
1836 if ($useProxy === true) {
1837 // Connect to host through proxy connection
1838 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1840 // Connect to host directly
1841 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1845 if (!is_resource($fp)) {
1851 if ($useProxy === true) {
1852 // Generate CONNECT request header
1853 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1854 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1856 // Use login data to proxy? (username at least!)
1857 if (getConfig('proxy_username') != '') {
1859 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . COMPILE_CODE(getConfig('proxy_password')));
1860 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1863 // Add last new-line
1864 $proxyTunnel .= getConfig('HTTP_EOL');
1865 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
1868 fputs($fp, $proxyTunnel);
1872 // No response received
1876 // Read the first line
1877 $resp = trim(fgets($fp, 10240));
1878 $respArray = explode(' ', $resp);
1879 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1880 // Invalid response!
1886 fputs($fp, $request);
1889 while (!feof($fp)) {
1890 $response[] = trim(fgets($fp, 1024));
1896 // Skip first empty lines
1898 foreach ($resp as $idx => $line) {
1900 $line = trim($line);
1902 // Is this line empty?
1905 array_shift($response);
1907 // Abort on first non-empty line
1912 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1914 // Proxy agent found?
1915 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1916 // Proxy header detected, so remove two lines
1917 array_shift($response);
1918 array_shift($response);
1921 // Was the request successfull?
1922 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1923 // Not found / access forbidden
1924 $response = array('', '', '');
1931 // Taken from www.php.net eregi() user comments
1932 function isEmailValid ($email) {
1934 $email = COMPILE_CODE($email);
1936 // Check first part of email address
1937 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1940 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1943 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1945 // Return check result
1946 // @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
1947 return preg_match($regex, $email);
1950 // Function taken from user comments on www.php.net / function eregi()
1951 function isUrlValid ($URL, $compile=true) {
1952 // Trim URL a little
1953 $URL = trim(urldecode($URL));
1954 //* DEBUG: */ echo $URL."<br />";
1956 // Compile some chars out...
1957 if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1958 //* DEBUG: */ echo $URL."<br />";
1960 // Check for the extension filter
1961 if (EXT_IS_ACTIVE('filter')) {
1962 // Use the extension's filter set
1963 return FILTER_VALIDATE_URL($URL, false);
1966 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1967 // https:// in front of the URLs
1968 return isUrlValidSimple($URL);
1971 // Generate a list of administrative links to a given userid
1972 function generateMemberAdminActionLinks ($uid, $status = '') {
1973 // Define all main targets
1974 $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1976 // Begin of navigation links
1977 $eval = "\$OUT = \"[ ";
1979 foreach ($TARGETS as $tar) {
1980 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=" . $tar."&uid=" . $uid."\\\" title=\\\"{--ADMIN_LINK_";
1981 //* DEBUG: */ echo "*" . $tar.'/' . $status."*<br />\n";
1982 if (($tar == "lock_user") && ($status == 'LOCKED')) {
1983 // Locked accounts shall be unlocked
1984 $eval .= "UNLOCK_USER";
1986 // All other status is fine
1987 $eval .= strtoupper($tar);
1989 $eval .= "_TITLE--}\\\">{--ADMIN_";
1990 if (($tar == "lock_user") && ($status == 'LOCKED')) {
1991 // Locked accounts shall be unlocked
1992 $eval .= "UNLOCK_USER";
1994 // All other status is fine
1995 $eval .= strtoupper($tar);
1997 $eval .= "--}</a></span> | ";
2000 // Finish navigation link
2001 $eval = substr($eval, 0, -7)."]\";";
2008 // Generate an email link
2009 function generateMemberEmailLink ($email, $table = 'admins') {
2010 // Default email link (INSECURE! Spammer can read this by harvester programs)
2011 $EMAIL = 'mailto:' . $email;
2013 // Check for several extensions
2014 if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
2015 // Create email link for contacting admin in guest area
2016 $EMAIL = adminsCreateEmailLink($email);
2017 } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
2018 // Create email link for contacting a member within admin area (or later in other areas, too?)
2019 $EMAIL = USER_generateMemberEmailLink($email);
2020 } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
2021 // Create email link to contact sponsor within admin area (or like the link above?)
2022 $EMAIL = SPONSOR_generateMemberEmailLink($email);
2025 // Shall I close the link when there is no admin?
2026 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2028 // Return email link
2032 // Generate a hash for extra-security for all passwords
2033 function generateHash ($plainText, $salt = '') {
2034 // Is the required extension 'sql_patches' there and a salt is not given?
2035 if (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('sql_patches'))) && (empty($salt))) {
2036 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2037 return md5($plainText);
2040 // Do we miss an arry element here?
2041 if (!isConfigEntrySet('file_hash')) {
2043 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2046 // When the salt is empty build a new one, else use the first x configured characters as the salt
2048 // Build server string (inc/databases.php is no longer updated with every commit)
2049 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
2052 $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');
2055 $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
2057 // Calculate number for generating the code
2058 $a = time() + getConfig('_ADD') - 1;
2060 // Generate SHA1 sum from modula of number and the prime number
2061 $sha1 = sha1(($a % getConfig('_PRIME')) . $server.getConfig('ENCRYPT_SEPERATOR') . $keys.getConfig('ENCRYPT_SEPERATOR') . $data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR') . $a);
2062 //* DEBUG: */ echo "SHA1=" . $sha1." (".strlen($sha1).")<br />";
2063 $sha1 = scrambleString($sha1);
2064 //* DEBUG: */ echo "Scrambled=" . $sha1." (".strlen($sha1).")<br />";
2065 //* DEBUG: */ $sha1b = descrambleString($sha1);
2066 //* DEBUG: */ echo "Descrambled=" . $sha1b." (".strlen($sha1b).")<br />";
2068 // Generate the password salt string
2069 $salt = substr($sha1, 0, getConfig('salt_length'));
2070 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2073 $salt = substr($salt, 0, getConfig('salt_length'));
2074 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2078 return $salt.sha1($salt . $plainText);
2081 // Scramble a string
2082 function scrambleString($str) {
2086 // Final check, in case of failture it will return unscrambled string
2087 if (strlen($str) > 40) {
2088 // The string is to long
2090 } elseif (strlen($str) == 40) {
2092 $scrambleNums = explode(':', getConfig('pass_scramble'));
2094 // Generate new numbers
2095 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2098 // Scramble string here
2099 //* DEBUG: */ echo "***Original=" . $str."***<br />";
2100 for ($idx = 0; $idx < strlen($str); $idx++) {
2101 // Get char on scrambled position
2102 $char = substr($str, $scrambleNums[$idx], 1);
2104 // Add it to final output string
2105 $scrambled .= $char;
2108 // Return scrambled string
2109 //* DEBUG: */ echo "***Scrambled=" . $scrambled."***<br />";
2113 // De-scramble a string scrambled by scrambleString()
2114 function descrambleString($str) {
2115 // Scramble only 40 chars long strings
2116 if (strlen($str) != 40) return $str;
2118 // Load numbers from config
2119 $scrambleNums = explode(':', getConfig('pass_scramble'));
2122 if (count($scrambleNums) != 40) return $str;
2124 // Begin descrambling
2125 $orig = str_repeat(" ", 40);
2126 //* DEBUG: */ echo "+++Scrambled=" . $str."+++<br />";
2127 for ($idx = 0; $idx < 40; $idx++) {
2128 $char = substr($str, $idx, 1);
2129 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2132 // Return scrambled string
2133 //* DEBUG: */ echo "+++Original=" . $orig."+++<br />";
2137 // Generated a "string" for scrambling
2138 function genScrambleString ($len) {
2139 // Prepare array for the numbers
2140 $scrambleNumbers = array();
2142 // First we need to setup randomized numbers from 0 to 31
2143 for ($idx = 0; $idx < $len; $idx++) {
2145 $rand = mt_rand(0, ($len -1));
2147 // Check for it by creating more numbers
2148 while (array_key_exists($rand, $scrambleNumbers)) {
2149 $rand = mt_rand(0, ($len -1));
2153 $scrambleNumbers[$rand] = $rand;
2156 // So let's create the string for storing it in database
2157 $scrambleString = implode(':', $scrambleNumbers);
2158 return $scrambleString;
2161 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2162 function generatePassString ($passHash) {
2163 // Return vanilla password hash
2166 // Is a secret key and master salt already initialized?
2167 if ((getConfig('secret_key') != '') && (getConfig('master_salt') != '')) {
2168 // Only calculate when the secret key is generated
2169 $newHash = ''; $start = 9;
2170 for ($idx = 0; $idx < 10; $idx++) {
2171 $part1 = hexdec(substr($passHash, $start, 4));
2172 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2173 $mod = dechex($idx);
2174 if ($part1 > $part2) {
2175 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2176 } elseif ($part2 > $part1) {
2177 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2179 $mod = substr(round($mod), 0, 4);
2180 $mod = str_repeat('0', 4-strlen($mod)) . $mod;
2181 //* DEBUG: */ echo "*" . $start.'=' . $mod."*<br />";
2186 //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
2187 $ret = generateHash($newHash, getConfig('master_salt'));
2188 //* DEBUG: */ print($ret."<br />\n");
2191 //* DEBUG: */ echo "--" . $passHash."--<br />\n";
2192 $ret = md5($passHash);
2193 //* DEBUG: */ echo "++" . $ret."++<br />\n";
2200 // Fix "deleted" cookies
2201 function fixDeletedCookies ($cookies) {
2202 // Is this an array with entries?
2203 if ((is_array($cookies)) && (count($cookies) > 0)) {
2204 // Then check all cookies if they are marked as deleted!
2205 foreach ($cookies as $cookieName) {
2206 // Is the cookie set to "deleted"?
2207 if (getSession($cookieName) == 'deleted') {
2208 setSession($cookieName, '');
2214 // Output error messages in a fasioned way and die...
2215 function app_die ($F, $L, $message) {
2216 // Check if Script is already dieing and not let it kill itself another 1000 times
2217 if (!isset($GLOBALS['app_died'])) {
2218 // Make sure, that the script realy realy diese here and now
2219 $GLOBALS['app_died'] = true;
2222 loadIncludeOnce('inc/header.php');
2224 // Rewrite message for output
2225 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2227 // Better log this message away
2228 DEBUG_LOG($F, $L, $message);
2230 // Load the message template
2231 LOAD_TEMPLATE('admin_settings_saved', false, $message);
2234 loadIncludeOnce('inc/footer.php');
2236 // Script tried to kill itself twice
2237 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2241 // Display parsing time and number of SQL queries in footer
2242 function displayParsingTime() {
2243 // Is the timer started?
2244 if (!isset($GLOBALS['startTime'])) {
2250 $endTime = microtime(true);
2252 // "Explode" both times
2253 $start = explode(' ', $GLOBALS['startTime']);
2254 $end = explode(' ', $endTime);
2255 $runTime = $end[0] - $start[0];
2256 if ($runTime < 0) $runTime = 0;
2257 $runTime = translateComma($runTime);
2261 'runtime' => $runTime,
2262 'numSQLs' => (getConfig('sql_count') + 1),
2263 'numTemplates' => (getConfig('num_templates') + 1)
2266 // Load the template
2267 LOAD_TEMPLATE('show_timings', false, $content);
2270 // Check wether a boolean constant is set
2271 // Taken from user comments in PHP documentation for function constant()
2272 function isBooleanConstantAndTrue ($constName) { // : Boolean
2273 // Failed by default
2277 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2279 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />\n";
2280 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2283 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />\n";
2284 if (defined($constName)) {
2286 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />\n";
2287 $res = (constant($constName) === true);
2291 $GLOBALS['cache_array']['const'][$constName] = $res;
2293 //* DEBUG: */ var_dump($res);
2299 // Checks if a given apache module is loaded
2300 function isApacheModuleLoaded ($apacheModule) {
2301 // Check it and return result
2302 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2305 // Get current theme name
2306 function getCurrentTheme() {
2307 // The default theme is 'default'... ;-)
2310 // Load default theme if not empty from configuration
2311 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2313 if (!isSessionVariableSet('mxchange_theme')) {
2314 // Set default theme
2315 setSession('mxchange_theme', $ret);
2316 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
2317 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2318 // Get theme from cookie
2319 $ret = getSession('mxchange_theme');
2322 if (getThemeId($ret) == 0) {
2323 // Fix it to default
2326 } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
2327 // Prepare FQFN for checking
2328 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
2330 // Installation mode active
2331 if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
2332 // Set cookie from URL data
2333 setSession('mxchange_theme', REQUEST_GET('theme'));
2334 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2335 // Set cookie from posted data
2336 setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2340 $ret = getSession('mxchange_theme');
2342 // Invalid design, reset cookie
2343 setSession('mxchange_theme', $ret);
2346 // Add (maybe) found theme.php file to inclusion list
2347 $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2349 // Try to load the requested include file
2350 if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
2352 // Return theme value
2356 // Get id from theme
2357 function getThemeId ($name) {
2358 // Is the extension 'theme' installed?
2359 if (!EXT_IS_ACTIVE('theme')) {
2367 // Is the cache entry there?
2368 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2369 // Get the version from cache
2370 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2373 incrementConfigEntry('cache_hits');
2374 } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
2375 // Check if current theme is already imported or not
2376 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2377 array($name), __FUNCTION__, __LINE__);
2380 if (SQL_NUMROWS($result) == 1) {
2382 list($id) = SQL_FETCHROW($result);
2386 SQL_FREERESULT($result);
2393 // Generates an error code from given account status
2394 function generateErrorCodeFromUserStatus ($status) {
2395 // @TODO The status should never be empty
2396 if (empty($status)) {
2397 // Something really bad happend here
2398 debug_report_bug(__FUNCTION__ . ': status is empty.');
2401 // Default error code if unknown account status
2402 $errorCode = getCode('UNKNOWN_STATUS');
2404 // Generate constant name
2405 $constantName = sprintf("ID_%s", $status);
2407 // Is the constant there?
2408 if (isCodeSet($constantName)) {
2410 $errorCode = getCode($constantName);
2413 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2416 // Return error code
2420 // Function to search for the last modifified file
2421 function searchDirsRecursive ($dir, &$last_changed) {
2423 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />\n";
2424 // Does it match what we are looking for? (We skip a lot files already!)
2425 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2426 $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2427 $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
2428 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2430 // Walk through all entries
2431 foreach ($ds as $d) {
2432 // Generate proper FQFN
2433 $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
2435 // Is it a file and readable?
2436 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2437 if (isDirectory($FQFN)) {
2438 // $FQFN is a directory so also crawl into this directory
2440 if (!empty($dir)) $newDir = $dir . '/'. $d;
2441 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />\n";
2442 searchDirsRecursive($newDir, $last_changed);
2443 } elseif (isFileReadable($FQFN)) {
2444 // $FQFN is a filename and no directory
2445 $time = filemtime($FQFN);
2446 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />\n";
2447 if ($last_changed['time'] < $time) {
2448 // This file is newer as the file before
2449 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2450 $last_changed['path_name'] = $FQFN;
2451 $last_changed['time'] = $time;
2457 // "Getter" for revision/version data
2458 function getActualVersion ($type = 'Revision') {
2459 // By default nothing is new... ;-)
2462 if (EXT_IS_ACTIVE('cache')) {
2463 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2464 if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') {
2465 // Force rebuild by URL parameter
2468 !isset($GLOBALS['cache_array']['revision'][$type])
2470 count($GLOBALS['cache_array']['revision']) < 3
2472 !$GLOBALS['cache_instance']->loadCacheFile('revision')
2478 // Is the cache file outdated/invalid?
2480 // Destroy cache file
2481 $GLOBALS['cache_instance']->destroyCacheFile();
2483 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2484 unset($GLOBALS['cache_array']['revision']);
2486 // Reload load_cach-revison.php
2487 loadInclude('inc/loader/load_cache-revision.php');
2493 // Return found value
2494 return $GLOBALS['cache_array']['revision'][$type][0];
2496 // Old Version without ext-cache active (deprecated ?)
2498 // FQFN of revision file
2499 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2501 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2502 if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
2503 // Forced rebuild of .revision file
2506 // Check for revision file
2507 if (!isFileReadable($FQFN)) {
2508 // Not found, so we need to create it
2511 // Revision file found
2512 $ins_vers = explode("\n", readFromFile($FQFN));
2514 // Get array for mapping information
2515 $mapper = array_flip(getSearchFor());
2516 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2518 // Is the content valid?
2519 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
2520 // File needs update!
2523 // Return found value
2524 return trim($ins_vers[$mapper[$type]]);
2529 // Has it been updated?
2530 if ($new === true) {
2531 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2536 // Repares an array we are looking for
2537 // 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
2538 function getSearchFor () {
2539 // Add Revision, Date, Tag and Author
2540 $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2542 // Return the created array
2546 // @TODO Please describe this function
2547 function getArrayFromActualVersion () {
2549 $next_dir = ''; // Directory to start with search
2550 $last_changed = array(
2554 $akt_vers = array(); // Init return array
2555 $res = 0; // Init value for counting the founded keywords
2557 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2558 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2561 $last_file = readFromFile($last_changed['path_name']);
2563 // Get all the keywords to search for
2564 $searchFor = getSearchFor();
2566 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2567 foreach ($searchFor as $search) {
2568 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2569 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2570 // This trimms the search-result and puts it in the $akt_vers-return array
2571 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2574 // Save the last-changed filename for debugging
2575 $akt_vers['File'] = $last_changed['path_name'];
2577 // at least 3 keyword-Tags are needed for propper values
2578 if ($res && $res >= 3
2579 && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
2580 && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
2581 && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
2582 // Prepare content witch need special treadment
2584 // Prepare timestamp for date
2585 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2586 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2588 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2589 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2590 $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2594 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2595 $version = sendGetRequest('check-updates3.php');
2598 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2599 if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
2600 if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
2601 if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
2602 if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
2605 // Return prepared array
2609 // Back-ported from the new ship-simu engine. :-)
2610 function debug_get_printable_backtrace () {
2612 $backtrace = "<ol>\n";
2614 // Get and prepare backtrace for output
2615 $backtraceArray = debug_backtrace();
2616 foreach ($backtraceArray as $key => $trace) {
2617 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2618 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2619 if (!isset($trace['args'])) $trace['args'] = array();
2620 $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";
2624 $backtrace .= "</ol>\n";
2626 // Return the backtrace
2630 // Output a debug backtrace to the user
2631 function debug_report_bug ($message = '') {
2634 // Is the optional message set?
2635 if (!empty($message)) {
2637 $debug = sprintf("Note: %s<br />\n",
2641 // @TODO Add a little more infos here
2642 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2646 $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>";
2647 $debug .= debug_get_printable_backtrace();
2648 $debug .= "</pre>\nRequest-URI: " . $_SERVER['REQUEST_URI']."<br />\n";
2649 $debug .= "Thank you for finding bugs.";
2652 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2656 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2657 function generateSeed () {
2658 list($usec, $sec) = explode(" ", microtime());
2659 return ((float)$sec + (float)$usec);
2662 // Converts a message code to a human-readable message
2663 function convertCodeToMessage ($code) {
2666 case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
2667 case getCode('LOGOUT_FAILED') : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2668 case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
2669 case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2670 case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2671 case getCode('USER_404') : $message = getMessage('USER_NOT_FOUND'); break;
2672 case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
2673 case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2675 case getCode('ERROR_MAILID'):
2676 if (EXT_IS_ACTIVE($ext, true)) {
2677 $message = getMessage('ERROR_CONFIRMING_MAIL');
2679 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2683 case getCode('EXTENSION_PROBLEM'):
2684 if (REQUEST_ISSET_GET('ext')) {
2685 $message = generateExtensionInactiveNotInstalledMessage(REQUEST_GET('ext'));
2687 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2691 case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
2692 case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2693 case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2694 case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2697 // Missing/invalid code
2698 $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2701 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2705 // Return the message
2709 // Generate a "link" for the given admin id (aid)
2710 function generateAdminLink ($aid) {
2711 // No assigned admin is default
2712 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2714 // Zero? = Not assigned
2715 if (bigintval($aid) > 0) {
2716 // Load admin's login
2717 $login = getAdminLogin($aid);
2719 // Is the login valid?
2720 if ($login != '***') {
2721 // Is the extension there?
2722 if (EXT_IS_ACTIVE('admins')) {
2724 $admin = "<a href=\"".adminsCreateEmailLink(getAdminEmail($aid))."\">" . $login."</a>";
2726 // Extension not found
2727 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2731 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2739 // Compile characters which are allowed in URLs
2740 function compileUriCode ($code, $simple=true) {
2741 // Compile constants
2742 if (!$simple) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2744 // Compile QUOT and other non-HTML codes
2745 $code = str_replace('{DOT}', '.',
2746 str_replace('{SLASH}', '/',
2747 str_replace('{QUOT}', "'",
2748 str_replace('{DOLLAR}', '$',
2749 str_replace('{OPEN_ANCHOR}', '(',
2750 str_replace('{CLOSE_ANCHOR}', ')',
2751 str_replace('{OPEN_SQR}', '[',
2752 str_replace('{CLOSE_SQR}', ']',
2753 str_replace('{PER}', '%',
2757 // Return compiled code
2761 // Function taken from user comments on www.php.net / function eregi()
2762 function isUrlValidSimple ($url) {
2764 $url = strip_tags(str_replace("\\", '', COMPILE_CODE(urldecode($url))));
2766 // Allows http and https
2767 $http = "(http|https)+(:\/\/)";
2769 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2770 // Test double-domains (e.g. .de.vu)
2771 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2773 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2775 $dir = "((/)+([-_\.[:alnum:]])+)*";
2777 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2778 // ... and the string after and including question character
2779 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2780 // Pattern for URLs like http://url/dir/doc.html?var=value
2781 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
2782 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
2783 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
2784 // Pattern for URLs like http://url/dir/?var=value
2785 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
2786 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
2787 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
2788 // Pattern for URLs like http://url/dir/page.ext
2789 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
2790 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
2791 $pattern['ipdp'] = $http . $ip . $dir . $page;
2792 // Pattern for URLs like http://url/dir
2793 $pattern['d1d'] = $http . $domain1 . $dir;
2794 $pattern['d2d'] = $http . $domain2 . $dir;
2795 $pattern['ipd'] = $http . $ip . $dir;
2796 // Pattern for URLs like http://url/?var=value
2797 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
2798 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
2799 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
2800 // Pattern for URLs like http://url?var=value
2801 $pattern['d1g12'] = $http . $domain1 . $getstring1;
2802 $pattern['d2g12'] = $http . $domain2 . $getstring1;
2803 $pattern['ipg12'] = $http . $ip . $getstring1;
2804 // Test all patterns
2806 foreach ($pattern as $key => $pat) {
2808 if (isDebugRegExpressionEnabled()) {
2809 // @TODO Are these convertions still required?
2810 $pat = str_replace('.', "\.", $pat);
2811 $pat = str_replace('@', "\@", $pat);
2812 echo $key."= " . $pat . "<br />";
2815 // Check if expression matches
2816 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2819 if ($reg === true) break;
2822 // Return true/false
2826 // Wtites data to a config.php-style file
2827 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2828 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2829 // Initialize some variables
2835 // Is the file there and read-/write-able?
2836 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2837 $search = 'CFG: ' . $comment;
2838 $tmp = $FQFN . '.tmp';
2840 // Open the source file
2841 $fp = fopen($FQFN, 'r') or OUTPUT_HTML('<strong>READ:</strong> ' . $FQFN . "<br />\n");
2843 // Is the resource valid?
2844 if (is_resource($fp)) {
2845 // Open temporary file
2846 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('<strong>WRITE:</strong> ' . $tmp . "<br />\n");
2848 // Is the resource again valid?
2849 if (is_resource($fp_tmp)) {
2850 while (!feof($fp)) {
2851 // Read from source file
2852 $line = fgets ($fp, 1024);
2854 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2857 if ($next === $seek) {
2859 $line = $prefix . $DATA . $suffix . "\n";
2865 // Write to temp file
2866 fputs($fp_tmp, $line);
2872 // Finished writing tmp file
2876 // Close source file
2879 if (($done === true) && ($found === true)) {
2880 // Copy back tmp file and delete tmp :-)
2881 copyFileVerified($tmp, $FQFN, 0644);
2882 return removeFile($tmp);
2883 } elseif ($found === false) {
2884 OUTPUT_HTML('<strong>CHANGE:</strong> 404!');
2886 OUTPUT_HTML('<strong>TMP:</strong> UNDONE!');
2890 // File not found, not readable or writeable
2891 OUTPUT_HTML('<strong>404:</strong> ' . $FQFN . '<br />');
2894 // An error was detected!
2897 // Send notification to admin
2898 function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
2899 if (GET_EXT_VERSION('admins') >= '0.4.1') {
2901 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2903 // Send out out-dated way
2904 $message = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2905 SEND_ADMIN_EMAILS($subject, $message);
2909 // Debug message logger
2910 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
2911 // Is debug mode enabled?
2912 if ((isDebugModeEnabled()) || ($force === true)) {
2914 $message = str_replace("\r", '', str_replace("\n", '', $message));
2916 // Log this message away
2917 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
2918 fwrite($fp, date("d.m.Y|H:i:s", time())."|" . getModule()."|".basename($funcFile)."|" . $line."|".strip_tags($message)."\n");
2923 // Load more reset scripts
2924 function runResetIncludes () {
2925 // Is the reset set or old sql_patches?
2926 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
2928 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
2931 // Get more daily reset scripts
2932 SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
2935 if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
2937 // Is the config entry set?
2938 if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
2939 // Create current week mark
2940 $currWeek = date('W', time());
2943 if (getConfig('last_week') != $currWeek) {
2944 // Include weekly reset scripts
2945 MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
2948 if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
2951 // Create current month mark
2952 $currMonth = date('m', time());
2955 if (getConfig('last_month') != $currMonth) {
2956 // Include monthly reset scripts
2957 MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
2960 if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
2965 runFilterChain('load_includes');
2968 // Handle extra values
2969 function handleExtraValues ($filterFunction, $value, $extraValue) {
2970 // Default is the value itself
2973 // Do we have a special filter function?
2974 if (!empty($filterFunction)) {
2975 // Does the filter function exist?
2976 if (function_exists($filterFunction)) {
2977 // Do we have extra parameters here?
2978 if (!empty($extraValue)) {
2979 // Put both parameters in one new array by default
2980 $args = array($value, $extraValue);
2982 // If we have an array simply use it and pre-extend it with our value
2983 if (is_array($extraValue)) {
2984 // Make the new args array
2985 $args = merge_array(array($value), $extraValue);
2988 // Call the multi-parameter call-back
2989 $ret = call_user_func_array($filterFunction, $args);
2991 // One parameter call
2992 $ret = call_user_func($filterFunction, $value);
3001 // Converts timestamp selections into a timestamp
3002 function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
3003 // Init test variable
3006 // Get last three chars
3007 $test = substr($id, -3);
3009 // Improved way of checking! :-)
3010 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3011 // Found a multi-selection for timings?
3012 $test = substr($id, 0, -3);
3013 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)) {
3014 // Generate timestamp
3015 $POST[$test] = createTimestampFromSelections($test, $POST);
3016 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3018 // Remove data from array
3019 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3020 unset($POST[$test.'_' . $rem]);
3024 unset($id); $skip = true; $test2 = $test;
3027 // Process this entry
3033 // Reverts the german decimal comma into Computer decimal dot
3034 function convertCommaToDot ($str) {
3035 // Default float is not a float... ;-)
3038 // Which language is selected?
3039 switch (getLanguage()) {
3040 case 'de': // German language
3041 // Remove german thousand dots first
3042 $str = str_replace('.', '', $str);
3044 // Replace german commata with decimal dot and cast it
3045 $float = (float)str_replace(',', '.', $str);
3048 default: // US and so on
3049 // Remove thousand dots first and cast
3050 $float = (float)str_replace(',', '', $str);
3058 // Handle menu-depending failed logins and return the rendered content
3059 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3060 // Default output is empty ;-)
3063 // Is the session data set?
3064 if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
3065 // Ignore zero values
3066 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
3067 // Non-guest has login failures found, get both data and prepare it for template
3068 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3070 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
3071 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), '2')
3075 $OUT = LOAD_TEMPLATE('login_failures', true, $content);
3078 // Reset session data
3079 setSession('mxchange_' . $accessLevel.'_failures', '');
3080 setSession('mxchange_' . $accessLevel.'_last_fail', '');
3083 // Return rendered content
3088 function rebuildCacheFiles ($cache, $inc = '') {
3089 // Shall I remove the cache file?
3090 if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
3092 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3094 $GLOBALS['cache_instance']->destroyCacheFile();
3097 // Include file given?
3100 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3102 // Is the include there?
3103 if (isIncludeReadable($INC)) {
3104 // And rebuild it from scratch
3105 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3108 // Include not found!
3109 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3115 // Purge admin menu cache
3116 function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
3117 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3118 if (!EXT_IS_ACTIVE('cache')) {
3119 // Cache extension not active
3121 } elseif (!isCacheInstanceValid()) {
3122 // No cache instance!
3123 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3125 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
3126 // Caching disabled (currently experiemental!)
3130 // Experiemental feature!
3131 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3134 // Determines the real remote address
3135 function determineRealRemoteAddress () {
3136 // Is a proxy in use?
3137 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
3139 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3140 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
3141 // Yet, another proxy
3142 $address = $_SERVER['HTTP_CLIENT_IP'];
3144 // The regular address when no proxy was used
3145 $address = $_SERVER['REMOTE_ADDR'];
3148 // This strips out the real address from proxy output
3149 if (strstr($address, ',')){
3150 $addressArray = explode(',', $address);
3151 $address = $addressArray[0];
3154 // Return the result
3158 // Adds a bonus mail to the queue
3159 // This is a high-level function!
3160 function addNewBonusMail ($data, $mode = '', $output=true) {
3161 // Use mode from data if not set and availble ;-)
3162 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3164 // Generate receiver list
3165 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3168 if (!empty($RECEIVER)) {
3169 // Add bonus mail to queue
3170 addBonusMailToQueue(
3182 // Mail inserted into bonus pool
3183 if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3184 } elseif ($output) {
3185 // More entered than can be reached!
3186 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3189 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3193 // Determines referal id and sets it
3194 function DETERMINE_REFID () {
3195 // Check if refid is set
3196 if ((REQUEST_ISSET_GET('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3197 // The variable user comes from the click-counter script click.php and we only accept this here
3198 $GLOBALS['refid'] = bigintval(REQUEST_GET('user'));
3199 } elseif (REQUEST_ISSET_POST('refid')) {
3200 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3201 $GLOBALS['refid'] = strip_tags(REQUEST_POST('refid'));
3202 } elseif (REQUEST_ISSET_GET('refid')) {
3203 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3204 $GLOBALS['refid'] = strip_tags(REQUEST_GET('refid'));
3205 } elseif (REQUEST_ISSET_GET('ref')) {
3206 // Set refid=ref (the referal link uses such variable)
3207 $GLOBALS['refid'] = strip_tags(REQUEST_GET('ref'));
3208 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3209 // Set session refid als global
3210 $GLOBALS['refid'] = bigintval(getSession('refid'));
3211 } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
3212 // Set default refid as refid in URL
3213 $GLOBALS['refid'] = getConfig(('def_refid'));
3214 } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
3215 // Select a random user which has confirmed enougth mails
3216 $GLOBALS['refid'] = determineRandomReferalId();
3218 // No default ID when sql_patches is not installed or none set
3219 $GLOBALS['refid'] = 0;
3222 // Set cookie when default refid > 0
3223 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3225 setSession('refid', $GLOBALS['refid']);
3228 // Return determined refid
3229 return $GLOBALS['refid'];
3232 // Enables the reset mode. Only call this function if you really want the
3234 function enableResetMode () {
3235 // Enable the reset mode
3236 $GLOBALS['reset_enabled'] = true;
3239 runFilterChain('reset_enabled');
3242 // Our shutdown-function
3243 function shutdown () {
3244 // Call the filter chain 'shutdown'
3245 runFilterChain('shutdown', null, false);
3247 if (SQL_IS_LINK_UP()) {
3249 SQL_CLOSE(__FILE__, __LINE__);
3250 } elseif ((!isInstalling()) && (isInstalled())) {
3252 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3255 // Stop executing here
3259 // Setter for userid
3260 function setUserId ($userid) {
3261 $GLOBALS['userid'] = bigintval($userid);
3264 // Getter for userid or returns zero
3265 function getUserId () {
3269 // Is the userid set?
3270 if (isUserIdSet()) {
3272 $userid = $GLOBALS['userid'];
3279 // Checks ether the userid is set
3280 function isUserIdSet () {
3281 return (isset($GLOBALS['userid']));
3284 // Handle message codes from URL
3285 function handleCodeMessage () {
3286 if (REQUEST_ISSET_GET('msg')) {
3287 // Default extension is 'unknown'
3290 // Is extension given?
3291 if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
3293 // Convert the 'msg' parameter from URL to a human-readable message
3294 $message = convertCodeToMessage(REQUEST_GET('msg'));
3296 // Load message template
3297 LOAD_TEMPLATE('message', false, $message);
3301 // Setter for extra title
3302 function setExtraTitle ($extraTitle) {
3303 $GLOBALS['extra_title'] = $extraTitle;
3306 // Getter for extra title
3307 function getExtraTitle () {
3308 // Is the extra title set?
3309 if (!isExtraTitleSet()) {
3310 // No, then abort here
3311 debug_report_bug('extra_title is not set!');
3315 return $GLOBALS['extra_title'];
3318 // Checks if the extra title is set
3319 function isExtraTitleSet () {
3320 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3323 // Generates a 'extension foo inactive' message
3324 function generateExtensionInactiveMessage ($ext_name) {
3325 // Is the extension empty?
3326 if (empty($ext_name)) {
3327 // This should not happen
3328 trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3332 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3334 // Is an admin logged in?
3336 // Then output admin message
3337 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3340 // Return prepared message
3344 // Generates a 'extension foo not installed' message
3345 function generateExtensionNotInstalledMessage ($ext_name) {
3346 // Is the extension empty?
3347 if (empty($ext_name)) {
3348 // This should not happen
3349 trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3353 $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3355 // Is an admin logged in?
3357 // Then output admin message
3358 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3361 // Return prepared message
3365 // Generates a message depending on if the extension is not installed or not
3367 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3371 // Is the extension not installed or just deactivated?
3372 switch (isExtensionInstalled($ext_name)) {
3373 case true; // Deactivated!
3374 $message = generateExtensionInactiveMessage($ext_name);
3377 case false; // Not installed!
3378 $message = generateExtensionNotInstalledMessage($ext_name);
3381 default: // Should not happen!
3382 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3383 $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3387 // Return the message
3391 //////////////////////////////////////////////////
3392 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3393 //////////////////////////////////////////////////
3395 if (!function_exists('html_entity_decode')) {
3396 // Taken from documentation on www.php.net
3397 function html_entity_decode ($string) {
3398 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3399 $trans_tbl = array_flip($trans_tbl);
3400 return strtr($string, $trans_tbl);