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 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
40 // Check if our config file is writeable or not
41 function is_INCWritable($inc) {
42 $fp = @fopen(PATH."inc/".$inc.".php", 'a');
43 if ($inc == "dummy") {
46 return @unlink(PATH."inc/dummy.php");
48 // Close all other files
53 // Open a table (you may want to add some header stuff here)
54 function OPEN_TABLE($PERCENT = "", $CLASS = "", $ALIGN="left", $VALIGN="", $td_only=false) {
57 // Count tables so we can generate CSS classes for every table... :-)
59 // Class is empty so count one up and create a class
60 $table_cnt++; $CLASS = "class".$table_cnt;
62 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
64 // Shall I add the classes to TABLE and TD or only to TD?
65 if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
68 if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
71 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
73 // Vertical align is given
74 if (!empty($VALIGN)) $OUT .= " valign=\"".$VALIGN."\"";
75 $OUT .= ">\n<TR>\n<TD";
76 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
77 $OUT .= " class=\"".$CLASS."\">";
81 // Close a table (you may want to add some footer stuff here)
82 function CLOSE_TABLE($ADD="") {
83 OUTPUT_HTML(" </TD>\n</TR>");
84 if (!empty($ADD)) OUTPUT_HTML($ADD);
85 OUTPUT_HTML("</TABLE>");
88 // Output HTML code directly or "render" it. You addionally switch the new-line character off
89 function OUTPUT_HTML($HTML, $NEW_LINE = true) {
90 // Some global variables
91 global $OUTPUT, $footer, $CSS;
93 // Do we have HTML-Code here?
95 // Yes, so we handle it as you have configured
99 // That's why you don't need any \n at the end of your HTML code... :-)
100 if (_OB_CACHING == "on") {
101 // Output into PHP's internal buffer
104 // That's why you don't need any \n at the end of your HTML code... :-)
105 if ($NEW_LINE) echo "\n";
107 // Render mode for old or lame servers...
110 // That's why you don't need any \n at the end of your HTML code... :-)
111 if ($NEW_LINE) $OUTPUT .= "\n";
116 // If we are switching from render to direct output rendered code
117 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
119 // The same as above... ^
121 if ($NEW_LINE) echo "\n";
125 // Huh, something goes wrong or maybe you have edited config.php ???
126 die ("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
129 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
130 // Output cached HTML code
131 $OUTPUT = ob_get_contents();
133 // Clear output buffer for later output
136 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
137 $OUTPUT = REWRITE_LINKS($OUTPUT);
140 // Compile and run finished rendered HTML code
141 while (strpos($OUTPUT, '{!') > 0) {
142 // Prepare the content and eval() it...
144 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
147 if (empty($newContent)) {
148 // Something went wrong!
149 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
151 $OUTPUT = $newContent;
154 // Output code here, DO NOT REMOVE! ;-)
156 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
157 // Rewrite links when rewrite extension is active
158 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
159 $OUTPUT = REWRITE_LINKS($OUTPUT);
162 // Compile and run finished rendered HTML code
163 while (strpos($OUTPUT, '{!') > 0) {
164 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
168 // Output code here, DO NOT REMOVE! ;-)
173 // Output the raw HTML code
174 function OUTPUT_RAW ($HTML) {
175 // Output stripped HTML code to avoid broken JavaScript code, etc.
176 echo stripslashes($HTML);
178 // Flush the output if only _OB_CACHING is not "on"
179 if (_OB_CACHING != "on") {
185 // Add a fatal error message to the queue array
186 function ADD_FATAL ($message, $extra="") {
189 // Regular text message to add to $FATAL
192 // $message is text with a mask plus extras to insert into the text
193 $FATAL[] = sprintf($message, $extra);
197 // Load a template file and return it's content (only it's name; do not use ' or ")
198 function LOAD_TEMPLATE($template, $return=false, $content="") {
199 // Add more variables which you want to use in your template files
200 global $DATA, $_CONFIG, $username;
202 // Make all template names lowercase
203 $template = strtolower($template);
205 // Count the template load
206 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
207 $_CONFIG['num_templates']++;
211 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
213 // @DEPRECATED Try to remove this if() block
214 if ($template == "member_support_form") {
215 // Support request of a member
216 $result = SQL_QUERY_ESC("SELECT gender, surname, family, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
217 array($GLOBALS['userid']), __FILE__, __LINE__);
219 // @TODO Merge this data into $content
220 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
223 $gender = TRANSLATE_GENDER($gender);
225 // Insert data if content is an array
226 if (is_array($content)) {
227 // Please switch to $content[bla] in all your templates! Direct
228 // variables are deprecated as of 09/13/2008.
229 $content['gender'] = $gender;
230 $content['surname'] = $surname;
231 $content['family'] = $family;
232 $content['email'] = $email;
236 SQL_FREERESULT($result);
239 // Generate date/time string
240 $date_time = MAKE_DATETIME(time(), "1");
243 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
246 // Check for admin/guest/member templates
247 if (strpos($template, "admin_") > -1) {
248 // Admin template found
250 } elseif (strpos($template, "guest_") > -1) {
251 // Guest template found
253 } elseif (strpos($template, "member_") > -1) {
254 // Member template found
256 } elseif (strpos($template, "install_") > -1) {
257 // Installation template found
259 } elseif (strpos($template, "ext_") > -1) {
260 // Extension template found
262 } elseif (strpos($template, "la_") > -1) {
263 // "Logical-area" template found
266 // Test for extension
267 $test = substr($template, 0, strpos($template, "_"));
268 if (EXT_IS_ACTIVE($test)) {
269 // Set extra path to extension's name
274 ////////////////////////
275 // Generate file name //
276 ////////////////////////
277 $file = $BASE.$MODE.$template.".tpl";
279 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
280 // Select what depended header/footer template file for admin/guest/member area
281 $file2 = sprintf("%s%s%s_%s.tpl",
285 SQL_ESCAPE($GLOBALS['what'])
289 if (FILE_READABLE($file2)) $file = $file2;
291 // Remove variable from memory
295 // Does the special template exists?
296 if (!FILE_READABLE($file)) {
297 // Reset to default template
298 $file = $BASE.$template.".tpl";
301 // Now does the final template exists?
302 if (FILE_READABLE($file)) {
303 // The local file does exists so we load it. :)
304 $tmpl_file = implode("", file($file));
306 // Replace ' to our own chars to preventing them being quoted
307 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
309 // Do we have to compile the code?
311 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
313 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
316 // Simply return loaded code
320 // Add surrounding HTML comments to help finding bugs faster
321 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
322 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
323 // Only admins shall see this warning or when installation mode is active
324 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
325 (".basename($file).")<br />
328 <PRE>".print_r($content, true)."</PRE>
330 <PRE>".print_r($DATA, true)."</PRE>
334 // Do we have some content to output or return?
336 // Not empty so let's put it out! ;)
338 // Return the HTML code
344 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
345 // Warning, empty output!
346 return "E:".$template."<br />\n";
350 // Send mail out to an email address
351 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = 'N', $FROM = "") {
352 // Compile subject line (for POINTS constant etc.)
353 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
357 if ((!eregi("@", $TO)) && ($TO > 0)) {
358 // Value detected, load email from database
359 if (EXT_IS_ACTIVE("msg")) {
360 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
363 // Load email address
364 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
366 // Does the user exist?
367 if (SQL_NUMROWS($result_email)) {
368 // Load email address
369 list($TO) = SQL_FETCHROW($result_email);
376 SQL_FREERESULT($result_email);
378 } elseif ("$TO" == "0") {
383 // Check for PHPMailer or debug-mode
384 if (!CHECK_PHPMAILER_USAGE()) {
385 // Not in PHPMailer-Mode
387 // Load email header template
388 $FROM = LOAD_EMAIL_TEMPLATE("header");
391 $FROM .= LOAD_EMAIL_TEMPLATE("header");
393 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
395 // Load email header template
396 $FROM = LOAD_EMAIL_TEMPLATE("header");
399 $FROM .= LOAD_EMAIL_TEMPLATE("header");
404 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
407 // Fix HTML parameter (default is no!)
408 if (empty($HTML)) $HTML = "N";
409 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
410 // In debug mode we want to display the mail instead of sending it away so we can debug this part
412 ".htmlentities(trim($FROM))."
414 Subject : ".$SUBJECT."
417 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail", true))) {
418 // Send mail as HTML away
419 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
420 } elseif (!empty($TO)) {
422 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
423 } elseif ($HTML == "N") {
425 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
429 // Check if legacy or PHPMailer command
431 function CHECK_PHPMAILER_USAGE() {
432 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
436 * Send out a raw email with PHPMailer class or legacy mail() command
438 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
439 // Shall we use PHPMailer class or legacy mode?
440 if (CHECK_PHPMAILER_USAGE()) {
441 // Use PHPMailer class with SMTP enabled
442 require_once(PATH."inc/phpmailer/class.phpmailer.php");
443 require_once(PATH."inc/phpmailer/class.smtp.php");
446 $mail = new PHPMailer();
447 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
450 $mail->SMTPAuth = true;
451 $mail->Host = SMTP_HOSTNAME;
453 $mail->Username = SMTP_USER;
454 $mail->Password = SMTP_PASSWORD;
456 $mail->From = WEBMASTER;
460 $mail->FromName = MAIN_TITLE;
461 $mail->Subject = $subject;
462 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
464 $mail->AltBody = "Your mail program required HTML support to read this mail!";
465 $mail->WordWrap = 70;
470 $mail->AddAddress($to, "");
471 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
472 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
473 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
476 // Use legacy mail() command
477 @mail($to, $subject, $msg, $from);
482 // Generate a password in a specified length or use default password length
483 function GEN_PASS($LEN = 0) {
485 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
487 // Initialize array with all allowed chars
488 $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,-,+,_,/");
490 // Initialize randomizer
491 mt_srand((double) microtime() * 1000000);
493 // Start creating password
495 for ($i = 0; $i < $LEN; $i++) {
496 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
499 // When the size is below 40 we can also add additional security by scrambling it
500 if (strlen($PASS) <= 40) {
501 // Also scramble the password
502 $PASS = scrambleString($PASS);
505 // Return the password
509 function MAKE_DATETIME ($time, $mode="0")
513 return NEVER_HAPPENED;
515 // Filter out numbers
516 $time = bigintval($time);
519 switch (GET_LANGUAGE())
521 case "de": // German date / time format
523 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
524 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
525 case "2": $ret = date("d.m.Y|H:i", $time); break;
526 case "3": $ret = date("d.m.Y", $time); break;
530 default: // Default is the US date / time format!
532 case "0": $ret = date("r", $time); break;
533 case "1": $ret = date("Y-m-d - g:i A", $time); break;
534 case "2": $ret = date("y-m-d|H:i", $time); break;
535 case "3": $ret = date("y-m-d", $time); break;
541 // Translates the american decimal dot into a german comma
542 function TRANSLATE_COMMA ($dotted, $cut=true) {
545 // Default is 3 you can change this in admin area "Misc -> Misc Options"
546 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
547 $maxComma = $_CONFIG['max_comma'];
551 // Test for commata if in cut-mode
552 $com = explode(".", $dotted);
553 if (count($com) > 1) {
554 // Commata found, so only zeros?
555 if ($com[1] == str_repeat("0", strlen($com[1]))) {
556 // Only zeros, so don't display them
560 // Don't display commatas even if there are none... ;-)
566 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
569 switch (GET_LANGUAGE()) {
571 $dotted = number_format($dotted, $maxComma, ",", ".");
575 $dotted = number_format($dotted, $maxComma, ".", ",");
579 // Return translated value
584 function DEREFERER ($URL) {
585 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
590 function TRANSLATE_GENDER ($gender) {
593 case "M": $ret = GENDER_M; break;
594 case "F": $ret = GENDER_F; break;
595 case "C": $ret = GENDER_C; break;
596 default : $ret = $gender; break;
601 function GET_POOL_TYPE($PT) {
602 // Unknown pool type is default
603 $ret = POOL_UNKNOWN." (".$PT.")";
605 // Generate constant name
606 $constantName = sprintf("POOL_%s", $PT);
608 // Is the type known?
609 if (defined($constantName)) {
610 // Prepare eval command
611 $eval = sprintf("\$ret = %s;", $constantName);
619 function FRAMETESTER($URL) {
620 // Prepare frametester URL
621 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
623 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
625 return $frametesterUrl;
628 function SELECTION_COUNT($array) {
630 if (is_array($array)) {
631 foreach ($array as $key => $sel) {
632 if (!empty($sel)) $ret++;
638 function IMG_CODE ($code, $type, $DATA, $uid) {
639 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
642 function TRANSLATE_STATUS($status) {
646 $ret = ACCOUNT_UNCONFIRMED;
650 $ret = ACCOUNT_CONFIRMED;
654 $ret = ACCOUNT_LOCKED;
658 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
664 function GET_LANGUAGE() {
665 if (!empty($_GET['mx_lang'])) {
666 // Accept only first 2 chars
667 $lang = substr($_GET['mx_lang'], 0, 2);
673 // Set default return value to default language from config
676 // Check GET variable and cookie
678 // Check if main language file does exist
679 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
680 // Okay found, so let's update cookies
683 } elseif (!isSessionVariableSet('mx_lang')) {
684 // Return stored value from cookie
685 $ret = get_session('mx_lang');
687 // Fixes a warning before the session has the mx_lang constant
688 if (empty($ret)) $ret = DEFAULT_LANG;
693 function SET_LANGUAGE($lang) {
696 // Accept only first 2 chars!
697 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
700 set_session("mx_lang", $lang);
703 function LOAD_EMAIL_TEMPLATE($template, $content="", $UID="0") {
704 global $DATA, $_CONFIG, $REPLACER;
706 // Make sure all template names are lowercase!
707 $template = strtolower($template);
709 // Default "nickname" if extension is not installed
712 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
713 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
715 // Init variables (DEPRECATED! Use $content[bla] instead.
721 // Prepare IP number and User Agent
722 $REMOTE_ADDR = getenv('REMOTE_ADDR');
723 $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
726 if (isSessionVariableSet('admin_login')) {
728 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
729 array(get_session('admin_login')), __FILE__, __LINE__);
730 list($ADMIN) = SQL_FETCHROW($result);
731 SQL_FREERESULT($result);
734 // Expiration in a nice output format
735 if ($_CONFIG['auto_purge'] == 0) {
736 // Will never expire!
737 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
738 } elseif (function_exists('CREATE_FANCY_TIME')) {
739 // Create nice date string
740 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
743 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
746 // Is content an array?
747 if (is_array($content)) {
748 // Add expiration to array, $EXPIRATION is now deprecated!
749 $content['expiration'] = $EXPIRATION;
752 // @TODO Try to rewrite this part
753 if ($template == "add-points") {
754 if (isset($_POST['points'])) {
755 $points = bigintval($_POST['points']);
757 $points = __POINTS_VALUE;
763 if (EXT_IS_ACTIVE("nickname")) {
765 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
766 array(bigintval($UID)), __FILE__, __LINE__);
767 list($surname, $family, $gender, $email, $nick) = SQL_FETCHROW($result);
768 SQL_FREERESULT($result);
771 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
772 array(bigintval($UID)), __FILE__, __LINE__);
773 list($surname, $family, $gender, $email) = SQL_FETCHROW($result);
774 SQL_FREERESULT($result);
777 // Neutral gender and email address is default
782 // Translate M to male or F to female
783 $gender = TRANSLATE_GENDER($gender);
785 // Insert data if content is an array
786 if (is_array($content)) {
787 // Please do no longer use direct variable names, use $content[bla]
789 $content['gender'] = $gender;
790 $content['surname'] = $surname;
791 $content['family'] = $family;
792 $content['email'] = $email;
793 $content['nick'] = $nick;
796 // Store email for some functions in global data array
797 $DATA['email'] = $email;
800 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
802 // Check for admin/guest/member templates
803 if (strpos($template, "admin_") > -1) {
804 // Admin template found
805 $file = $BASE."admin/".$template.".tpl";
806 } elseif (strpos($template, "guest_") > -1) {
807 // Guest template found
808 $file = $BASE."guest/".$template.".tpl";
809 } elseif (strpos($template, "member_") > -1) {
810 // Member template found
811 $file = $BASE."member/".$template.".tpl";
813 // Test for extension
814 $test = substr($template, 0, strpos($template, "_"));
815 if (EXT_IS_ACTIVE($test)) {
816 // Set extra path to extension's name
817 $file = $BASE.$test."/".$template.".tpl";
819 // No special filename
820 $file = $BASE.$template.".tpl";
824 // Does the special template exists?
825 if (!FILE_READABLE($file)) {
826 // Reset to default template
827 $file = $BASE.$template.".tpl";
830 // Now does the final template exists?
832 if (FILE_READABLE($file)) {
833 // The local file does exists so we load it. :)
834 $tmpl_file = @implode("", @file($file));
835 $tmpl_file = addslashes($tmpl_file);
838 $tmpl_file = "\$newContent=\"".COMPILE_CODE($tmpl_file)."\";";
841 // Replace HTML conform chars
842 $newContent = html_entity_decode($newContent);
843 } elseif (!empty($template)) {
844 // Template file not found!
845 $newContent = TEMPLATE_404.": ".$template."<br />
847 <PRE>".print_r($newContent, true)."</PRE>
849 <PRE>".print_r($DATA, true)."</PRE>
852 // Debug mode not active? Then remove the HTML tags
853 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
855 // No template name supplied!
856 $newContent = NO_TEMPLATE_SUPPLIED;
859 // Is there some content?
860 if (empty($newContent)) {
862 $newContent = "Compiler error for template {$template}!";
865 // Return compiled content
866 return COMPILE_CODE($newContent);
869 function MAKE_TIME($H, $M, $S, $stamp) {
870 // Extract day, month and year from given timestamp
871 $DAY = date("d", $stamp);
872 $MONTH = date("m", $stamp);
873 $YEAR = date('Y', $stamp);
875 // Create timestamp for wished time which depends on extracted date
876 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
879 function LOAD_URL($URL, $addUrlData=true) {
880 global $CSS, $_CONFIG, $footer;
882 // Check if http(s):// is there
883 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
884 // Make all URLs full-qualified
888 // Compile out URI codes
889 $URL = COMPILE_CODE($URL);
892 $OUTPUT = ob_get_contents();
897 // Add some data to URL if cookies are not accepted
898 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
900 // Probe for bot from search engine
901 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
902 // Search engine bot detected so let's rewrite many chars for the link
903 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
905 // Output new location link as anchor
906 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
907 } elseif (!headers_sent()) {
908 // Load URL when headers are not sent
911 debug_print_backtrace();
912 die("</pre>URL={$URL}");
914 @header ("Location: ".str_replace("&", "&", $URL));
916 // Output error message
917 include(PATH."inc/header.php");
918 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
919 include(PATH."inc/footer.php");
924 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
925 global $SEC_CHARS, $URL_CHARS;
928 // Select smaller set of chars to replace when we e.g. want to compile URLs
929 if (!$full) $ARRAY = $URL_CHARS;
933 // BEFORE 0.2.1 : Language and data constants
934 // WITH 0.2.1+ : Only language constants
935 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
937 // BEFORE 0.2.1 : Not used
938 // WITH 0.2.1+ : Data constants
939 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
942 // Compile QUOT and other non-HTML codes
943 foreach ($ARRAY['to'] as $k => $to) {
944 // Do the reversed thing as in inc/libs/security_functions.php
945 $code = str_replace($to, $ARRAY['from'][$k], $code);
948 // But shall I keep simple quotes for later use?
949 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
951 // Find $content[bla][blub] entries
952 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
954 // Are some matches found?
955 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
956 // Replace all matches
957 $matchesFound = array();
958 foreach ($matches[0] as $key => $match) {
959 // Avoid replacing matches multiple times
960 if (!isset($matchesFound[$match])) {
962 $code = str_replace($match, "\".".$match.".\"", $code);
963 $matchesFound[$match] = 1;
966 // Take all string elements
967 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
968 // Replace it in the code
969 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
970 $code = str_replace($match, $newMatch, $code);
971 $matchesFound[$key."_".$matches[4][$key]] = 1;
976 // Return compiled code
980 /************************************************************************
982 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
983 * $a_sort sortiert: *
985 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
986 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
987 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
988 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
989 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
991 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
992 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
993 * Sie, dass es doch nicht so schwer ist! :-) *
995 ************************************************************************/
996 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
999 while ($primary_key < count($a_sort)) {
1000 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1001 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1004 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1005 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1006 } elseif ($key != $key2) {
1007 // Sort numbers (E.g.: 9 < 10)
1008 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1009 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1013 // We have found two different values, so let's sort whole array
1014 foreach ($dummy as $sort_key => $sort_val) {
1015 $t = $dummy[$sort_key][$key];
1016 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1017 $dummy[$sort_key][$key2] = $t;
1028 // Write back sorted array
1032 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1034 global $MONTH_DESCR; $OUT = "";
1037 // This is a yes/no selection only!
1038 if ($id > 0) $prefix .= "[".$id."]";
1039 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1043 // Begin with regular selection box here
1044 if (!empty($prefix)) $prefix .= "_";
1046 if ($id > 0) $type2 .= "[".$id."]";
1047 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1052 for ($idx = 1; $idx < 32; $idx++)
1054 $OUT .= "<OPTION value=\"".$idx."\"";
1055 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1056 $OUT .= ">".$idx."</OPTION>\n";
1060 case "month": // Month
1061 foreach ($MONTH_DESCR as $month => $descr)
1063 $OUT .= "<OPTION value=\"".$month."\"";
1064 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1065 $OUT .= ">".$descr."</OPTION>\n";
1069 case "year": // Year
1071 $YEAR = date('Y', time());
1073 // Check if the default value is larger than minimum and bigger than actual year
1074 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1076 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1078 $OUT .= "<OPTION value=\"".$idx."\"";
1079 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1080 $OUT .= ">".$idx."</OPTION>\n";
1083 elseif ($DEFAULT == -1)
1085 // Current year minus 1
1086 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1088 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1093 // Get current year and subtract 16 (for erotic content)
1094 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1095 $YEAR = date('Y', time()) - 16;
1096 for ($idx = 1930; $idx <= $YEAR; $idx++)
1098 $OUT .= "<OPTION value=\"".$idx."\"";
1099 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1100 $OUT .= ">".$idx."</OPTION>\n";
1107 for ($idx = 0; $idx < 60; $idx+=5) {
1108 if (strlen($idx) == 1) $idx = "0".$idx;
1109 $OUT .= "<OPTION value=\"".$idx."\"";
1110 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1111 $OUT .= ">".$idx."</OPTION>\n";
1116 for ($idx = 0; $idx < 24; $idx++) {
1117 if (strlen($idx) == 1) $idx = "0".$idx;
1118 $OUT .= "<OPTION value=\"".$idx."\"";
1119 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1120 $OUT .= ">".$idx."</OPTION>\n";
1125 $OUT .= "<OPTION value=\"Y\"";
1126 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1127 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1128 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1129 $OUT .= ">".NO."</OPTION>\n";
1132 $OUT .= " </SELECT>\n";
1136 function TRANSLATE_YESNO($yn)
1140 case 'Y': $yn = YES; break;
1141 case 'N': $yn = NO; break;
1142 default : $yn = "??? (".$yn.")"; break;
1147 // Deprecated : $length
1150 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1153 // Fix missing _MAX constant
1154 if (!defined('_MAX')) define('_MAX', 15235);
1156 // Build server string
1157 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1160 $keys = SITE_KEY.":".DATE_KEY;
1161 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1162 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1163 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1164 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1166 // Build string from misc data
1167 $data = $code.":".$uid.":".$DATA;
1169 // Add more additional data
1170 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1171 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1172 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1173 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1174 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1175 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1177 // Calculate number for generating the code
1178 $a = $code + _ADD - 1;
1180 if (isset($_CONFIG['master_hash'])) {
1181 // Generate hash with master salt from modula of number with the prime number and other data
1182 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1184 // Create number from hash
1185 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1187 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1188 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1190 // Create number from hash
1191 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1194 // At least 10 numbers shall be secure enought!
1195 $len = $_CONFIG['code_length'];
1196 if ($len == 0) $len = $length;
1197 if ($len == 0) $len = 10;
1199 // Cut off requested counts of number
1200 $return = substr(str_replace('.', "", $rcode), 0, $len);
1202 // Done building code
1205 // Does only allow numbers
1206 function bigintval($num, $castValue = true) {
1207 // Filter all numbers out
1208 $ret = preg_replace("/[^0123456789]/", "", $num);
1211 if ($castValue) $ret = (double)$ret;
1213 // Has the whole value changed?
1214 if ("".$ret."" != "".$num."") {
1216 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1222 // Insert the code in $img_code into jpeg or PNG image
1223 function GENERATE_IMAGE($img_code, $header=true) {
1226 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1227 // Stop execution of function here because of over-sized code length
1229 } elseif (!$header) {
1230 // Return in an HTML code code
1231 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1235 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1236 if (FILE_READABLE($img)) {
1237 // Switch image type
1238 switch ($_CONFIG['img_type'])
1241 // Okay, load image and hide all errors
1242 $image = @imagecreatefromjpeg($img);
1246 // Okay, load image and hide all errors
1247 $image = @imagecreatefrompng($img);
1251 // Exit function here
1255 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1256 $text_color = imagecolorallocate($image, 0, 0, 0);
1258 // Insert code into image
1259 imagestring($image, 5, 14, 2, $img_code, $text_color);
1261 // Return to browser
1262 header ("Content-Type: image/".$_CONFIG['img_type']);
1264 // Output image with matching image factory
1265 switch ($_CONFIG['img_type']) {
1266 case "jpg": imagejpeg($image); break;
1267 case "png": imagepng($image); break;
1270 // Remove image from memory
1271 imagedestroy($image);
1273 // Create selection box or array of splitted timestamp
1274 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1275 // Calculate 2-seconds timestamp
1276 $stamp = round($timestamp / 2) * 2;
1278 // Do we have a leap year?
1280 $TEST = date('Y', time()) / 4;
1281 $M1 = date("m", time());
1282 $M2 = date("m", (time() + $stamp));
1284 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1285 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1287 // First of all years...
1288 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1290 $M = abs(floor($stamp / 2628000 - $Y * 12));
1292 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1294 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1296 $h = abs(floor($stamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1298 $m = abs(floor($stamp / 60 - $Y * (365 + $SWITCH / ONE_DAY) * 24 * 60 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1299 // And at last seconds...
1300 $s = abs(floor($stamp - $Y * (365 + $SWITCH / ONE_DAY) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1302 // Is seconds zero and time is < 60 seconds?
1303 if (($s == 0) && ($stamp < 60)) {
1305 $s = round($timestamp);
1309 // Now we convert them in seconds...
1311 if ($return_array) {
1312 // Just put all data in an array for later use
1324 $OUT = "<DIV align=\"".$align."\">\n";
1325 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1328 if (ereg('Y', $display) || (empty($display))) {
1329 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1332 if (ereg("M", $display) || (empty($display))) {
1333 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1336 if (ereg("W", $display) || (empty($display))) {
1337 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1340 if (ereg("D", $display) || (empty($display))) {
1341 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1344 if (ereg("h", $display) || (empty($display))) {
1345 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1348 if (ereg("m", $display) || (empty($display))) {
1349 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1352 if (ereg("s", $display) || (empty($display))) {
1353 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1359 if (ereg('Y', $display) || (empty($display))) {
1360 // Generate year selection
1361 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1362 for ($idx = 0; $idx <= 10; $idx++) {
1363 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1364 if ($idx == $Y) $OUT .= " selected default";
1365 $OUT .= ">".$idx."</OPTION>\n";
1367 $OUT .= " </SELECT></TD>\n";
1369 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1372 if (ereg("M", $display) || (empty($display))) {
1373 // Generate month selection
1374 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1375 for ($idx = 0; $idx <= 11; $idx++)
1377 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1378 if ($idx == $M) $OUT .= " selected default";
1379 $OUT .= ">".$idx."</OPTION>\n";
1381 $OUT .= " </SELECT></TD>\n";
1383 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1386 if (ereg("W", $display) || (empty($display))) {
1387 // Generate week selection
1388 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1389 for ($idx = 0; $idx <= 4; $idx++) {
1390 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1391 if ($idx == $W) $OUT .= " selected default";
1392 $OUT .= ">".$idx."</OPTION>\n";
1394 $OUT .= " </SELECT></TD>\n";
1396 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1399 if (ereg("D", $display) || (empty($display))) {
1400 // Generate day selection
1401 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1402 for ($idx = 0; $idx <= 31; $idx++) {
1403 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1404 if ($idx == $D) $OUT .= " selected default";
1405 $OUT .= ">".$idx."</OPTION>\n";
1407 $OUT .= " </SELECT></TD>\n";
1409 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1412 if (ereg("h", $display) || (empty($display))) {
1413 // Generate hour selection
1414 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1415 for ($idx = 0; $idx <= 23; $idx++) {
1416 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1417 if ($idx == $h) $OUT .= " selected default";
1418 $OUT .= ">".$idx."</OPTION>\n";
1420 $OUT .= " </SELECT></TD>\n";
1422 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1425 if (ereg("m", $display) || (empty($display))) {
1426 // Generate minute selection
1427 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1428 for ($idx = 0; $idx <= 59; $idx++) {
1429 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1430 if ($idx == $m) $OUT .= " selected default";
1431 $OUT .= ">".$idx."</OPTION>\n";
1433 $OUT .= " </SELECT></TD>\n";
1435 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1438 if (ereg("s", $display) || (empty($display))) {
1439 // Generate second selection
1440 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1441 for ($idx = 0; $idx <= 45; $idx += 15) {
1442 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1443 if ($idx == $s) $OUT .= " selected default";
1444 $OUT .= ">".$idx."</OPTION>\n";
1446 $OUT .= " </SELECT></TD>\n";
1448 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1451 $OUT .= "</TABLE>\n";
1453 // Return generated HTML code
1458 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1461 // Do we have a leap year?
1463 $TEST = date('Y', time()) / 4;
1464 $M1 = date("m", time());
1465 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1466 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1467 // First add years...
1468 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1470 $ret += $POST[$prefix."_mo"] * 2628000;
1472 $ret += $POST[$prefix."_we"] * 604800;
1474 $ret += $POST[$prefix."_da"] * 86400;
1476 $ret += $POST[$prefix."_ho"] * 3600;
1478 $ret += $POST[$prefix."_mi"] * 60;
1479 // And at last seconds...
1480 $ret += $POST[$prefix."_se"];
1481 // Return calculated value
1484 // Sends out mail to all administrators
1485 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1486 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1487 // Trim template name
1488 $template = trim($template);
1490 // Load email template
1491 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1493 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1494 // Older version detected!
1495 return SEND_ADMIN_EMAILS($subj, $msg);
1498 // Check which admin shall receive this mail
1499 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1500 array($template), __FILE__, __LINE__);
1501 if (SQL_NUMROWS($result) == 0) {
1502 // Create new entry (to all admins)
1503 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1504 array($template), __FILE__, __LINE__);
1506 // Load admin IDs...
1508 while(list($aid) = SQL_FETCHROW($result)) {
1513 SQL_FREERESULT($result);
1515 // "implode" IDs and query string
1516 $aid = implode(",", $aids);
1518 // Add line to userlog
1519 USERLOG_ADD_LINE($subj, $msg, $UID);
1521 } elseif ($aid == "0") {
1522 // Select all email adresses
1523 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1525 // If Admin-ID is not "to-all" select
1526 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1530 // Load email addresses and send away
1531 while (list($email) = SQL_FETCHROW($result)) {
1532 SEND_EMAIL($email, $subj, $msg);
1536 SQL_FREERESULT($result);
1539 function CREATE_FANCY_TIME($stamp) {
1540 // Get data array with years/months/weeks/days/...
1541 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1543 foreach($data as $k => $v) {
1545 // Value is greater than 0 "eval" data to return string
1546 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1552 // Do we have something there?
1553 if (strlen($ret) > 0) {
1554 // Remove leading commata and space
1555 $ret = substr($ret, 2);
1558 $ret = "0 "._SECONDS;
1561 // Return fancy time string
1565 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1566 $SEP = ""; $TOP = "";
1569 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1573 for ($page = 1; $page <= $PAGES; $page++) {
1574 // Is the page currently selected or shall we generate a link to it?
1575 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1576 // Is currently selected, so only highlight it
1577 $NAV .= "<STRONG>-";
1579 // Open anchor tag and add base URL
1580 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1582 // Add userid when we shall show all mails from a single member
1583 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1585 // Close open anchor tag
1589 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1590 // Is currently selected, so only highlight it
1591 $NAV .= "-</STRONG>";
1597 // Add seperator if we have not yet reached total pages
1598 if ($page < $PAGES) $NAV .= " | ";
1601 // Define constants only once
1602 if (!defined('__NAV_OUTPUT')) {
1603 define('__NAV_OUTPUT' , $NAV);
1604 define('__NAV_COLSPAN', $colspan);
1605 define('__NAV_TOP' , $TOP);
1606 define('__NAV_SEP' , $SEP);
1609 // Load navigation template
1610 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1613 // Return generated HTML-Code
1621 // Extract host from script name
1622 function EXTRACT_HOST (&$script) {
1623 // Use default SERVER_URL by default... ;) So?
1626 // Is this URL valid?
1627 if (substr($script, 0, 7) == "http://") {
1628 // Use the hostname from script URL as new hostname
1629 $url = substr($script, 7);
1630 $extract = explode("/", $url);
1632 // Done extracting the URL :)
1635 // Extract host name
1636 $host = str_replace("http://", "", $url);
1637 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1639 // Generate relative URL
1640 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1641 if (substr(strtolower($script), 0, 7) == "http://") {
1642 // But only if http:// is in front!
1643 $script = substr($script, (strlen($url) + 7));
1644 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1646 $script = substr($script, (strlen($url) + 8));
1649 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1650 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1656 // Send a GET request
1657 function GET_URL ($script) {
1658 // Compile the script name
1659 $script = COMPILE_CODE($script);
1661 // Extract host name from script
1662 $host = EXTRACT_HOST($script);
1664 // Generate GET request header
1665 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1666 $request .= "Host: " . $host . "\r\n";
1667 $request .= "Referer: " . URL . "/admin.php\r\n";
1668 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1669 $request .= "Content-Type: text/plain\r\n";
1670 $request .= "Cache-Control: no-cache\r\n";
1671 $request .= "Connection: Close\r\n\r\n";
1673 // Send the raw request
1674 $response = SEND_RAW_REQUEST($host, $request);
1676 // Return the result to the caller function
1680 // Send a POST request
1681 function POST_URL ($script, $postData) {
1682 // Is postData an array?
1683 if (!is_array($postData)) {
1685 return array("", "", "");
1688 // Compile the script name
1689 $script = COMPILE_CODE($script);
1691 // Extract host name from script
1692 $host = EXTRACT_HOST($script);
1694 // Construct request
1695 $data = http_build_query($postData, '', '&');
1697 // Generate POST request header
1698 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1699 $request .= "Host: " . $host . "\r\n";
1700 $request .= "Referer: " . URL . "/admin.php\r\n";
1701 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1702 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1703 $request .= "Content-length: " . strlen($data) . "\r\n";
1704 $request .= "Cache-Control: no-cache\r\n";
1705 $request .= "Connection: Close\r\n\r\n";
1708 // Send the raw request
1709 $response = SEND_RAW_REQUEST($host, $request);
1711 // Return the result to the caller function
1715 // Sends a raw request to another host
1716 function SEND_RAW_REQUEST ($host, $request) {
1720 $response = array("", "", "");
1722 // Default is not to use proxy
1725 // Are proxy settins set?
1726 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1732 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1734 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1736 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1740 if (!is_resource($fp)) {
1747 // Generate CONNECT request header
1748 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1749 $proxyTunnel .= "Host: ".$host."\r\n";
1751 // Use login data to proxy? (username at least!)
1752 if (!empty($_CONFIG['proxy_username'])) {
1754 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1755 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1758 // Add last new-line
1759 $proxyTunnel .= "\r\n";
1760 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1763 fputs($fp, $proxyTunnel);
1767 // No response received
1771 // Read the first line
1772 $resp = trim(fgets($fp, 10240));
1773 $respArray = explode(" ", $resp);
1774 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1775 // Invalid response!
1781 fputs($fp, $request);
1785 $response[] = trim(fgets($fp, 1024));
1791 // Skip first empty lines
1793 foreach ($resp as $idx => $line) {
1795 $line = trim($line);
1797 // Is this line empty?
1800 array_shift($response);
1802 // Abort on first non-empty line
1807 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1809 // Proxy agent found?
1810 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1811 // Proxy header detected, so remove two lines
1812 array_shift($response);
1813 array_shift($response);
1816 // Was the request successfull?
1817 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1818 // Not found / access forbidden
1819 $response = array("", "", "");
1825 // Taken from www.php.net eregi() user comments
1826 function VALIDATE_EMAIL($email) {
1828 $email = COMPILE_CODE($email);
1830 // Check first part of email address
1831 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1834 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1837 $regex = "^".$first."@".$domain."$";
1839 // Return check result
1840 return eregi($regex, $email);
1842 // Function taken from user comments on www.php.net / function eregi()
1843 function VALIDATE_URL ($URL, $compile=true) {
1844 // Trim URL a little
1845 $URL = trim(urldecode($URL));
1846 //* DEBUG: */ echo $URL."<br />";
1848 // Compile some chars out...
1849 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1850 //* DEBUG: */ echo $URL."<br />";
1852 // Check for the extension filter
1853 if (EXT_IS_ACTIVE("filter")) {
1854 // Use the extension's filter set
1855 return FILTER_VALIDATE_URL($URL, false);
1858 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1859 // https:// in front of the URLs
1860 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1863 function MEMBER_ACTION_LINKS($uid, $status="") {
1864 // Define all main targets
1865 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1867 // Begin of navigation links
1868 $eval = "\$OUT = \"[ ";
1870 foreach ($TARGETS as $tar) {
1871 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1872 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1873 if (($tar == "lock_user") && ($status == "LOCKED")) {
1874 // Locked accounts shall be unlocked
1875 $eval .= "UNLOCK_USER";
1877 // All other status is fine
1878 $eval .= strtoupper($tar);
1880 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1881 if (($tar == "lock_user") && ($status == "LOCKED")) {
1882 // Locked accounts shall be unlocked
1883 $eval .= "UNLOCK_USER";
1885 // All other status is fine
1886 $eval .= strtoupper($tar);
1888 $eval .= ".\"</A></SPAN> | ";
1891 // Finish navigation link
1892 $eval = substr($eval, 0, -7)."]\";";
1898 // Function for backward-compatiblity
1899 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1900 // Load it from the register extension
1901 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1903 // Generate an email link
1904 function CREATE_EMAIL_LINK($email, $table="admins") {
1905 // Default email link (INSECURE! Spammer can read this by harvester programs)
1906 $EMAIL = "mailto:".$email;
1908 // Check for several extensions
1909 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1910 // Create email link for contacting admin in guest area
1911 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1912 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1913 // Create email link for contacting a member within admin area (or later in other areas, too?)
1914 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1915 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1916 // Create email link to contact sponsor within admin area (or like the link above?)
1917 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1920 // Shall I close the link when there is no admin?
1921 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1923 // Return email link
1926 // Generate a hash for extra-security for all passwords
1927 function generateHash ($plainText, $salt = "") {
1928 global $_CONFIG, $_SERVER;
1930 // Is the required extension "sql_patches" there and a salt is not given?
1931 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == "")) && (empty($salt))) {
1932 // Extension sql_patches is missing/outdated so we return the plain text
1936 // Do we miss an arry element here?
1937 if (!isset($_CONFIG['file_hash'])) {
1939 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1940 debug_print_backtrace();
1944 // When the salt is empty build a new one, else use the first x configured characters as the salt
1946 // Build server string
1947 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1950 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime'])).":".$_CONFIG['master_salt'];
1953 $data = $plainText.":".uniqid(rand(), true).":".time();
1955 // Calculate number for generating the code
1956 $a = time() + _ADD - 1;
1958 // Generate SHA1 sum from modula of number and the prime number
1959 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1960 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
1961 $sha1 = scrambleString($sha1);
1962 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
1963 //* DEBUG: */ $sha1b = descrambleString($sha1);
1964 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
1966 // Generate the password salt string
1967 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1968 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1971 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1972 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
1976 return $salt.sha1($salt.$plainText);
1979 function scrambleString($str) {
1985 // Final check, in case of failture it will return unscrambled string
1986 if (strlen($str) > 40) {
1987 // The string is to long
1989 } elseif (strlen($str) == 40) {
1991 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1993 // Generate new numbers
1994 $scrambleNums = explode(":", genScrambleString(strlen($str)));
1997 // Scramble string here
1998 //* DEBUG: */ echo "***Original=".$str."***<br />";
1999 for ($idx = 0; $idx < strlen($str); $idx++) {
2000 // Get char on scrambled position
2001 $char = substr($str, $scrambleNums[$idx], 1);
2003 // Add it to final output string
2004 $scrambled .= $char;
2007 // Return scrambled string
2008 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2012 function descrambleString($str) {
2014 // Scramble only 40 chars long strings
2015 if (strlen($str) != 40) return $str;
2017 // Load numbers from config
2018 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2021 if (count($scrambleNums) != 40) return $str;
2023 // Begin descrambling
2024 $orig = str_repeat(" ", 40);
2025 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2026 for ($idx = 0; $idx < 40; $idx++) {
2027 $char = substr($str, $idx, 1);
2028 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2031 // Return scrambled string
2032 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2036 function genScrambleString($len) {
2037 // Prepare randomizer and array for the numbers
2038 mt_srand((double) microtime() * 1000000);
2039 $scrambleNumbers = array();
2041 // First we need to setup randomized numbers from 0 to 31
2042 for ($idx = 0; $idx < $len; $idx++) {
2044 $rand = mt_rand(0, ($len -1));
2046 // Check for it by creating more numbers
2047 while (array_key_exists($rand, $scrambleNumbers)) {
2048 $rand = mt_rand(0, ($len -1));
2052 $scrambleNumbers[$rand] = $rand;
2055 // So let's create the string for storing it in database
2056 $scrambleString = implode(":", $scrambleNumbers);
2057 return $scrambleString;
2059 // Append data like session ID referral ID to the given URL which would
2060 // normally be stored in cookies
2061 function ADD_URL_DATA($URL) {
2065 // Determine URL binder
2067 if (strpos($URL, "?") !== false) $BIND = "&";
2069 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2070 // Cookies are not accepted
2071 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2072 // Cookie found in URL
2073 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2074 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2075 // Not found! So let's set default here
2076 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2079 // Is there already added data? Then change the binder
2080 if (!empty($ADD)) $BIND = "&";
2083 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2084 // Add session from URL
2085 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2087 // Add current session
2088 $ADD .= $BIND."PHPSESSID=".session_id();
2092 // Add all together and return it
2095 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2096 function generatePassString($passHash) {
2099 // Return vanilla password hash
2102 // Is a secret key and master salt already initialized?
2103 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2104 // Only calculate when the secret key is generated
2105 $newHash = ""; $start = 9;
2106 for ($idx = 0; $idx < 10; $idx++) {
2107 $part1 = hexdec(substr($passHash, $start, 4));
2108 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2109 $mod = dechex($idx);
2110 if ($part1 > $part2) {
2111 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2112 } elseif ($part2 > $part1) {
2113 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2115 $mod = substr(round($mod), 0, 4);
2116 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2117 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2122 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2123 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2124 //* DEBUG: */ print($ret."<br />\n");
2127 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2128 $ret = md5($passHash);
2129 //* DEBUG: */ echo "++".$ret."++<br />\n";
2136 // Fix "deleted" cookies
2137 function FIX_DELETED_COOKIES ($cookies) {
2138 // Is this an array with entries?
2139 if ((is_array($cookies)) && (count($cookies) > 0)) {
2140 // Then check all cookies if they are marked as deleted!
2141 foreach ($cookies as $cookieName) {
2142 // Is the cookie set to "deleted"?
2143 if (get_session($cookieName) == "deleted") {
2144 set_session($cookieName, "");
2150 // Output error messages in a fasioned way and die...
2151 function mxchange_die ($msg) {
2154 // Load the message template
2155 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2158 include(PATH."inc/footer.php");
2164 // Display parsing time and number of SQL queries in footer
2165 function DISPLAY_PARSING_TIME_FOOTER() {
2166 global $startTime, $_CONFIG;
2167 $endTime = microtime(true);
2169 // Is the timer started?
2170 if (!isset($GLOBALS['startTime'])) {
2175 // "Explode" both times
2176 $start = explode(" ", $GLOBALS['startTime']);
2177 $end = explode(" ", $endTime);
2178 $runTime = $end[0] - $start[0];
2179 if ($runTime < 0) $runTime = 0;
2180 $runTime = TRANSLATE_COMMA($runTime);
2184 'runtime' => $runTime,
2185 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2186 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2189 // Load the template
2190 LOAD_TEMPLATE("show_timings", false, $content);
2193 // Unset/set session variables
2194 function set_session ($var, $value) {
2197 // Abort in CSS mode here
2198 if ($CSS == 1) return true;
2200 // Trim value and session variable
2201 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2203 // Is the session variable set?
2204 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2205 // Remove the session
2206 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2207 unset($_SESSION[$var]);
2208 return session_unregister($var);
2209 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2211 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2212 $_SESSION[$var] = $value;
2213 return session_register($var);
2214 } elseif (!empty($value)) {
2216 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2217 $_SESSION[$var] = $value;
2221 // Ignored (but valid)
2222 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2226 // Check wether a boolean constant is set
2227 // Taken from user comments in PHP documentation for function constant()
2228 function isBooleanConstantAndTrue($constName) { // : Boolean
2231 // Failed by default
2235 if (isset($constCache[$constName])) {
2237 $res = $constCache[$constName];
2240 if (defined($constName)) $res = (constant($constName) === true);
2243 $constCache[$constName] = $res;
2250 // Check wether a session variable is set
2251 function isSessionVariableSet($var) {
2252 //* DEBUG: */ echo __FUNCTION__.":var={$var}<br />\n";
2253 return (isset($_SESSION[$var]));
2255 // Returns wether the value of the session variable or NULL if not set
2256 function get_session($var) {
2259 // Default is not found! ;-)
2262 // Is the variable there or cached values?
2263 if (isset($cacheArray['session'][$var])) {
2264 // Get cached value (skips a lot SQL_ESCAPE() calles!
2265 $value = $cacheArray['session'][$var];
2266 } elseif (isSessionVariableSet($var)) {
2267 // Then get it secured!
2268 $value = SQL_ESCAPE($_SESSION[$var]);
2271 $cacheArray['session'][$var] = $value;
2277 // Send notification to admin
2278 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content="", $uid="0") {
2279 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2281 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2283 // Send outdated way
2284 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2285 SEND_ADMIN_EMAILS($subject, $msg);
2288 // Destroy user session
2289 function destroy_user_session () {
2290 // Remove all user data from session
2291 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2293 // Merges an array together but only if both are arrays
2294 function merge_array ($array1, $array2) {
2295 // Are both an array?
2296 if ((is_array($array1)) && (is_array($array2))) {
2297 // Merge all together
2298 return array_merge($array1, $array2);
2299 } elseif (is_array($array1)) {
2300 // Return left array
2304 // Something wired happened here...
2305 print(__FUNCTION__.":<pre>");
2306 debug_print_backtrace();
2309 // Debug message logger
2310 function DEBUG_LOG ($message) {
2311 // Is debug mode enabled?
2312 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
2313 // Log this message away
2314 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2315 fwrite($fp, date("d.m.Y|H:i:s", time())."|{$message}\n");
2319 // Reads a directory with PHP files in and gets only files back
2320 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2324 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2327 while ($baseFile = readdir($dirPointer)) {
2328 // Load file only if extension is active
2330 $file = $baseDir.$baseFile;
2332 // Is this a valid reset file?
2333 //* DEBUG: */ echo __FUNCTION__.":baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2334 if ((is_file($file)) && (is_readable($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2335 // Remove both for extension name
2336 $extName = substr($baseFile, strlen($prefix), -4);
2339 $extId = GET_EXT_ID($extName);
2341 // Is the extension valid and active?
2342 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2343 // Then add this file
2345 } elseif ($extId == 0) {
2346 // Add non-extension files as well
2353 closedir($dirPointer);
2355 // Return array with include files
2358 // Load more reset scripts
2359 function RESET_ADD_INCLUDES () {
2362 // Is the reset set or old sql_patches?
2363 if ((!isBooleanConstantAndTrue('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2368 // Get more daily reset scripts
2369 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2371 // Create current week mark
2372 $currWeek = date("W", time());
2375 if ($_CONFIG['last_week'] != $currWeek) {
2376 // Include weekly reset scripts
2377 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2380 UPDATE_CONFIG("last_week", $currWeek);
2383 // Create current month mark
2384 $currMonth = date("m", time());
2387 if ($_CONFIG['last_month'] != $currMonth) {
2388 // Include monthly reset scripts
2389 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2392 UPDATE_CONFIG("last_month", $currMonth);
2398 // Handle extra values
2399 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2400 // Default is the value itself
2403 // Do we have a special filter function?
2404 if (!empty($filterFunction)) {
2405 // Does the filter function exist?
2406 if (function_exists($filterFunction)) {
2407 // Do we have extra parameters here?
2408 if (!empty($extraValue)) {
2409 // Put both parameters in one new array by default
2410 $args = array($value, $extraValue);
2412 // If we have an array simply use it and pre-extend it with our value
2413 if (is_array($extraValue)) {
2414 // Make the new args array
2415 $args = array_merge(array($value), $extraValue);
2418 // Call the multi-parameter call-back
2419 $ret = call_user_func_array($filterFunction, $args);
2421 // One parameter call
2422 $ret = call_user_func($filterFunction, $value);
2430 // Check if given FQFN is a readable file
2431 function FILE_READABLE($fqfn) {
2433 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2435 // Converts timestamp selections into a timestamp
2436 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2437 // Init test variable
2440 // Get last three chars
2441 $TEST = substr($id, -3);
2443 // Improved way of checking! :-)
2444 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2445 // Found a multi-selection for timings?
2446 $TEST = substr($id, 0, -3);
2447 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)) {
2448 // Generate timestamp
2449 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2450 $DATA[] = "$TEST='".$POST[$TEST]."'";
2452 // Remove data from array
2453 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2454 unset($POST[$TEST."_".$rem]);
2458 unset($id); $skip = true; $TEST2 = $TEST;
2461 // Process this entry
2462 $skip = false; $TEST2 = "";
2465 // Reverts the german decimal comma into Computer decimal dot
2466 function REVERT_COMMA ($str) {
2467 // Default float is not a float... ;-)
2470 // Which language is selected?
2471 switch (GET_LANGUAGE()) {
2472 case "de": // German language
2473 // Remove german thousand dots first
2474 $str = str_replace(".", "", $str);
2476 // Replace german commata with decimal dot and cast it
2477 $float = (float)str_replace(",", ".", $str);
2480 default: // US and so on
2481 // Remove thousand dots first and cast
2482 $float = (float)str_replace(",", "", $str);
2489 // Handle menu-depending failed logins and return the rendered content
2490 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2491 // Default output is empty ;-)
2494 // Is the session data set?
2495 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2496 // Ignore zero values
2497 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2498 // Non-guest has login failtures found, get both data and prepare it for template
2499 //* DEBUG: */ echo __FUNCTION__.":accessLevel={$accessLevel}<br />\n";
2501 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2502 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2506 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2509 // Reset session data
2510 set_session('mxchange_'.$accessLevel.'_failtures', "");
2511 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2514 // Return rendered content
2518 function REBUILD_CACHE ($cache, $inc="") {
2519 global $cacheInstance;
2521 // Shall I remove the cache file?
2522 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2524 if ($cacheInstance->cache_file($cache, true)) {
2526 $cacheInstance->cache_destroy();
2528 // Include file given?
2530 // And rebuild it from scratch
2531 require_once(PATH."inc/loader/load_cache-".$inc.".php");
2536 // Purge admin menu cache
2537 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2538 global $_CONFIG, $cacheInstance;
2540 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2541 if (!EXT_IS_ACTIVE("cache")) {
2542 // Cache extension not active
2544 } elseif (!is_object($cacheInstance)) {
2545 // No cache instance!
2546 DEBUG_LOG(__FUNCTION__.": No cache instance found.");
2548 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2549 // Caching disabled (currently experiemental!)
2553 // Experiemental feature!
2554 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2557 //////////////////////////////////////////////////
2559 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2561 //////////////////////////////////////////////////
2563 if (!function_exists('html_entity_decode')) {
2564 // Taken from documentation on www.php.net
2565 function html_entity_decode($string) {
2566 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2567 $trans_tbl = array_flip($trans_tbl);
2568 return strtr($string, $trans_tbl);