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 * -------------------------------------------------------------------- *
14 * $Date:: 2009-03-06 20:24:32 +0100 (Fr, 06. Mär 2009) $ *
15 * $Tag:: 0.2.1-FINAL $ *
16 * $Author:: stelzi $ *
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 // Check if our config file is writeable or not
45 function IS_INC_WRITEABLE ($inc) {
47 $FQFN = sprintf("%sinc/%s.php", constant('PATH'), $inc);
49 // Abort by simple test
50 if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN))) {
54 // Test write-access on directory
55 return is_writeable(dirname($FQFN));
58 // Output HTML code directly or "render" it. You addionally switch the new-line character off
59 function OUTPUT_HTML ($HTML, $newLine = true) {
60 // Some global variables
63 // Do we have HTML-Code here?
65 // Yes, so we handle it as you have configured
66 switch (constant('OUTPUT_MODE'))
69 // That's why you don't need any \n at the end of your HTML code... :-)
70 if (constant('_OB_CACHING') == "on") {
71 // Output into PHP's internal buffer
74 // That's why you don't need any \n at the end of your HTML code... :-)
75 if ($newLine) echo "\n";
77 // Render mode for old or lame servers...
80 // That's why you don't need any \n at the end of your HTML code... :-)
81 if ($newLine) $OUTPUT .= "\n";
86 // If we are switching from render to direct output rendered code
87 if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
89 // The same as above... ^
91 if ($newLine) echo "\n";
95 // Huh, something goes wrong or maybe you have edited config.php ???
96 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
97 mxchange_die("<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
100 } elseif ((constant('_OB_CACHING') == "on") && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
101 // Headers already sent?
102 if (headers_sent()) {
104 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
106 // Trigger an user error
107 debug_report_bug("Headers are already sent!");
110 // Output cached HTML code
111 $OUTPUT = ob_get_contents();
113 // Clear output buffer for later output if output is found
114 if (!empty($OUTPUT)) {
119 header("HTTP/1.1 200");
122 $now = gmdate('D, d M Y H:i:s') . ' GMT';
124 // General headers for no caching
125 header("Expired: " . $now); // RFC2616 - Section 14.21
126 header("Last-Modified: " . $now);
127 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
128 header("Pragma: no-cache"); // HTTP/1.0
129 header("Connection: Close");
131 // Extension "rewrite" installed?
132 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
133 $OUTPUT = REWRITE_LINKS($OUTPUT);
136 // Compile and run finished rendered HTML code
137 while (strpos($OUTPUT, '{!') > 0) {
138 // Prepare the content and eval() it...
140 $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
143 // Was that eval okay?
144 if (empty($newContent)) {
145 // Something went wrong!
146 mxchange_die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
148 $OUTPUT = $newContent;
151 // Output code here, DO NOT REMOVE! ;-)
153 } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
154 // Rewrite links when rewrite extension is active
155 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
156 $OUTPUT = REWRITE_LINKS($OUTPUT);
159 // Compile and run finished rendered HTML code
160 while (strpos($OUTPUT, '{!') > 0) {
161 $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
165 // Output code here, DO NOT REMOVE! ;-)
170 // Output the raw HTML code
171 function OUTPUT_RAW ($HTML) {
172 // Output stripped HTML code to avoid broken JavaScript code, etc.
173 echo stripslashes(stripslashes($HTML));
175 // Flush the output if only constant('_OB_CACHING') is not "on"
176 if (constant('_OB_CACHING') != "on") {
182 // Init fatal message array
183 function initFatalMessages () {
184 $GLOBALS['fatal_messages'] = array();
187 // Getter for whole fatal error messages
188 function getFatalArray () {
189 return $GLOBALS['fatal_messages'];
192 // Add a fatal error message to the queue array
193 function addFatalMessage ($F, $L, $message, $extra="") {
194 if (is_array($extra)) {
195 // Multiple extras for a message with masks
196 $message = call_user_func_array('sprintf', $extra);
197 } elseif (!empty($extra)) {
198 // $message is text with a mask plus extras to insert into the text
199 $message = sprintf($message, $extra);
202 // Add message to $GLOBALS['fatal_messages']
203 $GLOBALS['fatal_messages'][] = $message;
205 // Log fatal messages away
206 DEBUG_LOG($F, $L, " message={$message}");
209 // Getter for total fatal message count
210 function getTotalFatalErrors () {
214 // Do we have at least the first entry?
215 if (!empty($GLOBALS['fatal_messages'][0])) {
217 $count = count($GLOBALS['fatal_messages']);
224 // Load a template file and return it's content (only it's name; do not use ' or ")
225 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
226 // Add more variables which you want to use in your template files
227 global $DATA, $_CONFIG, $username;
229 // Make all template names lowercase
230 $template = strtolower($template);
232 // Count the template load
233 incrementConfigEntry('num_templates');
235 // Prepare IP number and User Agent
236 $REMOTE_ADDR = GET_REMOTE_ADDR();
237 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
238 $HTTP_USER_AGENT = GET_USER_AGENT();
242 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
244 // @DEPRECATED Try to rewrite the if() condition
245 if ($template == "member_support_form") {
246 // Support request of a member
247 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
248 array($GLOBALS['userid']), __FUNCTION__, __LINE__);
250 // Is content an array?
251 if (is_array($content)) {
253 $content = merge_array($content, SQL_FETCHARRAY($result));
256 $content['gender'] = TRANSLATE_GENDER($content['gender']);
259 // @TODO Fine all templates which are using these direct variables and rewrite them.
260 // @TODO After this step is done, this else-block is history
261 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
264 $gender = TRANSLATE_GENDER($gender);
265 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
269 SQL_FREERESULT($result);
272 // Generate date/time string
273 $date_time = MAKE_DATETIME(time(), "1");
276 $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
279 // Check for admin/guest/member templates
280 if (strpos($template, "admin_") > -1) {
281 // Admin template found
283 } elseif (strpos($template, "guest_") > -1) {
284 // Guest template found
286 } elseif (strpos($template, "member_") > -1) {
287 // Member template found
289 } elseif (strpos($template, "install_") > -1) {
290 // Installation template found
292 } elseif (strpos($template, "ext_") > -1) {
293 // Extension template found
295 } elseif (strpos($template, "la_") > -1) {
296 // "Logical-area" template found
299 // Test for extension
300 $test = substr($template, 0, strpos($template, "_"));
301 if (EXT_IS_ACTIVE($test)) {
302 // Set extra path to extension's name
307 ////////////////////////
308 // Generate file name //
309 ////////////////////////
310 $FQFN = $BASE.$MODE.$template.".tpl";
312 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
313 // Select what depended header/footer template file for admin/guest/member area
314 $file2 = sprintf("%s%s%s_%s.tpl",
318 SQL_ESCAPE($GLOBALS['what'])
322 if (FILE_READABLE($file2)) $FQFN = $file2;
324 // Remove variable from memory
328 // Does the special template exists?
329 if (!FILE_READABLE($FQFN)) {
330 // Reset to default template
331 $FQFN = $BASE.$template.".tpl";
334 // Now does the final template exists?
335 if (FILE_READABLE($FQFN)) {
336 // The local file does exists so we load it. :)
337 $tmpl_file = READ_FILE($FQFN);
339 // Replace ' to our own chars to preventing them being quoted
340 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
342 // Do we have to compile the code?
344 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
346 $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
349 // Simply return loaded code
353 // Add surrounding HTML comments to help finding bugs faster
354 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
355 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
356 // Only admins shall see this warning or when installation mode is active
357 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
358 (".basename($FQFN).")<br />
361 <pre>".print_r($content, true)."</pre>
363 <pre>".print_r($DATA, true)."</pre>
367 // Remove content and data
371 // Do we have some content to output or return?
373 // Not empty so let's put it out! ;)
374 if ($return === true) {
375 // Return the HTML code
381 } elseif (isDebugModeEnabled()) {
382 // Warning, empty output!
383 return "E:".$template."<br />\n";
387 // Send mail out to an email address
388 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
389 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
391 // Compile subject line (for POINTS constant etc.)
392 $eval = "\$SUBJECT = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($SUBJECT))."\");";
396 if ((!eregi("@", $TO)) && ($TO > 0)) {
397 // Value detected, is the message extension installed?
398 if (EXT_IS_ACTIVE("msg")) {
399 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
402 // Load email address
403 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FUNCTION__, __LINE__);
404 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
406 // Does the user exist?
407 if (SQL_NUMROWS($result_email)) {
408 // Load email address
409 list($TO) = SQL_FETCHROW($result_email);
412 $TO = constant('WEBMASTER');
416 SQL_FREERESULT($result_email);
418 } elseif ("$TO" == "0") {
420 $TO = constant('WEBMASTER');
422 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
424 // Check for PHPMailer or debug-mode
425 if (!CHECK_PHPMAILER_USAGE()) {
426 // Not in PHPMailer-Mode
428 // Load email header template
429 $FROM = LOAD_EMAIL_TEMPLATE("header");
432 $FROM .= LOAD_EMAIL_TEMPLATE("header");
434 } elseif (isDebugModeEnabled()) {
436 // Load email header template
437 $FROM = LOAD_EMAIL_TEMPLATE("header");
440 $FROM .= LOAD_EMAIL_TEMPLATE("header");
445 $eval = "\$TO = \"".COMPILE_CODE(smartAddSlashes($TO))."\";";
449 $eval = "\$MSG = \"".COMPILE_CODE(smartAddSlashes($MSG))."\";";
452 // Fix HTML parameter (default is no!)
453 if (empty($HTML)) $HTML = "N";
454 if (isDebugModeEnabled()) {
455 // In debug mode we want to display the mail instead of sending it away so we can debug this part
457 ".htmlentities(trim($FROM))."
459 Subject : ".$SUBJECT."
462 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
463 // Send mail as HTML away
464 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
465 } elseif (!empty($TO)) {
467 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
468 } elseif ($HTML == "N") {
470 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
474 // Check if legacy or PHPMailer command
475 // @TODO Rewrite this to an extension 'smtp'
477 function CHECK_PHPMAILER_USAGE() {
478 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (constant('SMTP_HOSTNAME') != "") && (constant('SMTP_USER') != ""));
482 * Send out a raw email with PHPMailer class or legacy mail() command
484 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
485 // Shall we use PHPMailer class or legacy mode?
486 if (CHECK_PHPMAILER_USAGE()) {
487 // Use PHPMailer class with SMTP enabled
488 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
489 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
492 $mail = new PHPMailer();
493 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
496 $mail->SMTPAuth = true;
497 $mail->Host = constant('SMTP_HOSTNAME');
499 $mail->Username = constant('SMTP_USER');
500 $mail->Password = constant('SMTP_PASSWORD');
502 $mail->From = constant('WEBMASTER');
506 $mail->FromName = constant('MAIN_TITLE');
507 $mail->Subject = $subject;
508 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
510 $mail->AltBody = "Your mail program required HTML support to read this mail!";
511 $mail->WordWrap = 70;
514 $mail->Body = decodeEntities($msg);
516 $mail->AddAddress($to, "");
517 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
518 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
519 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
522 // Use legacy mail() command
523 @mail($to, $subject, decodeEntities($msg), $from);
528 // Generate a password in a specified length or use default password length
529 function GEN_PASS ($LEN = 0) {
530 // Auto-fix invalid length of zero
531 if ($LEN == 0) $LEN = getConfig('pass_len');
533 // Initialize array with all allowed chars
534 $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,-,+,_,/");
536 // Start creating password
538 for ($i = 0; $i < $LEN; $i++) {
539 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
542 // When the size is below 40 we can also add additional security by scrambling it
543 if (strlen($PASS) <= 40) {
544 // Also scramble the password
545 $PASS = scrambleString($PASS);
548 // Return the password
552 function MAKE_DATETIME ($time, $mode="0")
556 return NEVER_HAPPENED;
558 // Filter out numbers
559 $time = bigintval($time);
562 switch (GET_LANGUAGE())
564 case "de": // German date / time format
566 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
567 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
568 case "2": $ret = date("d.m.Y|H:i", $time); break;
569 case "3": $ret = date("d.m.Y", $time); break;
571 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
576 default: // Default is the US date / time format!
578 case "0": $ret = date("r", $time); break;
579 case "1": $ret = date("Y-m-d - g:i A", $time); break;
580 case "2": $ret = date("y-m-d|H:i", $time); break;
581 case "3": $ret = date("y-m-d", $time); break;
583 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
590 // Translates the american decimal dot into a german comma
591 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
592 // Default is 3 you can change this in admin area "Misc -> Misc Options"
593 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', "3");
595 // Use from config is default
596 $maxComma = getConfig('max_comma');
598 // Use from parameter?
599 if ($max > 0) $maxComma = $max;
602 if (($cut) && ($max == 0)) {
603 // Test for commata if in cut-mode
604 $com = explode(".", $dotted);
605 if (count($com) < 2) {
606 // Don't display commatas even if there are none... ;-)
612 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
615 switch (GET_LANGUAGE()) {
617 $dotted = number_format($dotted, $maxComma, ",", ".");
621 $dotted = number_format($dotted, $maxComma, ".", ",");
625 // Return translated value
630 function DEREFERER ($URL) {
631 // Don't de-refer our own links!
632 if (substr($URL, 0, strlen(URL)) != URL) {
633 // De-refer this link
634 $URL = "modules.php?module=loader&url=".encodeString(compileUriCode($URL));
641 // Translate Uni*-like gender to human-readable
642 function TRANSLATE_GENDER ($gender) {
644 $ret = "!{$gender}!";
646 // Male/female or company?
648 case "M": $ret = getMessage('GENDER_M'); break;
649 case "F": $ret = getMessage('GENDER_F'); break;
650 case "C": $ret = getMessage('GENDER_C'); break;
652 // Log unknown gender
653 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
657 // Return translated gender
662 function FRAMETESTER ($URL) {
663 // Prepare frametester URL
664 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
666 encodeString(compileUriCode($URL))
668 return $frametesterUrl;
672 function SELECTION_COUNT ($array) {
674 if (is_array($array)) {
675 foreach ($array as $key => $selected) {
676 if (!empty($selected)) $ret++;
682 function IMG_CODE ($code, $type, $DATA, $uid) {
683 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
686 function TRANSLATE_STATUS ($status) {
692 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
697 $ret = getMessage('ACCOUNT_DELETED');
701 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
702 $ret = sprintf(getMessage('UNKNOWN_STATUS"'), $status);
710 function GET_LANGUAGE() {
711 // Set default return value to default language from config
712 $ret = constant('DEFAULT_LANG');
717 // Is the variable set
718 if (REQUEST_ISSET_GET(('mx_lang'))) {
719 // Accept only first 2 chars
720 $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
721 } elseif (isset($GLOBALS['cache_array']['language'])) {
723 $ret = $GLOBALS['cache_array']['language'];
724 } elseif (!empty($lang)) {
725 // Check if main language file does exist
726 if (FILE_READABLE(constant('PATH')."inc/language/".$lang.".php")) {
727 // Okay found, so let's update cookies
730 } elseif (!isSessionVariableSet('mx_lang')) {
731 // Return stored value from cookie
732 $ret = get_session('mx_lang');
734 // Fixes a warning before the session has the mx_lang constant
735 if (empty($ret)) $ret = constant('DEFAULT_LANG');
739 $GLOBALS['cache_array']['language'] = $ret;
745 function SET_LANGUAGE ($lang) {
746 // Accept only first 2 chars!
747 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
750 set_session('mx_lang', $lang);
753 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
754 global $DATA, $_CONFIG;
756 // Make sure all template names are lowercase!
757 $template = strtolower($template);
759 // Default "nickname" if extension is not installed
762 // Prepare IP number and User Agent
763 $REMOTE_ADDR = GET_REMOTE_ADDR();
764 $HTTP_USER_AGENT = GET_USER_AGENT();
767 $ADMIN = constant('MAIN_TITLE');
769 // Is the admin logged in?
772 $aid = GET_CURRENT_ADMIN_ID();
775 $ADMIN = GET_ADMIN_EMAIL($aid);
778 // Neutral email address is default
779 $email = constant('WEBMASTER');
781 // Expiration in a nice output format
782 if (getConfig('auto_purge') == 0) {
783 // Will never expire!
784 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
786 // Create nice date string
787 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
790 // Is content an array?
791 if (is_array($content)) {
792 // Add expiration to array, $EXPIRATION is now deprecated!
793 $content['expiration'] = $EXPIRATION;
797 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
798 if (($UID > 0) && (is_array($content))) {
799 // If nickname extension is installed, fetch nickname as well
800 if (EXT_IS_ACTIVE("nickname")) {
801 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
803 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
804 array(bigintval($UID)), __FUNCTION__, __LINE__);
806 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
808 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
809 array(bigintval($UID)), __FUNCTION__, __LINE__);
812 // Fetch and merge data
813 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
814 $content = merge_array($content, SQL_FETCHARRAY($result));
815 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
818 SQL_FREERESULT($result);
821 // Translate M to male or F to female if present
822 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
824 // Overwrite email from data if present
825 if (isset($content['email'])) $email = $content['email'];
827 // Store email for some functions in global data array
828 $DATA['email'] = $email;
831 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
833 // Check for admin/guest/member templates
834 if (strpos($template, "admin_") > -1) {
835 // Admin template found
836 $FQFN = $BASE."admin/".$template.".tpl";
837 } elseif (strpos($template, "guest_") > -1) {
838 // Guest template found
839 $FQFN = $BASE."guest/".$template.".tpl";
840 } elseif (strpos($template, "member_") > -1) {
841 // Member template found
842 $FQFN = $BASE."member/".$template.".tpl";
844 // Test for extension
845 $test = substr($template, 0, strpos($template, "_"));
846 if (EXT_IS_ACTIVE($test)) {
847 // Set extra path to extension's name
848 $FQFN = $BASE.$test."/".$template.".tpl";
850 // No special filename
851 $FQFN = $BASE.$template.".tpl";
855 // Does the special template exists?
856 if (!FILE_READABLE($FQFN)) {
857 // Reset to default template
858 $FQFN = $BASE.$template.".tpl";
861 // Now does the final template exists?
863 if (FILE_READABLE($FQFN)) {
864 // The local file does exists so we load it. :)
865 $tmpl_file = READ_FILE($FQFN);
866 $tmpl_file = SQL_ESCAPE($tmpl_file);
869 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
871 } elseif (!empty($template)) {
872 // Template file not found!
873 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
874 {--TEMPLATE_CONTENT--}
875 <pre>".print_r($content, true)."</pre>
877 <pre>".print_r($DATA, true)."</pre>
880 // Debug mode not active? Then remove the HTML tags
881 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
883 // No template name supplied!
884 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
887 // Is there some content?
888 if (empty($newContent)) {
890 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
891 // Add last error if the required function exists
892 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
895 // Remove content and data
899 // Return compiled content
900 return COMPILE_CODE($newContent);
903 function MAKE_TIME ($H, $M, $S, $stamp) {
904 // Extract day, month and year from given timestamp
905 $DAY = date("d", $stamp);
906 $MONTH = date("m", $stamp);
907 $YEAR = date('Y', $stamp);
909 // Create timestamp for wished time which depends on extracted date
910 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
913 function LOAD_URL ($URL, $addUrlData=true) {
914 // Compile out URI codes
915 $URL = compileUriCode($URL);
917 // Check if http(s):// is there
918 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
919 // Make all URLs full-qualified
924 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
925 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
926 $OUTPUT = ob_get_contents();
928 // Clear it only if there is content
929 if (!empty($OUTPUT)) {
933 // Add some data to URL if cookies are not accepted
934 if (((!defined('__COOKIES')) || (!constant('__COOKIES'))) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
936 // Probe for bot from search engine
937 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
938 // Search engine bot detected so let's rewrite many chars for the link
939 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
941 // Output new location link as anchor
942 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
943 } elseif (!headers_sent()) {
944 // Load URL when headers are not sent
945 //* DEBUG: */ debug_report_bug("URL={$URL}");
946 header ("Location: ".str_replace("&", "&", $URL));
948 // Output error message
949 LOAD_INC("inc/header.php");
950 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
951 LOAD_INC("inc/footer.php");
956 // Wrapper for LOAD_URL but URL comes from a configuration entry
957 function LOAD_CONFIGURED_URL ($configEntry) {
959 $URL = getConfig($configEntry);
964 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
972 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
973 // Is the code a string?
974 if (!is_string($code)) {
975 // Silently return it
979 $ARRAY = $GLOBALS['security_chars'];
981 // Select smaller set of chars to replace when we e.g. want to compile URLs
982 if (!$full) $ARRAY = $GLOBALS['url_chars'];
986 // BEFORE 0.2.1 : Language and data constants
987 // WITH 0.2.1+ : Only language constants
988 $code = str_replace('{--','".', str_replace('--}','."', $code));
990 // BEFORE 0.2.1 : Not used
991 // WITH 0.2.1+ : Data constants
992 $code = str_replace('{!','".', str_replace("!}", '."', $code));
995 // Compile QUOT and other non-HTML codes
996 foreach ($ARRAY['to'] as $k => $to) {
997 // Do the reversed thing as in inc/libs/security_functions.php
998 $code = str_replace($to, $ARRAY['from'][$k], $code);
1001 // But shall I keep simple quotes for later use?
1002 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1004 // Find $content[bla][blub] entries
1005 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1007 // Are some matches found?
1008 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1009 // Replace all matches
1010 $matchesFound = array();
1011 foreach ($matches[0] as $key => $match) {
1012 // Fuzzy look has failed by default
1013 $fuzzyFound = false;
1015 // Fuzzy look on match if already found
1016 foreach ($matchesFound as $found => $set) {
1018 $test = substr($found, 0, strlen($match));
1020 // Does this entry exist?
1021 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1022 if ($test == $match) {
1024 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1031 if ($fuzzyFound) continue;
1033 // Take all string elements
1034 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1035 // Replace it in the code
1036 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1037 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1038 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1039 $matchesFound[$key."_".$matches[4][$key]] = 1;
1040 $matchesFound[$match] = 1;
1041 } elseif (!isset($matchesFound[$match])) {
1042 // Not yet replaced!
1043 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1044 $code = str_replace($match, "\".".$match.".\"", $code);
1045 $matchesFound[$match] = 1;
1050 // Return compiled code
1054 /************************************************************************
1056 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1057 * $a_sort sortiert: *
1059 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1060 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1061 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1062 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1063 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1065 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1066 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1067 * Sie, dass es doch nicht so schwer ist! :-) *
1069 ************************************************************************/
1070 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1072 while ($primary_key < count($a_sort)) {
1073 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1074 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1077 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1078 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1079 } elseif ($key != $key2) {
1080 // Sort numbers (E.g.: 9 < 10)
1081 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1082 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1086 // We have found two different values, so let's sort whole array
1087 foreach ($dummy as $sort_key => $sort_val) {
1088 $t = $dummy[$sort_key][$key];
1089 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1090 $dummy[$sort_key][$key2] = $t;
1101 // Write back sorted array
1106 function ADD_SELECTION ($type, $DEFAULT, $prefix="", $id="0") {
1109 if ($type == "yn") {
1110 // This is a yes/no selection only!
1111 if ($id > 0) $prefix .= "[".$id."]";
1112 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1114 // Begin with regular selection box here
1115 if (!empty($prefix)) $prefix .= "_";
1117 if ($id > 0) $type2 .= "[".$id."]";
1118 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1123 for ($idx = 1; $idx < 32; $idx++) {
1124 $OUT .= "<option value=\"".$idx."\"";
1125 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1126 $OUT .= ">".$idx."</option>\n";
1130 case "month": // Month
1131 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1132 $OUT .= "<option value=\"".$month."\"";
1133 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1134 $OUT .= ">".$descr."</option>\n";
1138 case "year": // Year
1140 $YEAR = date('Y', time());
1142 // Use configured min age or fixed?
1143 if (GET_EXT_VERSION("other") >= "0.2.1") {
1145 $startYear = $YEAR - getConfig('min_age');
1148 $startYear = $YEAR - 16;
1151 // Calculate earliest year (100 years old people can still enter Internet???)
1152 $minYear = $YEAR - 100;
1154 // Check if the default value is larger than minimum and bigger than actual year
1155 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1156 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1157 $OUT .= "<option value=\"".$idx."\"";
1158 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1159 $OUT .= ">".$idx."</option>\n";
1161 } elseif ($DEFAULT == -1) {
1162 // Current year minus 1
1163 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1165 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1168 // Get current year and subtract the configured minimum age
1169 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1170 // Calculate earliest year depending on extension version
1171 if (GET_EXT_VERSION("other") >= "0.2.1") {
1172 // Use configured minimum age
1173 $YEAR = date('Y', time()) - getConfig('min_age');
1175 // Use fixed 16 years age
1176 $YEAR = date('Y', time()) - 16;
1179 // Construct year selection list
1180 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1181 $OUT .= "<option value=\"".$idx."\"";
1182 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1183 $OUT .= ">".$idx."</option>\n";
1190 for ($idx = 0; $idx < 60; $idx+=5) {
1191 if (strlen($idx) == 1) $idx = "0".$idx;
1192 $OUT .= "<option value=\"".$idx."\"";
1193 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1194 $OUT .= ">".$idx."</option>\n";
1199 for ($idx = 0; $idx < 24; $idx++) {
1200 if (strlen($idx) == 1) $idx = "0".$idx;
1201 $OUT .= "<option value=\"".$idx."\"";
1202 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1203 $OUT .= ">".$idx."</option>\n";
1208 $OUT .= "<option value=\"Y\"";
1209 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1210 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1211 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1212 $OUT .= ">{--NO--}</option>\n";
1215 $OUT .= " </select>\n";
1220 function TRANSLATE_YESNO ($yn) {
1222 $translated = "??? (".$yn.")";
1224 case "Y": $translated = getMessage('YES'); break;
1225 case "N": $translated = getMessage('NO'); break;
1227 // Log unknown value
1228 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
1237 // Deprecated : $length
1240 function generateRandomCodde ($length, $code, $uid, $DATA="") {
1241 // Fix missing _MAX constant
1242 // @TODO Rewrite this unnice code
1243 if (!defined('_MAX')) define('_MAX', 15235);
1245 // Build server string
1246 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
1249 $keys = constant('SITE_KEY').":".constant('DATE_KEY');
1250 if (isConfigEntrySet('secret_key')) $keys .= ":".getConfig('secret_key');
1251 if (isConfigEntrySet('file_hash')) $keys .= ":".getConfig('file_hash');
1252 $keys .= ":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1253 if (isConfigEntrySet('master_salt')) $keys .= ":".getConfig('master_salt');
1255 // Build string from misc data
1256 $data = $code.":".$uid.":".$DATA;
1258 // Add more additional data
1259 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1260 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1261 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1262 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1263 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1265 // Calculate number for generating the code
1266 $a = $code + constant('_ADD') - 1;
1268 if (isConfigEntrySet('master_hash')) {
1269 // Generate hash with master salt from modula of number with the prime number and other data
1270 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1272 // Create number from hash
1273 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1275 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1276 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(constant('SITE_KEY')), 0, 8));
1278 // Create number from hash
1279 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1282 // At least 10 numbers shall be secure enought!
1283 $len = getConfig('code_length');
1284 if ($len == 0) $len = $length;
1285 if ($len == 0) $len = 10;
1287 // Cut off requested counts of number
1288 $return = substr(str_replace('.', "", $rcode), 0, $len);
1290 // Done building code
1294 // Does only allow numbers
1295 function bigintval ($num, $castValue = true) {
1296 // Filter all numbers out
1297 $ret = preg_replace("/[^0123456789]/", "", $num);
1300 if ($castValue) $ret = (double)$ret;
1302 // Has the whole value changed?
1303 // @TODO Remove this if() block if all is working fine
1304 if ("".$ret."" != "".$num."") {
1306 debug_report_bug("{$ret}<>{$num}");
1313 // Insert the code in $img_code into jpeg or PNG image
1314 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1315 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1316 // Stop execution of function here because of over-sized code length
1318 } elseif (!$headerSent) {
1319 // Return in an HTML code code
1320 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1324 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1325 if (FILE_READABLE($img)) {
1326 // Switch image type
1327 switch (getConfig('img_type'))
1330 // Okay, load image and hide all errors
1331 $image = @imagecreatefromjpeg($img);
1335 // Okay, load image and hide all errors
1336 $image = @imagecreatefrompng($img);
1340 // Exit function here
1341 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1345 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1346 $text_color = imagecolorallocate($image, 0, 0, 0);
1348 // Insert code into image
1349 imagestring($image, 5, 14, 2, $img_code, $text_color);
1351 // Return to browser
1352 header ("Content-Type: image/".getConfig('img_type'));
1354 // Output image with matching image factory
1355 switch (getConfig('img_type')) {
1356 case "jpg": imagejpeg($image); break;
1357 case "png": imagepng($image); break;
1360 // Remove image from memory
1361 imagedestroy($image);
1363 // Create selection box or array of splitted timestamp
1364 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1365 // Calculate 2-seconds timestamp
1366 $stamp = round($timestamp);
1367 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1369 // Do we have a leap year?
1371 $TEST = date('Y', time()) / 4;
1372 $M1 = date("m", time());
1373 $M2 = date("m", (time() + $timestamp));
1375 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1376 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1378 // First of all years...
1379 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1380 //* DEBUG: */ print("Y={$Y}<br />\n");
1382 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1383 //* DEBUG: */ print("M={$M}<br />\n");
1385 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1386 //* DEBUG: */ print("W={$W}<br />\n");
1388 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1389 //* DEBUG: */ print("D={$D}<br />\n");
1391 $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));
1392 //* DEBUG: */ print("h={$h}<br />\n");
1394 $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));
1395 //* DEBUG: */ print("m={$m}<br />\n");
1396 // And at last seconds...
1397 $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));
1398 //* DEBUG: */ print("s={$s}<br />\n");
1400 // Is seconds zero and time is < 60 seconds?
1401 if (($s == 0) && ($timestamp < 60)) {
1403 $s = round($timestamp);
1407 // Now we convert them in seconds...
1409 if ($return_array) {
1410 // Just put all data in an array for later use
1422 $OUT = "<div align=\"".$align."\">\n";
1423 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1426 if (ereg('Y', $display) || (empty($display))) {
1427 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1430 if (ereg("M", $display) || (empty($display))) {
1431 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1434 if (ereg("W", $display) || (empty($display))) {
1435 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1438 if (ereg("D", $display) || (empty($display))) {
1439 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1442 if (ereg("h", $display) || (empty($display))) {
1443 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1446 if (ereg("m", $display) || (empty($display))) {
1447 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1450 if (ereg("s", $display) || (empty($display))) {
1451 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1457 if (ereg('Y', $display) || (empty($display))) {
1458 // Generate year selection
1459 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1460 for ($idx = 0; $idx <= 10; $idx++) {
1461 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1462 if ($idx == $Y) $OUT .= " selected=\"selected\"";
1463 $OUT .= ">".$idx."</option>\n";
1465 $OUT .= " </select></td>\n";
1467 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1470 if (ereg("M", $display) || (empty($display))) {
1471 // Generate month selection
1472 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1473 for ($idx = 0; $idx <= 11; $idx++)
1475 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1476 if ($idx == $M) $OUT .= " selected=\"selected\"";
1477 $OUT .= ">".$idx."</option>\n";
1479 $OUT .= " </select></td>\n";
1481 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1484 if (ereg("W", $display) || (empty($display))) {
1485 // Generate week selection
1486 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1487 for ($idx = 0; $idx <= 4; $idx++) {
1488 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1489 if ($idx == $W) $OUT .= " selected=\"selected\"";
1490 $OUT .= ">".$idx."</option>\n";
1492 $OUT .= " </select></td>\n";
1494 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1497 if (ereg("D", $display) || (empty($display))) {
1498 // Generate day selection
1499 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1500 for ($idx = 0; $idx <= 31; $idx++) {
1501 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1502 if ($idx == $D) $OUT .= " selected=\"selected\"";
1503 $OUT .= ">".$idx."</option>\n";
1505 $OUT .= " </select></td>\n";
1507 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1510 if (ereg("h", $display) || (empty($display))) {
1511 // Generate hour selection
1512 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1513 for ($idx = 0; $idx <= 23; $idx++) {
1514 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1515 if ($idx == $h) $OUT .= " selected=\"selected\"";
1516 $OUT .= ">".$idx."</option>\n";
1518 $OUT .= " </select></td>\n";
1520 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1523 if (ereg("m", $display) || (empty($display))) {
1524 // Generate minute selection
1525 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1526 for ($idx = 0; $idx <= 59; $idx++) {
1527 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1528 if ($idx == $m) $OUT .= " selected=\"selected\"";
1529 $OUT .= ">".$idx."</option>\n";
1531 $OUT .= " </select></td>\n";
1533 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1536 if (ereg("s", $display) || (empty($display))) {
1537 // Generate second selection
1538 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1539 for ($idx = 0; $idx <= 59; $idx++) {
1540 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1541 if ($idx == $s) $OUT .= " selected=\"selected\"";
1542 $OUT .= ">".$idx."</option>\n";
1544 $OUT .= " </select></td>\n";
1546 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1549 $OUT .= "</table>\n";
1551 // Return generated HTML code
1557 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1558 // Initial return value
1561 // Do we have a leap year?
1563 $TEST = date('Y', time()) / 4;
1564 $M1 = date("m", time());
1565 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1566 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1567 // First add years...
1568 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1570 $ret += $POST[$prefix."_mo"] * 2628000;
1572 $ret += $POST[$prefix."_we"] * 604800;
1574 $ret += $POST[$prefix."_da"] * 86400;
1576 $ret += $POST[$prefix."_ho"] * 3600;
1578 $ret += $POST[$prefix."_mi"] * 60;
1579 // And at last seconds...
1580 $ret += $POST[$prefix."_se"];
1581 // Return calculated value
1585 // Sends out mail to all administrators
1586 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1587 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1588 // Trim template name
1589 $template = trim($template);
1591 // Load email template
1592 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1594 // Check which admin shall receive this mail
1595 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1596 array($template), __FUNCTION__, __LINE__);
1597 if (SQL_NUMROWS($result) == 0) {
1598 // Create new entry (to all admins)
1599 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1600 array($template), __FUNCTION__, __LINE__);
1602 // Load admin IDs...
1603 // @TODO This can be, somehow, rewritten
1604 $adminIds = array();
1605 while ($content = SQL_FETCHARRAY($result)) {
1606 $adminIds[] = $content['admin_id'];
1610 SQL_FREERESULT($result);
1615 // "implode" IDs and query string
1616 $aid = implode(",", $adminIds);
1618 if (EXT_IS_ACTIVE("events")) {
1619 // Add line to user events
1620 EVENTS_ADD_LINE($subj, $msg, $UID);
1622 // Log error for debug
1623 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1629 } elseif ($aid == "0") {
1630 // Select all email adresses
1631 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1632 __FUNCTION__, __LINE__);
1634 // If Admin-ID is not "to-all" select
1635 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1636 array($aid), __FUNCTION__, __LINE__);
1640 // Load email addresses and send away
1641 while ($content = SQL_FETCHARRAY($result)) {
1642 SEND_EMAIL($content['email'], $subj, $msg);
1646 SQL_FREERESULT($result);
1650 function CREATE_FANCY_TIME ($stamp) {
1651 // Get data array with years/months/weeks/days/...
1652 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1654 foreach($data as $k => $v) {
1656 // Value is greater than 0 "eval" data to return string
1657 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1663 // Do we have something there?
1664 if (strlen($ret) > 0) {
1665 // Remove leading commata and space
1666 $ret = substr($ret, 2);
1669 $ret = "0 {--_SECONDS--}";
1672 // Return fancy time string
1677 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1678 $SEP = ""; $TOP = "";
1681 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1685 for ($page = 1; $page <= $PAGES; $page++) {
1686 // Is the page currently selected or shall we generate a link to it?
1687 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1688 // Is currently selected, so only highlight it
1689 $NAV .= "<strong>-";
1691 // Open anchor tag and add base URL
1692 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1694 // Add userid when we shall show all mails from a single member
1695 if ((REQUEST_ISSET_GET(('uid'))) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1697 // Close open anchor tag
1701 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1702 // Is currently selected, so only highlight it
1703 $NAV .= "-</strong>";
1709 // Add seperator if we have not yet reached total pages
1710 if ($page < $PAGES) $NAV .= " | ";
1713 // Define constants only once
1714 if (!defined('__NAV_OUTPUT')) {
1715 define('__NAV_OUTPUT' , $NAV);
1716 define('__NAV_COLSPAN', $colspan);
1717 define('__NAV_TOP' , $TOP);
1718 define('__NAV_SEP' , $SEP);
1721 // Load navigation template
1722 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1724 if ($return === true) {
1725 // Return generated HTML-Code
1733 // Extract host from script name
1734 function EXTRACT_HOST (&$script) {
1735 // Use default SERVER_URL by default... ;) So?
1736 $url = constant('SERVER_URL');
1738 // Is this URL valid?
1739 if (substr($script, 0, 7) == "http://") {
1740 // Use the hostname from script URL as new hostname
1741 $url = substr($script, 7);
1742 $extract = explode("/", $url);
1744 // Done extracting the URL :)
1747 // Extract host name
1748 $host = str_replace("http://", "", $url);
1749 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1751 // Generate relative URL
1752 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1753 if (substr(strtolower($script), 0, 7) == "http://") {
1754 // But only if http:// is in front!
1755 $script = substr($script, (strlen($url) + 7));
1756 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1758 $script = substr($script, (strlen($url) + 8));
1761 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1762 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1768 // Send a GET request
1769 function GET_URL ($script) {
1770 // Compile the script name
1771 $script = COMPILE_CODE($script);
1773 // Extract host name from script
1774 $host = EXTRACT_HOST($script);
1776 // Generate GET request header
1777 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1778 $request .= "Host: " . $host . "\r\n";
1779 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1780 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1781 $request .= "Content-Type: text/plain\r\n";
1782 $request .= "Cache-Control: no-cache\r\n";
1783 $request .= "Connection: Close\r\n\r\n";
1785 // Send the raw request
1786 $response = SEND_RAW_REQUEST($host, $request);
1788 // Return the result to the caller function
1792 // Send a POST request
1793 function POST_URL ($script, $postData) {
1794 // Is postData an array?
1795 if (!is_array($postData)) {
1797 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1798 return array("", "", "");
1801 // Compile the script name
1802 $script = COMPILE_CODE($script);
1804 // Extract host name from script
1805 $host = EXTRACT_HOST($script);
1807 // Construct request
1808 $data = http_build_query($postData, '','&');
1810 // Generate POST request header
1811 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1812 $request .= "Host: " . $host . "\r\n";
1813 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1814 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1815 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1816 $request .= "Content-length: " . strlen($data) . "\r\n";
1817 $request .= "Cache-Control: no-cache\r\n";
1818 $request .= "Connection: Close\r\n\r\n";
1821 // Send the raw request
1822 $response = SEND_RAW_REQUEST($host, $request);
1824 // Return the result to the caller function
1828 // Sends a raw request to another host
1829 function SEND_RAW_REQUEST ($host, $request) {
1831 $response = array("", "", "");
1833 // Default is not to use proxy
1836 // Are proxy settins set?
1837 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1843 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1845 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1847 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1851 if (!is_resource($fp)) {
1858 // Generate CONNECT request header
1859 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1860 $proxyTunnel .= "Host: ".$host."\r\n";
1862 // Use login data to proxy? (username at least!)
1863 if (getConfig('proxy_username') != "") {
1865 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1866 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1869 // Add last new-line
1870 $proxyTunnel .= "\r\n";
1871 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1874 fputs($fp, $proxyTunnel);
1878 // No response received
1882 // Read the first line
1883 $resp = trim(fgets($fp, 10240));
1884 $respArray = explode(" ", $resp);
1885 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1886 // Invalid response!
1892 fputs($fp, $request);
1895 while (!feof($fp)) {
1896 $response[] = trim(fgets($fp, 1024));
1902 // Skip first empty lines
1904 foreach ($resp as $idx => $line) {
1906 $line = trim($line);
1908 // Is this line empty?
1911 array_shift($response);
1913 // Abort on first non-empty line
1918 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1920 // Proxy agent found?
1921 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1922 // Proxy header detected, so remove two lines
1923 array_shift($response);
1924 array_shift($response);
1927 // Was the request successfull?
1928 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1929 // Not found / access forbidden
1930 $response = array("", "", "");
1937 // Taken from www.php.net eregi() user comments
1938 function VALIDATE_EMAIL ($email) {
1940 $email = COMPILE_CODE($email);
1942 // Check first part of email address
1943 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1946 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1949 $regex = "^".$first."@".$domain."$";
1951 // Return check result
1952 return eregi($regex, $email);
1955 // Function taken from user comments on www.php.net / function eregi()
1956 function VALIDATE_URL ($URL, $compile=true) {
1957 // Trim URL a little
1958 $URL = trim(urldecode($URL));
1959 //* DEBUG: */ echo $URL."<br />";
1961 // Compile some chars out...
1962 if ($compile) $URL = compileUriCode($URL, false, false, false);
1963 //* DEBUG: */ echo $URL."<br />";
1965 // Check for the extension filter
1966 if (EXT_IS_ACTIVE("filter")) {
1967 // Use the extension's filter set
1968 return FILTER_VALIDATE_URL($URL, false);
1971 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1972 // https:// in front of the URLs
1973 return isUrlValid($URL);
1976 // Generate a list of administrative links to a given userid
1977 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1978 // Define all main targets
1979 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1981 // Begin of navigation links
1982 $eval = "\$OUT = \"[ ";
1984 foreach ($TARGETS as $tar) {
1985 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1986 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1987 if (($tar == "lock_user") && ($status == "LOCKED")) {
1988 // Locked accounts shall be unlocked
1989 $eval .= "UNLOCK_USER";
1991 // All other status is fine
1992 $eval .= strtoupper($tar);
1994 $eval .= "_TITLE--}\\\">{--ADMIN_";
1995 if (($tar == "lock_user") && ($status == "LOCKED")) {
1996 // Locked accounts shall be unlocked
1997 $eval .= "UNLOCK_USER";
1999 // All other status is fine
2000 $eval .= strtoupper($tar);
2002 $eval .= "--}</a></span> | ";
2005 // Finish navigation link
2006 $eval = substr($eval, 0, -7)."]\";";
2013 // Generate an email link
2014 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2015 // Default email link (INSECURE! Spammer can read this by harvester programs)
2016 $EMAIL = "mailto:".$email;
2018 // Check for several extensions
2019 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2020 // Create email link for contacting admin in guest area
2021 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2022 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2023 // Create email link for contacting a member within admin area (or later in other areas, too?)
2024 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2025 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2026 // Create email link to contact sponsor within admin area (or like the link above?)
2027 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2030 // Shall I close the link when there is no admin?
2031 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2033 // Return email link
2037 // Generate a hash for extra-security for all passwords
2038 function generateHash ($plainText, $salt = "") {
2041 // Is the required extension "sql_patches" there and a salt is not given?
2042 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2043 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2044 return md5($plainText);
2047 // Do we miss an arry element here?
2048 if (!isConfigEntrySet('file_hash')) {
2050 debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
2053 // When the salt is empty build a new one, else use the first x configured characters as the salt
2055 // Build server string
2056 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
2059 $keys = constant('SITE_KEY').":".constant('DATE_KEY').":".getConfig('secret_key').":".getConfig('file_hash').":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).":".getConfig('master_salt');
2062 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2064 // Calculate number for generating the code
2065 $a = time() + constant('_ADD') - 1;
2067 // Generate SHA1 sum from modula of number and the prime number
2068 $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2069 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2070 $sha1 = scrambleString($sha1);
2071 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2072 //* DEBUG: */ $sha1b = descrambleString($sha1);
2073 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2075 // Generate the password salt string
2076 $salt = substr($sha1, 0, getConfig('salt_length'));
2077 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2080 $salt = substr($salt, 0, getConfig('salt_length'));
2081 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2085 return $salt.sha1($salt.$plainText);
2088 // Scramble a string
2089 function scrambleString($str) {
2093 // Final check, in case of failture it will return unscrambled string
2094 if (strlen($str) > 40) {
2095 // The string is to long
2097 } elseif (strlen($str) == 40) {
2099 $scrambleNums = explode(":", getConfig('pass_scramble'));
2101 // Generate new numbers
2102 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2105 // Scramble string here
2106 //* DEBUG: */ echo "***Original=".$str."***<br />";
2107 for ($idx = 0; $idx < strlen($str); $idx++) {
2108 // Get char on scrambled position
2109 $char = substr($str, $scrambleNums[$idx], 1);
2111 // Add it to final output string
2112 $scrambled .= $char;
2115 // Return scrambled string
2116 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2120 // De-scramble a string scrambled by scrambleString()
2121 function descrambleString($str) {
2122 // Scramble only 40 chars long strings
2123 if (strlen($str) != 40) return $str;
2125 // Load numbers from config
2126 $scrambleNums = explode(":", getConfig('pass_scramble'));
2129 if (count($scrambleNums) != 40) return $str;
2131 // Begin descrambling
2132 $orig = str_repeat(" ", 40);
2133 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2134 for ($idx = 0; $idx < 40; $idx++) {
2135 $char = substr($str, $idx, 1);
2136 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2139 // Return scrambled string
2140 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2144 // Generated a "string" for scrambling
2145 function genScrambleString ($len) {
2146 // Prepare array for the numbers
2147 $scrambleNumbers = array();
2149 // First we need to setup randomized numbers from 0 to 31
2150 for ($idx = 0; $idx < $len; $idx++) {
2152 $rand = mt_rand(0, ($len -1));
2154 // Check for it by creating more numbers
2155 while (array_key_exists($rand, $scrambleNumbers)) {
2156 $rand = mt_rand(0, ($len -1));
2160 $scrambleNumbers[$rand] = $rand;
2163 // So let's create the string for storing it in database
2164 $scrambleString = implode(":", $scrambleNumbers);
2165 return $scrambleString;
2168 // Append data like session ID or referal ID to the given URL which would
2169 // normally be stored in cookies
2170 function ADD_URL_DATA ($URL) {
2174 // Determine URL binder
2176 if (strpos($URL, "?") !== false) $BIND = "&";
2178 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2179 // Cookies are not accepted
2180 if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
2181 // Cookie found in URL
2182 $ADD .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
2183 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2184 // Not found! So let's set default here
2185 $ADD .= $BIND."refid=".getConfig('def_refid');
2189 // Add all together and return it
2193 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2194 function generatePassString ($passHash) {
2195 // Return vanilla password hash
2198 // Is a secret key and master salt already initialized?
2199 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2200 // Only calculate when the secret key is generated
2201 $newHash = ""; $start = 9;
2202 for ($idx = 0; $idx < 10; $idx++) {
2203 $part1 = hexdec(substr($passHash, $start, 4));
2204 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2205 $mod = dechex($idx);
2206 if ($part1 > $part2) {
2207 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2208 } elseif ($part2 > $part1) {
2209 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2211 $mod = substr(round($mod), 0, 4);
2212 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2213 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2218 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2219 $ret = generateHash($newHash, getConfig('master_salt'));
2220 //* DEBUG: */ print($ret."<br />\n");
2223 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2224 $ret = md5($passHash);
2225 //* DEBUG: */ echo "++".$ret."++<br />\n";
2232 // Fix "deleted" cookies
2233 function FIX_DELETED_COOKIES ($cookies) {
2234 // Is this an array with entries?
2235 if ((is_array($cookies)) && (count($cookies) > 0)) {
2236 // Then check all cookies if they are marked as deleted!
2237 foreach ($cookies as $cookieName) {
2238 // Is the cookie set to "deleted"?
2239 if (get_session($cookieName) == "deleted") {
2240 set_session($cookieName, "");
2246 // Output error messages in a fasioned way and die...
2247 function mxchange_die ($msg) {
2249 LOAD_INC_ONCE("inc/header.php");
2251 // Load the message template
2252 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2255 LOAD_INC_ONCE("inc/footer.php");
2261 // Display parsing time and number of SQL queries in footer
2262 function DISPLAY_PARSING_TIME_FOOTER() {
2263 // Is the timer started?
2264 if (!isset($GLOBALS['startTime'])) {
2270 $endTime = microtime(true);
2272 // "Explode" both times
2273 $start = explode(" ", $GLOBALS['startTime']);
2274 $end = explode(" ", $endTime);
2275 $runTime = $end[0] - $start[0];
2276 if ($runTime < 0) $runTime = 0;
2277 $runTime = TRANSLATE_COMMA($runTime);
2281 'runtime' => $runTime,
2282 'numSQLs' => (getConfig('sql_count') + 1),
2283 'numTemplates' => (getConfig('num_templates') + 1)
2286 // Load the template
2287 LOAD_TEMPLATE("show_timings", false, $content);
2290 // Check wether a boolean constant is set
2291 // Taken from user comments in PHP documentation for function constant()
2292 function isBooleanConstantAndTrue ($constName) { // : Boolean
2293 // Failed by default
2297 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2299 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2300 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2303 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2304 if (defined($constName)) {
2306 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2307 $res = (constant($constName) === true);
2311 $GLOBALS['cache_array']['const'][$constName] = $res;
2313 //* DEBUG: */ var_dump($res);
2319 // Checks if a given apache module is loaded
2320 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2321 // Check it and return result
2322 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2325 // "Getter" for language strings
2326 // @TODO Rewrite all language constants to this function.
2327 function getMessage ($messageId) {
2328 // Default is not found!
2329 $return = "!".$messageId."!";
2331 // Is the language string found?
2332 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2333 // Language array element found in small_letters
2334 $return = $GLOBALS['msg'][$messageId];
2335 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2336 // @DEPRECATED Language array element found in BIG_LETTERS
2337 $return = $GLOBALS['msg'][$messageId];
2338 } elseif (defined($messageId)) {
2339 // @DEPRECATED Deprecated constant found
2340 $return = constant($messageId);
2342 // Missing language constant
2343 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2346 // Return the string
2350 // Get current theme name
2351 function GET_CURR_THEME() {
2354 // The default theme is 'default'... ;-)
2357 // Load default theme if not empty from configuration
2358 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2360 if (!isSessionVariableSet('mxchange_theme')) {
2361 // Set default theme
2362 set_session('mxchange_theme', $ret);
2363 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2364 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2365 // Get theme from cookie
2366 $ret = get_session('mxchange_theme');
2369 if (THEME_GET_ID($ret) == 0) {
2370 // Fix it to default
2373 } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET(('theme'))) || (REQUEST_ISSET_POST(('theme'))))) {
2374 // Prepare FQFN for checking
2375 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET(('theme')));
2377 // Installation mode active
2378 if ((REQUEST_ISSET_GET(('theme'))) && (FILE_READABLE($theme))) {
2379 // Set cookie from URL data
2380 set_session('mxchange_theme', REQUEST_GET(('theme')));
2381 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2382 // Set cookie from posted data
2383 set_session('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2387 $ret = get_session('mxchange_theme');
2389 // Invalid design, reset cookie
2390 set_session('mxchange_theme', $ret);
2393 // Add (maybe) found theme.php file to inclusion list
2394 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($ret));
2396 // Try to load the requested include file
2397 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2399 // Return theme value
2403 // Get id from theme
2404 function THEME_GET_ID ($name) {
2405 // Is the extension "theme" installed?
2406 if (!EXT_IS_ACTIVE("theme")) {
2414 // Is the cache entry there?
2415 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2416 // Get the version from cache
2417 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2420 incrementConfigEntry('cache_hits');
2421 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2422 // Check if current theme is already imported or not
2423 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2424 array($name), __FUNCTION__, __LINE__);
2427 if (SQL_NUMROWS($result) == 1) {
2429 list($id) = SQL_FETCHROW($result);
2433 SQL_FREERESULT($result);
2440 // Read a given file
2441 function READ_FILE ($FQFN, $sqlPrepare = false) {
2443 if (function_exists('file_get_contents')) {
2445 $content = file_get_contents($FQFN);
2447 // Fall-back to implode-file chain
2448 $content = implode("", file($FQFN));
2451 // Prepare SQL queries?
2452 if ($sqlPrepare === true) {
2453 // Remove some unwanted chars
2454 $content = str_replace("\r", "", $content);
2455 $content = str_replace("\n\n", "\n", $content);
2458 // Return the content
2462 // Writes content to a file
2463 function WRITE_FILE ($FQFN, $content) {
2464 // Is the file writeable?
2465 if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
2467 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
2473 // By default all is failed...
2476 // Is the function there?
2477 if (function_exists('file_put_contents')) {
2478 // Write it directly
2479 $return = file_put_contents($FQFN, $content);
2481 // Write it with fopen
2482 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
2483 fwrite($fp, $content);
2487 $return = chmod($FQFN, 0644);
2494 // Generates an error code from given account status
2495 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
2496 // Default error code if unknown account status
2497 $ERROR = constant('CODE_UNKNOWN_STATUS');
2499 // Generate constant name
2500 $constantName = sprintf("CODE_ID_%s", $status);
2502 // Is the constant there?
2503 if (defined($constantName)) {
2505 $ERROR = constant($constantName);
2508 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2511 // Return error code
2515 // Clears the output buffer. This function does *NOT* backup sent content.
2516 function clearOutputBuffer () {
2517 // Trigger an error on failure
2518 if (!ob_end_clean()) {
2520 debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
2524 // Function to search for the last modifikated file
2525 function searchDirsRecoursive($dir, &$last_changed) {
2526 $ds = scandir($dir); // Needs adjustment for PHP < 5.0.0!!
2527 foreach ($ds as $d) {
2528 $f_name = $dir.'/'.$d; // makes a proper Filename
2529 if (!preg_match('@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache)$@',$d)) { // no . or .. or .revision or .svn in the filename
2530 $is_dir = is_dir($f_name);
2531 if (!$is_dir) { // $f_name is a filename and no directory
2532 $time = filemtime($f_name);
2533 if ($last_changed['time'] < $time) { // This file is newer as the file before
2534 $last_changed['path_name'] = $f_name;
2535 $last_changed['time'] = $time;
2537 } elseif ($is_dir) { // $f_name is a directory so also crawl into this directory
2538 searchDirsRecoursive($f_name, $last_changed);
2545 // "Getter" for revision/version data
2546 function getActualVersion ($type = 'Revision') {
2547 // By default nothing is new... ;-)
2550 if (EXT_IS_ACTIVE("cache")) {
2551 // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
2552 if (isset($_GET['check_revision_data']) && $_GET['check_revision_data'] == 'yes') $new = true;
2553 if (!isset($GLOBALS['cache_array']['revision'][$type])
2554 || count($GLOBALS['cache_array']['revision']) < 3
2555 || !$GLOBALS['cache_instance']->loadCacheFile("revision")) $new = true;
2559 $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
2561 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2562 unset($GLOBALS['cache_array']['revision']);
2563 // Reload load_cach-revison.php
2564 LOAD_INC('inc/loader/load_cache-revision.php');
2567 return $GLOBALS['cache_array']['revision'][$type][0];
2570 // old Version without ext-cache aktive (depricated ?)
2572 // FQFN of revision file
2573 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2575 // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
2576 if (isset($_GET['check_revision_data']) && $_GET['check_revision_data'] == 'yes') {
2580 // Check for revision file
2581 if (!FILE_READABLE($FQFN)) {
2582 // Not found, so we need to create it
2585 // Revision file found
2586 $ins_vers = explode("\n", READ_FILE($FQFN));
2588 // Is the content valid?
2589 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$type])) || (trim($ins_vers[$type]) == '') || ($ins_vers[0]) == "new") {
2590 // File needs update!
2593 // Revision-File has valid Data and isn't 'new' so return the Rev-Number
2594 $ttype = array_search ($type,array_keys(getSearchFor()));
2595 if ($ttype || $ttype != null) return trim($ins_vers[$ttype]);
2600 // Has it been updated?
2601 if ($new === true) {
2602 WRITE_FILE($FQFN, implode("\n", getAkt_vers()));
2606 function getSearchFor()
2608 $searchFor[] = 'Revision';
2609 $searchFor[] = 'Date';
2610 $searchFor[] = 'Tag';
2611 $searchFor[] = 'Author';
2618 function getAkt_vers()
2621 $last_changed['path_name'] = '';
2622 $last_changed['time'] = 0;
2623 $akt_vers = array();
2624 searchDirsRecoursive($next_dir, $last_changed); //Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2625 $last_file = READ_FILE($last_changed['path_name']);
2627 $searchFor = getSearchFor();
2629 foreach ($searchFor as $search) {
2630 $ergeb += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
2631 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2634 if ($ergeb && $ergeb >= 3) {
2636 preg_match('@(....)-(..)-(..) (..):(..):(..)@',$akt_vers['Date'],$match_d);
2637 $akt_vers['Date'] = mktime($match_d[4],$match_d[5],$match_d[6],$match_d[2],$match_d[3],$match_d[1]);
2638 if (isset($akt_vers['Author']) && $akt_vers['Author'] != 'quix0r') $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2640 // no valid Data from the last modificated file so read the Revision from the Server. FallbackSolution!! Could be removed I think.
2641 $version = GET_URL("check-updates3.php");
2643 $akt_vers['Revision'] = trim($version[10]);
2644 $akt_vers['Date'] = trim($version[9]);
2645 $akt_vers['Tag'] = trim($version[8]);
2651 // Loads an include file and logs any missing files for debug purposes
2652 function LOAD_INC ($INC) {
2653 // Add the path. This is why we need a trailing slash in config.php
2654 $FQFN = constant('PATH') . $INC;
2656 // Is the include file there?
2657 if (!FILE_READABLE($FQFN)) {
2658 // Not there so log it
2659 debug_report_bug(sprintf("Include file %s not found.", $INC));
2667 // Loads an include file once
2668 function LOAD_INC_ONCE ($INC) {
2669 // Is it not loaded?
2670 if (!isset($GLOBALS['load_once'][$INC])) {
2671 // Then try to load it
2674 // And mark it as loaded
2675 $GLOBALS['load_once'][$INC] = "loaded";
2679 // Back-ported from the new ship-simu engine. :-)
2680 function debug_get_printable_backtrace () {
2682 $backtrace = "<ol>\n";
2684 // Get and prepare backtrace for output
2685 $backtraceArray = debug_backtrace();
2686 foreach ($backtraceArray as $key => $trace) {
2687 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2688 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2689 if (!isset($trace['args'])) $trace['args'] = array();
2690 $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";
2694 $backtrace .= "</ol>\n";
2696 // Return the backtrace
2700 // Output a debug backtrace to the user
2701 function debug_report_bug ($message = "") {
2704 // Is the optional message set?
2705 if (!empty($message)) {
2707 $debug = sprintf("Note: %s<br />\n",
2711 // @TODO Add a little more infos here
2712 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2716 $debug .= ("Please report this error at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>");
2717 $debug .= (debug_get_printable_backtrace());
2718 $debug .= ("</pre>Thank you for your help finding bugs.");
2724 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2725 function generateSeed () {
2726 list($usec, $sec) = explode(" ", microtime());
2727 return ((float)$sec + (float)$usec);
2730 // Converts a message code to a human-readable message
2731 function convertCodeToMessage ($code) {
2734 case constant('CODE_LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
2735 case constant('CODE_LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2736 case constant('CODE_DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
2737 case constant('CODE_POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2738 case constant('CODE_ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2739 case constant('CODE_USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
2740 case constant('CODE_STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
2741 case constant('CODE_ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2743 case constant('CODE_ERROR_MAILID'):
2744 if (EXT_IS_ACTIVE($ext, true)) {
2745 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2747 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
2751 case constant('CODE_EXTENSION_PROBLEM'):
2752 if (REQUEST_ISSET_GET(('ext'))) {
2753 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
2755 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2759 case constant('CODE_COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2760 case constant('CODE_BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2761 case constant('CODE_LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2762 default : $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code); break;
2765 // Return the message
2769 // Checks wether the given extension is currently not installed
2770 // and redirects if so.
2771 function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
2772 // Is the extension uninstalled/inactive?
2773 if (!EXT_IS_ACTIVE($ext_name)) {
2774 // Redirect to index
2775 LOAD_URL("modules.php?module=index&msg=".constant('CODE_EXTENSION_PROBLEM')."&ext=".$ext_name);
2779 // Generate a "link" for the given admin id (aid)
2780 function GENERATE_AID_LINK ($aid) {
2781 // No assigned admin is default
2782 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2784 // Zero? = Not assigned
2786 // Load admin's login
2787 $login = GET_ADMIN_LOGIN($aid);
2788 if ($login != "***") {
2789 // Is the extension there?
2790 if (EXT_IS_ACTIVE("admins")) {
2792 $admin = "<a href=\"".ADMINS_CREATE_EMAIL_LINK(GET_ADMIN_EMAIL($aid))."\">".$login."</a>";
2794 // Extension not found
2795 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
2799 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2807 // Checks wether an include file (non-FQFN better) is readable
2808 function INCLUDE_READABLE ($INC) {
2810 $FQFN = constant('PATH') . $INC;
2813 return FILE_READABLE($FQFN);
2817 // @TODO Implement $compress
2818 function encodeString ($str, $compress=true) {
2819 $str = urlencode(base64_encode(compileUriCode($str)));
2823 // Decode strings encoded with encodeString()
2824 // @TODO Implement $decompress
2825 function decodeString ($str, $decompress=true) {
2826 $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
2830 // Compile characters which are allowed in URLs
2831 function compileUriCode ($code, $simple=true) {
2832 // Compile constants
2833 if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2835 // Compile QUOT and other non-HTML codes
2836 $code = str_replace("{DOT}", ".",
2837 str_replace("{SLASH}", "/",
2838 str_replace("{QUOT}", "'",
2839 str_replace("{DOLLAR}", "$",
2840 str_replace("{OPEN_ANCHOR}", "(",
2841 str_replace("{CLOSE_ANCHOR}", ")",
2842 str_replace("{OPEN_SQR}", "[",
2843 str_replace("{CLOSE_SQR}", "]",
2844 str_replace("{PER}", "%",
2848 // Return compiled code
2852 // Function taken from user comments on www.php.net / function eregi()
2853 function isUrlValid ($url) {
2855 $url = strip_tags(str_replace("\\", "", compileUriCode(urldecode($url))));
2857 // Allows http and https
2858 $http = "(http|https)+(:\/\/)";
2860 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2861 // Test double-domains (e.g. .de.vu)
2862 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2864 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2866 $dir = "((/)+([-_\.[:alnum:]])+)*";
2868 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2869 // ... and the string after and including question character
2870 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2871 // Pattern for URLs like http://url/dir/doc.html?var=value
2872 $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
2873 $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
2874 $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
2875 // Pattern for URLs like http://url/dir/?var=value
2876 $pattern['d1dg1'] = $http.$domain1.$dir."/".$getstring1;
2877 $pattern['d2dg1'] = $http.$domain2.$dir."/".$getstring1;
2878 $pattern['ipdg1'] = $http.$ip.$dir."/".$getstring1;
2879 // Pattern for URLs like http://url/dir/page.ext
2880 $pattern['d1dp'] = $http.$domain1.$dir.$page;
2881 $pattern['d1dp'] = $http.$domain2.$dir.$page;
2882 $pattern['ipdp'] = $http.$ip.$dir.$page;
2883 // Pattern for URLs like http://url/dir
2884 $pattern['d1d'] = $http.$domain1.$dir;
2885 $pattern['d2d'] = $http.$domain2.$dir;
2886 $pattern['ipd'] = $http.$ip.$dir;
2887 // Pattern for URLs like http://url/?var=value
2888 $pattern['d1g1'] = $http.$domain1."/".$getstring1;
2889 $pattern['d2g1'] = $http.$domain2."/".$getstring1;
2890 $pattern['ipg1'] = $http.$ip."/".$getstring1;
2891 // Pattern for URLs like http://url?var=value
2892 $pattern['d1g12'] = $http.$domain1.$getstring1;
2893 $pattern['d2g12'] = $http.$domain2.$getstring1;
2894 $pattern['ipg12'] = $http.$ip.$getstring1;
2895 // Test all patterns
2897 foreach ($pattern as $key=>$pat) {
2899 if (defined('DEBUG_REGEX')) {
2900 $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2901 $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2902 $pat = str_replace("[:digit:]", "0-9", $pat);
2903 $pat = str_replace(".", "\.", $pat);
2904 $pat = str_replace("@", "\@", $pat);
2905 echo $key."= ".$pat."<br />";
2908 // Check if expression matches
2909 $reg = ($reg || preg_match(("^".$pat."^"), $url));
2912 if ($reg === true) break;
2915 // Return true/false
2919 // Smartly adds slashes
2920 function smartAddSlashes ($unquoted) {
2921 $unquoted = str_replace("\\", "", $unquoted);
2922 return addslashes($unquoted);
2925 // Decode entities in a nicer way
2926 function decodeEntities ($str) {
2927 // @TODO We may want to switch over to UTF-8 here!
2928 $decodedString = html_entity_decode($str, ENT_NOQUOTES, "ISO-8859-15");
2930 // Return decoded string
2931 return $decodedString;
2934 // Wtites data to a config.php-style file
2935 // @TODO Rewrite this function to use READ_FILE() and WRITE_FILE()
2936 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2937 // Initialize some variables
2943 // Is the file there and read-/write-able?
2944 if ((FILE_READABLE($FQFN)) && (is_writeable($FQFN))) {
2945 $search = "CFG: ".$comment;
2946 $tmp = $FQFN.".tmp";
2948 // Open the source file
2949 $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
2951 // Is the resource valid?
2952 if (is_resource($fp)) {
2953 // Open temporary file
2954 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
2956 // Is the resource again valid?
2957 if (is_resource($fp_tmp)) {
2958 while (!feof($fp)) {
2959 // Read from source file
2960 $line = fgets ($fp, 1024);
2962 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2965 if ($next === $seek) {
2967 $line = $prefix . $DATA . $suffix."\n";
2973 // Write to temp file
2974 fputs($fp_tmp, $line);
2980 // Finished writing tmp file
2984 // Close source file
2987 if (($done) && ($found)) {
2988 // Copy back tmp file and delete tmp :-)
2990 return unlink($tmp);
2991 } elseif (!$found) {
2992 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
2994 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
2998 // File not found, not readable or writeable
2999 OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
3002 // An error was detected!
3005 // Send notification to admin
3006 function SEND_ADMIN_NOTIFICATION ($subject, $templateName, $content=array(), $uid="0") {
3007 if (GET_EXT_VERSION("admins") >= "0.4.1") {
3009 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
3011 // Send out out-dated way
3012 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
3013 SEND_ADMIN_EMAILS($subject, $msg);
3017 // Merges an array together but only if both are arrays
3018 function merge_array ($array1, $array2) {
3019 // Are both an array?
3020 if ((is_array($array1)) && (is_array($array2))) {
3021 // Merge all together
3022 return array_merge($array1, $array2);
3023 } elseif (is_array($array1)) {
3024 // Return left array
3025 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
3027 } elseif (is_array($array2)) {
3028 // Return right array
3029 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
3033 // Both are not arrays
3034 debug_report_bug(__FUNCTION__.": No arrays provided!");
3037 // Debug message logger
3038 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
3039 // Is debug mode enabled?
3040 if ((isDebugModeEnabled()) || ($force === true)) {
3041 // Log this message away
3042 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
3043 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
3048 // Reads a directory with PHP files in and gets only files back
3049 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
3053 $dirPointer = opendir(constant('PATH') . $baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
3056 while ($baseFile = readdir($dirPointer)) {
3057 // Load file only if extension is active
3058 $INC = $baseDir.$baseFile;
3059 $FQFN = constant('PATH') . $INC;
3061 // Is this a valid reset file?
3062 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
3063 if ((FILE_READABLE($FQFN)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
3064 // Remove both for extension name
3065 $extName = substr($baseFile, strlen($prefix), -4);
3068 $extId = GET_EXT_ID($extName);
3070 // Is the extension valid and active?
3071 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
3072 // Then add this file
3074 } elseif ($extId == 0) {
3075 // Add non-extension files as well
3082 closedir($dirPointer);
3087 // Return array with include files
3091 // Load more reset scripts
3092 function runResetIncludes () {
3093 // Is the reset set or old sql_patches?
3094 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
3096 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
3099 // Get more daily reset scripts
3100 $INC_POOL = GET_DIR_AS_ARRAY("inc/reset/", "reset_");
3103 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
3105 // Is the config entry set?
3106 if (GET_EXT_VERSION("sql_patches") >= "0.4.2") {
3107 // Create current week mark
3108 $currWeek = date("W", time());
3111 if (getConfig('last_week') != $currWeek) {
3112 // Include weekly reset scripts
3113 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY("inc/weekly/", "weekly_"));
3116 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
3119 // Create current month mark
3120 $currMonth = date("m", time());
3123 if (getConfig('last_month') != $currMonth) {
3124 // Include monthly reset scripts
3125 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY("inc/monthly/", "monthly_"));
3128 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
3133 runFilterChain('load_includes', $INC_POOL);
3136 // Handle extra values
3137 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
3138 // Default is the value itself
3141 // Do we have a special filter function?
3142 if (!empty($filterFunction)) {
3143 // Does the filter function exist?
3144 if (function_exists($filterFunction)) {
3145 // Do we have extra parameters here?
3146 if (!empty($extraValue)) {
3147 // Put both parameters in one new array by default
3148 $args = array($value, $extraValue);
3150 // If we have an array simply use it and pre-extend it with our value
3151 if (is_array($extraValue)) {
3152 // Make the new args array
3153 $args = merge_array(array($value), $extraValue);
3156 // Call the multi-parameter call-back
3157 $ret = call_user_func_array($filterFunction, $args);
3159 // One parameter call
3160 $ret = call_user_func($filterFunction, $value);
3169 // Check if given FQFN is a readable file
3170 function FILE_READABLE ($FQFN) {
3172 return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
3175 // Converts timestamp selections into a timestamp
3176 function CONVERT_SELECTIONS_TO_TIMESTAMP (&$POST, &$DATA, &$id, &$skip) {
3177 // Init test variable
3180 // Get last three chars
3181 $test = substr($id, -3);
3183 // Improved way of checking! :-)
3184 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
3185 // Found a multi-selection for timings?
3186 $test = substr($id, 0, -3);
3187 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)) {
3188 // Generate timestamp
3189 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
3190 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3192 // Remove data from array
3193 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
3194 unset($POST[$test."_".$rem]);
3198 unset($id); $skip = true; $test2 = $test;
3201 // Process this entry
3207 // Reverts the german decimal comma into Computer decimal dot
3208 function REVERT_COMMA ($str) {
3209 // Default float is not a float... ;-)
3212 // Which language is selected?
3213 switch (GET_LANGUAGE()) {
3214 case "de": // German language
3215 // Remove german thousand dots first
3216 $str = str_replace(".", "", $str);
3218 // Replace german commata with decimal dot and cast it
3219 $float = (float)str_replace(",", ".", $str);
3222 default: // US and so on
3223 // Remove thousand dots first and cast
3224 $float = (float)str_replace(",", "", $str);
3232 // Handle menu-depending failed logins and return the rendered content
3233 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3234 // Default output is empty ;-)
3237 // Is the session data set?
3238 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3239 // Ignore zero values
3240 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
3241 // Non-guest has login failures found, get both data and prepare it for template
3242 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3244 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
3245 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
3249 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
3252 // Reset session data
3253 set_session('mxchange_'.$accessLevel.'_failures', "");
3254 set_session('mxchange_'.$accessLevel.'_last_fail', "");
3257 // Return rendered content
3262 function rebuildCacheFiles ($cache, $inc="") {
3263 // Shall I remove the cache file?
3264 if ((EXT_IS_ACTIVE("cache")) && (isCacheInstanceValid())) {
3266 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3268 $GLOBALS['cache_instance']->destroyCacheFile();
3271 // Include file given?
3274 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3276 // Is the include there?
3277 if (INCLUDE_READABLE($INC)) {
3278 // And rebuild it from scratch
3279 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3282 // Include not found!
3283 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3289 // Purge admin menu cache
3290 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
3291 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3292 if (!EXT_IS_ACTIVE("cache")) {
3293 // Cache extension not active
3295 } elseif (!isCacheInstanceValid()) {
3296 // No cache instance!
3297 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3299 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
3300 // Caching disabled (currently experiemental!)
3304 // Experiemental feature!
3305 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3308 // Translates the "pool type" into human-readable
3309 function TRANSLATE_POOL_TYPE ($type) {
3310 // Default type is unknown
3311 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
3313 // Generate constant
3314 $constName = sprintf("POOL_TYPE_%s", $type);
3317 if (defined($constName)) {
3319 $translated = getMessage($constName);
3322 // Return "translation"
3326 // "Getter" for remote IP number
3327 function GET_REMOTE_ADDR () {
3328 // Get remote ip from environment
3329 $remoteAddr = getenv('REMOTE_ADDR');
3331 // Is removeip installed?
3332 if (EXT_IS_ACTIVE("removeip")) {
3333 // Then anonymize it
3334 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
3341 // "Getter" for remote hostname
3342 function GET_REMOTE_HOST () {
3343 // Get remote ip from environment
3344 $remoteHost = getenv('REMOTE_HOST');
3346 // Is removeip installed?
3347 if (EXT_IS_ACTIVE("removeip")) {
3348 // Then anonymize it
3349 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
3356 // "Getter" for user agent
3357 function GET_USER_AGENT () {
3358 // Get remote ip from environment
3359 $userAgent = getenv('HTTP_USER_AGENT');
3361 // Is removeip installed?
3362 if (EXT_IS_ACTIVE("removeip")) {
3363 // Then anonymize it
3364 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
3371 // "Getter" for referer
3372 function GET_REFERER () {
3373 // Get remote ip from environment
3374 $referer = getenv('HTTP_REFERER');
3376 // Is removeip installed?
3377 if (EXT_IS_ACTIVE("removeip")) {
3378 // Then anonymize it
3379 $referer = GET_ANONYMOUS_REFERER($referer);
3386 // Adds a bonus mail to the queue
3387 // This is a high-level function!
3388 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
3389 // Use mode from data if not set and availble ;-)
3390 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3392 // Generate receiver list
3393 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
3396 if (!empty($RECEIVER)) {
3397 // Add bonus mail to queue
3398 ADD_BONUS_MAIL_TO_QUEUE(
3410 // Mail inserted into bonus pool
3411 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
3412 } elseif ($output) {
3413 // More entered than can be reached!
3414 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
3417 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3421 // Determines referal id and sets it
3422 function DETERMINE_REFID () {
3423 global $CLICK, $_SERVER;
3425 // Check if refid is set
3426 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3427 // The variable user comes from the click-counter script click.php and we only accept this here
3428 $GLOBALS['refid'] = bigintval($_GET['user']);
3429 } elseif (!empty($_POST['refid'])) {
3430 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3431 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3432 } elseif (!empty($_GET['refid'])) {
3433 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3434 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3435 } elseif (!empty($_GET['ref'])) {
3436 // Set refid=ref (the referal link uses such variable)
3437 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3438 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
3439 // Set session refid als global
3440 $GLOBALS['refid'] = bigintval(get_session('refid'));
3441 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
3442 // Set default refid as refid in URL
3443 $GLOBALS['refid'] = getConfig(('def_refid'));
3444 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
3445 // Select a random user which has confirmed enougth mails
3446 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
3448 // No default ID when sql_patches is not installed or none set
3449 $GLOBALS['refid'] = 0;
3452 // Set cookie when default refid > 0
3453 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
3455 set_session('refid', $GLOBALS['refid']);
3458 // Return determined refid
3459 return $GLOBALS['refid'];
3462 // Check wether we are installing
3463 function isInstalling () {
3464 return (isset($GLOBALS['mxchange_installing']));
3467 // Check wether this script is installed
3468 function isInstalled () {
3469 return isBooleanConstantAndTrue('mxchange_installed');
3472 // Check wether an admin is registered
3473 function isAdminRegistered () {
3474 return isBooleanConstantAndTrue('admin_registered');
3477 // Enables the reset mode. Only call this function if you really want the
3479 function enableResetMode () {
3480 // Enable the reset mode
3481 $GLOBALS['reset_enabled'] = true;
3484 runFilterChain('reset_enabled');
3487 // Checks wether the reset mode is active
3488 function isResetModeEnabled () {
3489 // Now simply check it
3490 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
3493 // Checks wether the debug mode is enabled
3494 function isDebugModeEnabled () {
3496 return isBooleanConstantAndTrue('DEBUG_MODE');
3499 // Checks wether the cache instance is valid
3500 function isCacheInstanceValid () {
3501 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
3504 //////////////////////////////////////////////////
3505 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3506 //////////////////////////////////////////////////
3508 if (!function_exists('html_entity_decode')) {
3509 // Taken from documentation on www.php.net
3510 function html_entity_decode ($string) {
3511 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3512 $trans_tbl = array_flip($trans_tbl);
3513 return strtr($string, $trans_tbl);