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 = \"".COMPILE_CODE(addslashes($SUBJECT))."\";";
355 $SUBJECT = html_entity_decode($SUBJECT);
358 if ((!eregi("@", $TO)) && ($TO > 0)) {
359 // Value detected, load email from database
360 if (EXT_IS_ACTIVE("msg")) {
361 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
364 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
365 list($TO) = SQL_FETCHROW($result_email);
366 SQL_FREERESULT($result_email);
368 } elseif ($TO == 0) {
373 // Not in PHPMailer-Mode
374 if (!CHECK_PHPMAILER_USAGE()) {
376 // Load email header template
377 $FROM = LOAD_EMAIL_TEMPLATE("header");
380 $FROM .= LOAD_EMAIL_TEMPLATE("header");
382 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
384 // Load email header template
385 $FROM = LOAD_EMAIL_TEMPLATE("header");
388 $FROM .= LOAD_EMAIL_TEMPLATE("header");
392 // Fix HTML parameter (default is no!)
393 if (empty($HTML)) $HTML = "N";
394 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
395 // In debug mode we want to display the mail instead of sending it away so we can debug this part
397 ".htmlentities(trim($FROM))."
399 Subject : ".$SUBJECT."
402 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail", true))) {
403 // Send mail as HTML away
404 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
405 } elseif (!empty($TO)) {
407 $TO = COMPILE_CODE($TO);
410 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
411 } elseif ($HTML == "N") {
413 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
417 // Check if legacy or PHPMailer command
419 function CHECK_PHPMAILER_USAGE() {
420 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
424 * Send out a raw email with PHPMailer class or legacy mail() command
426 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
427 // Shall we use PHPMailer class or legacy mode?
428 if (CHECK_PHPMAILER_USAGE()) {
429 // Use PHPMailer class with SMTP enabled
430 require_once(PATH."inc/phpmailer/class.phpmailer.php");
431 require_once(PATH."inc/phpmailer/class.smtp.php");
434 $mail = new PHPMailer();
435 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
438 $mail->SMTPAuth = true;
439 $mail->Host = SMTP_HOSTNAME;
441 $mail->Username = SMTP_USER;
442 $mail->Password = SMTP_PASSWORD;
444 $mail->From = WEBMASTER;
448 $mail->FromName = MAIN_TITLE;
449 $mail->Subject = $subject;
450 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
452 $mail->AltBody = "Your mail program required HTML support to read this mail!";
453 $mail->WordWrap = 70;
458 $mail->AddAddress($to, "");
459 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
460 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
461 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
464 // Use legacy mail() command
465 @mail($to, $subject, $msg, $from);
470 // Generate a password in a specified length or use default password length
471 function GEN_PASS($LEN = 0) {
473 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
475 // Initialize array with all allowed chars
476 $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,-,+,_,/");
478 // Initialize randomizer
479 mt_srand((double) microtime() * 1000000);
481 // Start creating password
483 for ($i = 0; $i < $LEN; $i++) {
484 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
487 // When the size is below 40 we can also add additional security by scrambling it
488 if (strlen($PASS) <= 40) {
489 // Also scramble the password
490 $PASS = scrambleString($PASS);
493 // Return the password
497 function MAKE_DATETIME ($time, $mode="0")
501 return NEVER_HAPPENED;
503 // Filter out numbers
504 $time = bigintval($time);
507 switch (GET_LANGUAGE())
509 case "de": // German date / time format
511 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
512 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
513 case "2": $ret = date("d.m.Y|H:i", $time); break;
514 case "3": $ret = date("d.m.Y", $time); break;
518 default: // Default is the US date / time format!
520 case "0": $ret = date("r", $time); break;
521 case "1": $ret = date("Y-m-d - g:i A", $time); break;
522 case "2": $ret = date("y-m-d|H:i", $time); break;
523 case "3": $ret = date("y-m-d", $time); break;
529 // Translates the american decimal dot into a german comma
530 function TRANSLATE_COMMA ($dotted, $cut=true) {
533 // Default is 3 you can change this in admin area "Misc -> Misc Options"
534 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
535 $maxComma = $_CONFIG['max_comma'];
539 // Test for commata if in cut-mode
540 $com = explode(".", $dotted);
541 if (count($com) > 1) {
542 // Commata found, so only zeros?
543 if ($com[1] == str_repeat("0", strlen($com[1]))) {
544 // Only zeros, so don't display them
548 // Don't display commatas even if there are none... ;-)
554 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
557 switch (GET_LANGUAGE()) {
559 $dotted = number_format($dotted, $maxComma, ",", ".");
563 $dotted = number_format($dotted, $maxComma, ".", ",");
567 // Return translated value
572 function DEREFERER ($URL) {
573 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
578 function TRANSLATE_GENDER ($gender) {
581 case "M": $ret = GENDER_M; break;
582 case "F": $ret = GENDER_F; break;
583 case "C": $ret = GENDER_C; break;
584 default : $ret = $gender; break;
589 function GET_POOL_TYPE($PT) {
590 // Unknown pool type is default
591 $ret = POOL_UNKNOWN." (".$PT.")";
593 // Generate constant name
594 $constantName = sprintf("POOL_%s", $PT);
596 // Is the type known?
597 if (defined($constantName)) {
598 // Prepare eval command
599 $eval = sprintf("\$ret = %s;", $constantName);
607 function FRAMETESTER($URL) {
608 // Prepare frametester URL
609 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
611 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
613 return $frametesterUrl;
616 function SELECTION_COUNT($array) {
618 if (is_array($array)) {
619 foreach ($array as $key => $sel) {
620 if (!empty($sel)) $ret++;
626 function IMG_CODE ($code, $type, $DATA, $uid) {
627 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
630 function TRANSLATE_STATUS($status) {
634 $ret = ACCOUNT_UNCONFIRMED;
638 $ret = ACCOUNT_CONFIRMED;
642 $ret = ACCOUNT_LOCKED;
646 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
652 function GET_LANGUAGE() {
653 if (!empty($_GET['mx_lang'])) {
654 // Accept only first 2 chars
655 $lang = substr($_GET['mx_lang'], 0, 2);
661 // Set default return value to default language from config
664 // Check GET variable and cookie
666 // Check if main language file does exist
667 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
668 // Okay found, so let's update cookies
671 } elseif (!isSessionVariableSet('mx_lang')) {
672 // Return stored value from cookie
673 $ret = get_session('mx_lang');
675 // Fixes a warning before the session has the mx_lang constant
676 if (empty($ret)) $ret = DEFAULT_LANG;
681 function SET_LANGUAGE($lang) {
684 // Accept only first 2 chars!
685 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
688 set_session("mx_lang", $lang);
691 function LOAD_EMAIL_TEMPLATE($template, $content="", $UID="0") {
692 global $DATA, $_CONFIG, $REPLACER;
694 // Make sure all template names are lowercase!
695 $template = strtolower($template);
697 // Default "nickname" if extension is not installed
700 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
701 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
703 // Init variables (DEPRECATED! Use $content[bla] instead.
709 // Prepare IP number and User Agent
710 $REMOTE_ADDR = getenv('REMOTE_ADDR');
711 $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
714 if (isSessionVariableSet('admin_login')) {
716 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
717 array(get_session('admin_login')), __FILE__, __LINE__);
718 list($ADMIN) = SQL_FETCHROW($result);
719 SQL_FREERESULT($result);
722 // Expiration in a nice output format
723 if ($_CONFIG['auto_purge'] == 0) {
724 // Will never expire!
725 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
726 } elseif (function_exists('CREATE_FANCY_TIME')) {
727 // Create nice date string
728 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
731 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
734 // Is content an array?
735 if (is_array($content)) {
736 // Add expiration to array, $EXPIRATION is now deprecated!
737 $content['expiration'] = $EXPIRATION;
740 // @TODO Try to rewrite this part
741 if ($template == "add-points") {
742 if (isset($_POST['points'])) {
743 $points = bigintval($_POST['points']);
745 $points = __POINTS_VALUE;
751 if (EXT_IS_ACTIVE("nickname")) {
753 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
754 array(bigintval($UID)), __FILE__, __LINE__);
755 list($surname, $family, $gender, $email, $nick) = SQL_FETCHROW($result);
756 SQL_FREERESULT($result);
759 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
760 array(bigintval($UID)), __FILE__, __LINE__);
761 list($surname, $family, $gender, $email) = SQL_FETCHROW($result);
762 SQL_FREERESULT($result);
765 // Neutral gender and email address is default
770 // Translate M to male or F to female
771 $gender = TRANSLATE_GENDER($gender);
773 // Insert data if content is an array
774 if (is_array($content)) {
775 // Please do no longer use direct variable names, use $content[bla]
777 $content['gender'] = $gender;
778 $content['surname'] = $surname;
779 $content['family'] = $family;
780 $content['email'] = $email;
781 $content['nick'] = $nick;
784 // Store email for some functions in global data array
785 $DATA['email'] = $email;
788 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
790 // Check for admin/guest/member templates
791 if (strpos($template, "admin_") > -1) {
792 // Admin template found
793 $file = $BASE."admin/".$template.".tpl";
794 } elseif (strpos($template, "guest_") > -1) {
795 // Guest template found
796 $file = $BASE."guest/".$template.".tpl";
797 } elseif (strpos($template, "member_") > -1) {
798 // Member template found
799 $file = $BASE."member/".$template.".tpl";
801 // Test for extension
802 $test = substr($template, 0, strpos($template, "_"));
803 if (EXT_IS_ACTIVE($test)) {
804 // Set extra path to extension's name
805 $file = $BASE.$test."/".$template.".tpl";
807 // No special filename
808 $file = $BASE.$template.".tpl";
812 // Does the special template exists?
813 if (!FILE_READABLE($file)) {
814 // Reset to default template
815 $file = $BASE.$template.".tpl";
818 // Now does the final template exists?
820 if (FILE_READABLE($file)) {
821 // The local file does exists so we load it. :)
822 $tmpl_file = @implode("", @file($file));
823 $tmpl_file = addslashes($tmpl_file);
826 $tmpl_file = "\$newContent=\"".COMPILE_CODE($tmpl_file)."\";";
829 // Replace HTML conform chars
830 $newContent = html_entity_decode($newContent);
831 } elseif (!empty($template)) {
832 // Template file not found!
833 $newContent = TEMPLATE_404.": ".$template."<br />
835 <PRE>".print_r($newContent, true)."</PRE>
837 <PRE>".print_r($DATA, true)."</PRE>
840 // Debug mode not active? Then remove the HTML tags
841 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
843 // No template name supplied!
844 $newContent = NO_TEMPLATE_SUPPLIED;
847 // Is there some content?
848 if (empty($newContent)) {
850 $newContent = "Compiler error for template {$template}!";
853 // Return compiled content
854 return COMPILE_CODE($newContent);
857 function MAKE_TIME($H, $M, $S, $stamp) {
858 // Extract day, month and year from given timestamp
859 $DAY = date("d", $stamp);
860 $MONTH = date("m", $stamp);
861 $YEAR = date('Y', $stamp);
863 // Create timestamp for wished time which depends on extracted date
864 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
867 function LOAD_URL($URL, $addUrlData=true) {
868 global $CSS, $_CONFIG, $footer;
870 // Check if http(s):// is there
871 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
872 // Make all URLs full-qualified
876 // Compile out URI codes
877 $URL = COMPILE_CODE($URL);
880 $OUTPUT = ob_get_contents();
885 // Add some data to URL if cookies are not accepted
886 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
888 // Probe for bot from search engine
889 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
890 // Search engine bot detected so let's rewrite many chars for the link
891 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
893 // Output new location link as anchor
894 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
895 } elseif (!headers_sent()) {
896 // Load URL when headers are not sent
899 debug_print_backtrace();
900 die("</pre>URL={$URL}");
902 @header ("Location: ".str_replace("&", "&", $URL));
904 // Output error message
905 include(PATH."inc/header.php");
906 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
907 include(PATH."inc/footer.php");
912 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
913 global $SEC_CHARS, $URL_CHARS;
916 // Select smaller set of chars to replace when we e.g. want to compile URLs
917 if (!$full) $ARRAY = $URL_CHARS;
921 // BEFORE 0.2.1 : Language and data constants
922 // WITH 0.2.1+ : Only language constants
923 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
925 // BEFORE 0.2.1 : Not used
926 // WITH 0.2.1+ : Data constants
927 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
930 // Compile QUOT and other non-HTML codes
931 foreach ($ARRAY['to'] as $k => $to) {
932 // Do the reversed thing as in inc/libs/security_functions.php
933 $code = str_replace($to, $ARRAY['from'][$k], $code);
936 // But shall I keep simple quotes for later use?
937 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
939 // Find $content[bla][blub] entries
940 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
942 // Are some matches found?
943 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
944 // Replace all matches
945 $matchesFound = array();
946 foreach ($matches[0] as $key => $match) {
947 // Avoid replacing matches multiple times
948 if (!isset($matchesFound[$match])) {
950 $code = str_replace($match, "\".".$match.".\"", $code);
951 $matchesFound[$match] = 1;
954 // Take all string elements
955 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
956 // Replace it in the code
957 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
958 $code = str_replace($match, $newMatch, $code);
959 $matchesFound[$key."_".$matches[4][$key]] = 1;
964 // Return compiled code
968 /************************************************************************
970 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
971 * $a_sort sortiert: *
973 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
974 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
975 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
976 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
977 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
979 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
980 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
981 * Sie, dass es doch nicht so schwer ist! :-) *
983 ************************************************************************/
984 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
987 while ($primary_key < count($a_sort)) {
988 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
989 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
992 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
993 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
994 } elseif ($key != $key2) {
995 // Sort numbers (E.g.: 9 < 10)
996 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
997 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1001 // We have found two different values, so let's sort whole array
1002 foreach ($dummy as $sort_key => $sort_val) {
1003 $t = $dummy[$sort_key][$key];
1004 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1005 $dummy[$sort_key][$key2] = $t;
1016 // Write back sorted array
1020 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1022 global $MONTH_DESCR; $OUT = "";
1025 // This is a yes/no selection only!
1026 if ($id > 0) $prefix .= "[".$id."]";
1027 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1031 // Begin with regular selection box here
1032 if (!empty($prefix)) $prefix .= "_";
1034 if ($id > 0) $type2 .= "[".$id."]";
1035 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1040 for ($idx = 1; $idx < 32; $idx++)
1042 $OUT .= "<OPTION value=\"".$idx."\"";
1043 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1044 $OUT .= ">".$idx."</OPTION>\n";
1048 case "month": // Month
1049 foreach ($MONTH_DESCR as $month => $descr)
1051 $OUT .= "<OPTION value=\"".$month."\"";
1052 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1053 $OUT .= ">".$descr."</OPTION>\n";
1057 case "year": // Year
1059 $YEAR = date('Y', time());
1061 // Check if the default value is larger than minimum and bigger than actual year
1062 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1064 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1066 $OUT .= "<OPTION value=\"".$idx."\"";
1067 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1068 $OUT .= ">".$idx."</OPTION>\n";
1071 elseif ($DEFAULT == -1)
1073 // Current year minus 1
1074 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1076 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1081 // Get current year and subtract 16 (for erotic content)
1082 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1083 $YEAR = date('Y', time()) - 16;
1084 for ($idx = 1930; $idx <= $YEAR; $idx++)
1086 $OUT .= "<OPTION value=\"".$idx."\"";
1087 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1088 $OUT .= ">".$idx."</OPTION>\n";
1095 for ($idx = 0; $idx < 60; $idx+=5) {
1096 if (strlen($idx) == 1) $idx = "0".$idx;
1097 $OUT .= "<OPTION value=\"".$idx."\"";
1098 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1099 $OUT .= ">".$idx."</OPTION>\n";
1104 for ($idx = 0; $idx < 24; $idx++) {
1105 if (strlen($idx) == 1) $idx = "0".$idx;
1106 $OUT .= "<OPTION value=\"".$idx."\"";
1107 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1108 $OUT .= ">".$idx."</OPTION>\n";
1113 $OUT .= "<OPTION value=\"Y\"";
1114 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1115 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1116 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1117 $OUT .= ">".NO."</OPTION>\n";
1120 $OUT .= " </SELECT>\n";
1124 function TRANSLATE_YESNO($yn)
1128 case 'Y': $yn = YES; break;
1129 case 'N': $yn = NO; break;
1130 default : $yn = "??? (".$yn.")"; break;
1135 // Deprecated : $length
1138 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1141 // Fix missing _MAX constant
1142 if (!defined('_MAX')) define('_MAX', 15235);
1144 // Build server string
1145 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1148 $keys = SITE_KEY.":".DATE_KEY;
1149 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1150 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1151 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1152 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1154 // Build string from misc data
1155 $data = $code.":".$uid.":".$DATA;
1157 // Add more additional data
1158 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1159 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1160 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1161 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1162 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1163 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1165 // Calculate number for generating the code
1166 $a = $code + _ADD - 1;
1168 if (isset($_CONFIG['master_hash'])) {
1169 // Generate hash with master salt from modula of number with the prime number and other data
1170 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1172 // Create number from hash
1173 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1175 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1176 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1178 // Create number from hash
1179 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1182 // At least 10 numbers shall be secure enought!
1183 $len = $_CONFIG['code_length'];
1184 if ($len == 0) $len = $length;
1185 if ($len == 0) $len = 10;
1187 // Cut off requested counts of number
1188 $return = substr(str_replace('.', "", $rcode), 0, $len);
1190 // Done building code
1193 // Does only allow numbers
1194 function bigintval($num, $castValue = true) {
1195 // Filter all numbers out
1196 $ret = preg_replace("/[^0123456789]/", "", $num);
1199 if ($castValue) $ret = (double)$ret;
1201 // Has the whole value changed?
1202 if ("".$ret."" != "".$num."") {
1204 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1210 // Insert the code in $img_code into jpeg or PNG image
1211 function GENERATE_IMAGE($img_code, $header=true) {
1214 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1215 // Stop execution of function here because of over-sized code length
1217 } elseif (!$header) {
1218 // Return in an HTML code code
1219 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1223 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1224 if (FILE_READABLE($img)) {
1225 // Switch image type
1226 switch ($_CONFIG['img_type'])
1229 // Okay, load image and hide all errors
1230 $image = @imagecreatefromjpeg($img);
1234 // Okay, load image and hide all errors
1235 $image = @imagecreatefrompng($img);
1239 // Exit function here
1243 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1244 $text_color = imagecolorallocate($image, 0, 0, 0);
1246 // Insert code into image
1247 imagestring($image, 5, 14, 2, $img_code, $text_color);
1249 // Return to browser
1250 header ("Content-Type: image/".$_CONFIG['img_type']);
1252 // Output image with matching image factory
1253 switch ($_CONFIG['img_type']) {
1254 case "jpg": imagejpeg($image); break;
1255 case "png": imagepng($image); break;
1258 // Remove image from memory
1259 imagedestroy($image);
1261 // Create selection box or array of splitted timestamp
1262 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1263 // Calculate 2-seconds timestamp
1264 $stamp = round($timestamp / 2) * 2;
1266 // Do we have a leap year?
1268 $TEST = date('Y', time()) / 4;
1269 $M1 = date("m", time());
1270 $M2 = date("m", (time() + $stamp));
1272 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1273 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1275 // First of all years...
1276 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1278 $M = abs(floor($stamp / 2628000 - $Y * 12));
1280 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1282 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1284 $h = abs(floor($stamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1286 $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));
1287 // And at last seconds...
1288 $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));
1290 // Is seconds zero and time is < 60 seconds?
1291 if (($s == 0) && ($stamp < 60)) {
1293 $s = round($timestamp);
1297 // Now we convert them in seconds...
1299 if ($return_array) {
1300 // Just put all data in an array for later use
1312 $OUT = "<DIV align=\"".$align."\">\n";
1313 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1316 if (ereg('Y', $display) || (empty($display))) {
1317 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1320 if (ereg("M", $display) || (empty($display))) {
1321 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1324 if (ereg("W", $display) || (empty($display))) {
1325 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1328 if (ereg("D", $display) || (empty($display))) {
1329 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1332 if (ereg("h", $display) || (empty($display))) {
1333 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1336 if (ereg("m", $display) || (empty($display))) {
1337 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1340 if (ereg("s", $display) || (empty($display))) {
1341 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1347 if (ereg('Y', $display) || (empty($display))) {
1348 // Generate year selection
1349 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1350 for ($idx = 0; $idx <= 10; $idx++) {
1351 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1352 if ($idx == $Y) $OUT .= " selected default";
1353 $OUT .= ">".$idx."</OPTION>\n";
1355 $OUT .= " </SELECT></TD>\n";
1357 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1360 if (ereg("M", $display) || (empty($display))) {
1361 // Generate month selection
1362 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1363 for ($idx = 0; $idx <= 11; $idx++)
1365 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1366 if ($idx == $M) $OUT .= " selected default";
1367 $OUT .= ">".$idx."</OPTION>\n";
1369 $OUT .= " </SELECT></TD>\n";
1371 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1374 if (ereg("W", $display) || (empty($display))) {
1375 // Generate week selection
1376 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1377 for ($idx = 0; $idx <= 4; $idx++) {
1378 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1379 if ($idx == $W) $OUT .= " selected default";
1380 $OUT .= ">".$idx."</OPTION>\n";
1382 $OUT .= " </SELECT></TD>\n";
1384 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1387 if (ereg("D", $display) || (empty($display))) {
1388 // Generate day selection
1389 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1390 for ($idx = 0; $idx <= 31; $idx++) {
1391 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1392 if ($idx == $D) $OUT .= " selected default";
1393 $OUT .= ">".$idx."</OPTION>\n";
1395 $OUT .= " </SELECT></TD>\n";
1397 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1400 if (ereg("h", $display) || (empty($display))) {
1401 // Generate hour selection
1402 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1403 for ($idx = 0; $idx <= 23; $idx++) {
1404 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1405 if ($idx == $h) $OUT .= " selected default";
1406 $OUT .= ">".$idx."</OPTION>\n";
1408 $OUT .= " </SELECT></TD>\n";
1410 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1413 if (ereg("m", $display) || (empty($display))) {
1414 // Generate minute selection
1415 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1416 for ($idx = 0; $idx <= 59; $idx++) {
1417 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1418 if ($idx == $m) $OUT .= " selected default";
1419 $OUT .= ">".$idx."</OPTION>\n";
1421 $OUT .= " </SELECT></TD>\n";
1423 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1426 if (ereg("s", $display) || (empty($display))) {
1427 // Generate second selection
1428 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1429 for ($idx = 0; $idx <= 45; $idx += 15) {
1430 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1431 if ($idx == $s) $OUT .= " selected default";
1432 $OUT .= ">".$idx."</OPTION>\n";
1434 $OUT .= " </SELECT></TD>\n";
1436 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1439 $OUT .= "</TABLE>\n";
1441 // Return generated HTML code
1446 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1449 // Do we have a leap year?
1451 $TEST = date('Y', time()) / 4;
1452 $M1 = date("m", time());
1453 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1454 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1455 // First add years...
1456 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1458 $ret += $POST[$prefix."_mo"] * 2628000;
1460 $ret += $POST[$prefix."_we"] * 604800;
1462 $ret += $POST[$prefix."_da"] * 86400;
1464 $ret += $POST[$prefix."_ho"] * 3600;
1466 $ret += $POST[$prefix."_mi"] * 60;
1467 // And at last seconds...
1468 $ret += $POST[$prefix."_se"];
1469 // Return calculated value
1472 // Sends out mail to all administrators
1473 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1474 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1475 // Trim template name
1476 $template = trim($template);
1478 // Load email template
1479 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1481 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1482 // Older version detected!
1483 return SEND_ADMIN_EMAILS($subj, $msg);
1486 // Check which admin shall receive this mail
1487 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1488 array($template), __FILE__, __LINE__);
1489 if (SQL_NUMROWS($result) == 0) {
1490 // Create new entry (to all admins)
1491 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1492 array($template), __FILE__, __LINE__);
1494 // Load admin IDs...
1496 while(list($aid) = SQL_FETCHROW($result)) {
1501 SQL_FREERESULT($result);
1503 // "implode" IDs and query string
1504 $aid = implode(",", $aids);
1506 // Add line to userlog
1507 USERLOG_ADD_LINE($subj, $msg, $UID);
1509 } elseif ($aid == "0") {
1510 // Select all email adresses
1511 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1513 // If Admin-ID is not "to-all" select
1514 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1518 // Load email addresses and send away
1519 while (list($email) = SQL_FETCHROW($result)) {
1520 SEND_EMAIL($email, $subj, $msg);
1524 SQL_FREERESULT($result);
1527 function CREATE_FANCY_TIME($stamp) {
1528 // Get data array with years/months/weeks/days/...
1529 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1531 foreach($data as $k => $v) {
1533 // Value is greater than 0 "eval" data to return string
1534 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1540 // Do we have something there?
1541 if (strlen($ret) > 0) {
1542 // Remove leading commata and space
1543 $ret = substr($ret, 2);
1546 $ret = "0 "._SECONDS;
1549 // Return fancy time string
1553 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1554 $SEP = ""; $TOP = "";
1557 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1561 for ($page = 1; $page <= $PAGES; $page++) {
1562 // Is the page currently selected or shall we generate a link to it?
1563 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1564 // Is currently selected, so only highlight it
1565 $NAV .= "<STRONG>-";
1567 // Open anchor tag and add base URL
1568 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1570 // Add userid when we shall show all mails from a single member
1571 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1573 // Close open anchor tag
1577 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1578 // Is currently selected, so only highlight it
1579 $NAV .= "-</STRONG>";
1585 // Add seperator if we have not yet reached total pages
1586 if ($page < $PAGES) $NAV .= " | ";
1589 // Define constants only once
1590 if (!defined('__NAV_OUTPUT')) {
1591 define('__NAV_OUTPUT' , $NAV);
1592 define('__NAV_COLSPAN', $colspan);
1593 define('__NAV_TOP' , $TOP);
1594 define('__NAV_SEP' , $SEP);
1597 // Load navigation template
1598 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1601 // Return generated HTML-Code
1609 // Extract host from script name
1610 function EXTRACT_HOST (&$script) {
1611 // Use default SERVER_URL by default... ;) So?
1614 // Is this URL valid?
1615 if (substr($script, 0, 7) == "http://") {
1616 // Use the hostname from script URL as new hostname
1617 $url = substr($script, 7);
1618 $extract = explode("/", $url);
1620 // Done extracting the URL :)
1623 // Extract host name
1624 $host = str_replace("http://", "", $url);
1625 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1627 // Generate relative URL
1628 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1629 if (substr(strtolower($script), 0, 7) == "http://") {
1630 // But only if http:// is in front!
1631 $script = substr($script, (strlen($url) + 7));
1632 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1634 $script = substr($script, (strlen($url) + 8));
1637 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1638 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1644 // Send a GET request
1645 function GET_URL ($script) {
1646 // Compile the script name
1647 $script = COMPILE_CODE($script);
1649 // Extract host name from script
1650 $host = EXTRACT_HOST($script);
1652 // Generate GET request header
1653 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1654 $request .= "Host: " . $host . "\r\n";
1655 $request .= "Referer: " . URL . "/admin.php\r\n";
1656 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1657 $request .= "Content-Type: text/plain\r\n";
1658 $request .= "Cache-Control: no-cache\r\n";
1659 $request .= "Connection: Close\r\n\r\n";
1661 // Send the raw request
1662 $response = SEND_RAW_REQUEST($host, $request);
1664 // Return the result to the caller function
1668 // Send a POST request
1669 function POST_URL ($script, $postData) {
1670 // Is postData an array?
1671 if (!is_array($postData)) {
1673 return array("", "", "");
1676 // Compile the script name
1677 $script = COMPILE_CODE($script);
1679 // Extract host name from script
1680 $host = EXTRACT_HOST($script);
1682 // Construct request
1683 $data = http_build_query($postData, '', '&');
1685 // Generate POST request header
1686 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1687 $request .= "Host: " . $host . "\r\n";
1688 $request .= "Referer: " . URL . "/admin.php\r\n";
1689 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1690 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1691 $request .= "Content-length: " . strlen($data) . "\r\n";
1692 $request .= "Cache-Control: no-cache\r\n";
1693 $request .= "Connection: Close\r\n\r\n";
1696 // Send the raw request
1697 $response = SEND_RAW_REQUEST($host, $request);
1699 // Return the result to the caller function
1703 // Sends a raw request to another host
1704 function SEND_RAW_REQUEST ($host, $request) {
1708 $response = array("", "", "");
1710 // Default is not to use proxy
1713 // Are proxy settins set?
1714 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1720 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1722 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1724 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1728 if (!is_resource($fp)) {
1735 // Generate CONNECT request header
1736 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1737 $proxyTunnel .= "Host: ".$host."\r\n";
1739 // Use login data to proxy? (username at least!)
1740 if (!empty($_CONFIG['proxy_username'])) {
1742 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1743 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1746 // Add last new-line
1747 $proxyTunnel .= "\r\n";
1748 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1751 fputs($fp, $proxyTunnel);
1755 // No response received
1759 // Read the first line
1760 $resp = trim(fgets($fp, 10240));
1761 $respArray = explode(" ", $resp);
1762 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1763 // Invalid response!
1769 fputs($fp, $request);
1773 $response[] = trim(fgets($fp, 1024));
1779 // Skip first empty lines
1781 foreach ($resp as $idx => $line) {
1783 $line = trim($line);
1785 // Is this line empty?
1788 array_shift($response);
1790 // Abort on first non-empty line
1795 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1797 // Proxy agent found?
1798 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1799 // Proxy header detected, so remove two lines
1800 array_shift($response);
1801 array_shift($response);
1804 // Was the request successfull?
1805 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1806 // Not found / access forbidden
1807 $response = array("", "", "");
1813 // Taken from www.php.net eregi() user comments
1814 function VALIDATE_EMAIL($email) {
1816 $email = COMPILE_CODE($email);
1818 // Check first part of email address
1819 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1822 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1825 $regex = "^".$first."@".$domain."$";
1827 // Return check result
1828 return eregi($regex, $email);
1830 // Function taken from user comments on www.php.net / function eregi()
1831 function VALIDATE_URL ($URL, $compile=true) {
1832 // Trim URL a little
1833 $URL = trim(urldecode($URL));
1834 //* DEBUG: */ echo $URL."<br />";
1836 // Compile some chars out...
1837 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1838 //* DEBUG: */ echo $URL."<br />";
1840 // Check for the extension filter
1841 if (EXT_IS_ACTIVE("filter")) {
1842 // Use the extension's filter set
1843 return FILTER_VALIDATE_URL($URL, false);
1846 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1847 // https:// in front of the URLs
1848 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1851 function MEMBER_ACTION_LINKS($uid, $status="") {
1852 // Define all main targets
1853 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1855 // Begin of navigation links
1856 $eval = "\$OUT = \"[ ";
1858 foreach ($TARGETS as $tar) {
1859 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1860 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1861 if (($tar == "lock_user") && ($status == "LOCKED")) {
1862 // Locked accounts shall be unlocked
1863 $eval .= "UNLOCK_USER";
1865 // All other status is fine
1866 $eval .= strtoupper($tar);
1868 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1869 if (($tar == "lock_user") && ($status == "LOCKED")) {
1870 // Locked accounts shall be unlocked
1871 $eval .= "UNLOCK_USER";
1873 // All other status is fine
1874 $eval .= strtoupper($tar);
1876 $eval .= ".\"</A></SPAN> | ";
1879 // Finish navigation link
1880 $eval = substr($eval, 0, -7)."]\";";
1886 // Function for backward-compatiblity
1887 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1888 // Load it from the register extension
1889 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1891 // Generate an email link
1892 function CREATE_EMAIL_LINK($email, $table="admins") {
1893 // Default email link (INSECURE! Spammer can read this by harvester programs)
1894 $EMAIL = "mailto:".$email;
1896 // Check for several extensions
1897 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1898 // Create email link for contacting admin in guest area
1899 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1900 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1901 // Create email link for contacting a member within admin area (or later in other areas, too?)
1902 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1903 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1904 // Create email link to contact sponsor within admin area (or like the link above?)
1905 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1908 // Shall I close the link when there is no admin?
1909 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1911 // Return email link
1914 // Generate a hash for extra-security for all passwords
1915 function generateHash ($plainText, $salt = "") {
1916 global $_CONFIG, $_SERVER;
1918 // Is the required extension "sql_patches" there and a salt is not given?
1919 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == "")) && (empty($salt))) {
1920 // Extension sql_patches is missing/outdated so we return the plain text
1924 // Do we miss an arry element here?
1925 if (!isset($_CONFIG['file_hash'])) {
1927 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1928 debug_print_backtrace();
1932 // When the salt is empty build a new one, else use the first x configured characters as the salt
1934 // Build server string
1935 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1938 $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'];
1941 $data = $plainText.":".uniqid(rand(), true).":".time();
1943 // Calculate number for generating the code
1944 $a = time() + _ADD - 1;
1946 // Generate SHA1 sum from modula of number and the prime number
1947 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1948 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
1949 $sha1 = scrambleString($sha1);
1950 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
1951 //* DEBUG: */ $sha1b = descrambleString($sha1);
1952 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
1954 // Generate the password salt string
1955 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1956 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1959 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1960 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
1964 return $salt.sha1($salt.$plainText);
1967 function scrambleString($str) {
1973 // Final check, in case of failture it will return unscrambled string
1974 if (strlen($str) > 40) {
1975 // The string is to long
1977 } elseif (strlen($str) == 40) {
1979 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1981 // Generate new numbers
1982 $scrambleNums = explode(":", genScrambleString(strlen($str)));
1985 // Scramble string here
1986 //* DEBUG: */ echo "***Original=".$str."***<br />";
1987 for ($idx = 0; $idx < strlen($str); $idx++) {
1988 // Get char on scrambled position
1989 $char = substr($str, $scrambleNums[$idx], 1);
1991 // Add it to final output string
1992 $scrambled .= $char;
1995 // Return scrambled string
1996 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2000 function descrambleString($str) {
2002 // Scramble only 40 chars long strings
2003 if (strlen($str) != 40) return $str;
2005 // Load numbers from config
2006 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2009 if (count($scrambleNums) != 40) return $str;
2011 // Begin descrambling
2012 $orig = str_repeat(" ", 40);
2013 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2014 for ($idx = 0; $idx < 40; $idx++) {
2015 $char = substr($str, $idx, 1);
2016 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2019 // Return scrambled string
2020 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2024 function genScrambleString($len) {
2025 // Prepare randomizer and array for the numbers
2026 mt_srand((double) microtime() * 1000000);
2027 $scrambleNumbers = array();
2029 // First we need to setup randomized numbers from 0 to 31
2030 for ($idx = 0; $idx < $len; $idx++) {
2032 $rand = mt_rand(0, ($len -1));
2034 // Check for it by creating more numbers
2035 while (array_key_exists($rand, $scrambleNumbers)) {
2036 $rand = mt_rand(0, ($len -1));
2040 $scrambleNumbers[$rand] = $rand;
2043 // So let's create the string for storing it in database
2044 $scrambleString = implode(":", $scrambleNumbers);
2045 return $scrambleString;
2047 // Append data like session ID referral ID to the given URL which would
2048 // normally be stored in cookies
2049 function ADD_URL_DATA($URL) {
2053 // Determine URL binder
2055 if (strpos($URL, "?") !== false) $BIND = "&";
2057 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2058 // Cookies are not accepted
2059 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2060 // Cookie found in URL
2061 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2062 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2063 // Not found! So let's set default here
2064 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2067 // Is there already added data? Then change the binder
2068 if (!empty($ADD)) $BIND = "&";
2071 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2072 // Add session from URL
2073 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2075 // Add current session
2076 $ADD .= $BIND."PHPSESSID=".session_id();
2080 // Add all together and return it
2083 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2084 function generatePassString($passHash) {
2087 // Return vanilla password hash
2090 // Is a secret key and master salt already initialized?
2091 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2092 // Only calculate when the secret key is generated
2093 $newHash = ""; $start = 9;
2094 for ($idx = 0; $idx < 10; $idx++) {
2095 $part1 = hexdec(substr($passHash, $start, 4));
2096 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2097 $mod = dechex($idx);
2098 if ($part1 > $part2) {
2099 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2100 } elseif ($part2 > $part1) {
2101 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2103 $mod = substr(round($mod), 0, 4);
2104 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2105 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2110 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2111 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2112 //* DEBUG: */ print($ret."<br />\n");
2115 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2116 $ret = md5($passHash);
2117 //* DEBUG: */ echo "++".$ret."++<br />\n";
2124 // Fix "deleted" cookies
2125 function FIX_DELETED_COOKIES ($cookies) {
2126 // Is this an array with entries?
2127 if ((is_array($cookies)) && (count($cookies) > 0)) {
2128 // Then check all cookies if they are marked as deleted!
2129 foreach ($cookies as $cookieName) {
2130 // Is the cookie set to "deleted"?
2131 if (get_session($cookieName) == "deleted") {
2132 set_session($cookieName, "");
2138 // Output error messages in a fasioned way and die...
2139 function mxchange_die ($msg) {
2142 // Load the message template
2143 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2146 include(PATH."inc/footer.php");
2152 // Display parsing time and number of SQL queries in footer
2153 function DISPLAY_PARSING_TIME_FOOTER() {
2154 global $startTime, $_CONFIG;
2155 $endTime = microtime(true);
2157 // Is the timer started?
2158 if (!isset($GLOBALS['startTime'])) {
2163 // "Explode" both times
2164 $start = explode(" ", $GLOBALS['startTime']);
2165 $end = explode(" ", $endTime);
2166 $runTime = $end[0] - $start[0];
2167 if ($runTime < 0) $runTime = 0;
2168 $runTime = TRANSLATE_COMMA($runTime);
2172 'runtime' => $runTime,
2173 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2174 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2177 // Load the template
2178 LOAD_TEMPLATE("show_timings", false, $content);
2181 // Unset/set session variables
2182 function set_session ($var, $value) {
2185 // Abort in CSS mode here
2186 if ($CSS == 1) return true;
2188 // Trim value and session variable
2189 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2191 // Is the session variable set?
2192 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2193 // Remove the session
2194 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2195 unset($_SESSION[$var]);
2196 return session_unregister($var);
2197 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2199 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2200 $_SESSION[$var] = $value;
2201 return session_register($var);
2202 } elseif (!empty($value)) {
2204 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2205 $_SESSION[$var] = $value;
2209 // Ignored (but valid)
2210 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2214 // Check wether a boolean constant is set
2215 // Taken from user comments in PHP documentation for function constant()
2216 function isBooleanConstantAndTrue($constName) { // : Boolean
2219 // Failed by default
2223 if (isset($constCache[$constName])) {
2225 $res = $constCache[$constName];
2228 if (defined($constName)) $res = (constant($constName) === true);
2231 $constCache[$constName] = $res;
2238 // Check wether a session variable is set
2239 function isSessionVariableSet($var) {
2240 //* DEBUG: */ echo __FUNCTION__.":var={$var}<br />\n";
2241 return (isset($_SESSION[$var]));
2243 // Returns wether the value of the session variable or NULL if not set
2244 function get_session($var) {
2247 // Default is not found! ;-)
2250 // Is the variable there or cached values?
2251 if (isset($cacheArray['session'][$var])) {
2252 // Get cached value (skips a lot SQL_ESCAPE() calles!
2253 $value = $cacheArray['session'][$var];
2254 } elseif (isSessionVariableSet($var)) {
2255 // Then get it secured!
2256 $value = SQL_ESCAPE($_SESSION[$var]);
2259 $cacheArray['session'][$var] = $value;
2265 // Send notification to admin
2266 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content="", $uid="0") {
2267 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2269 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2271 // Send outdated way
2272 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2273 SEND_ADMIN_EMAILS($subject, $msg);
2276 // Destroy user session
2277 function destroy_user_session () {
2278 // Remove all user data from session
2279 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2281 // Merges an array together but only if both are arrays
2282 function merge_array ($array1, $array2) {
2283 // Are both an array?
2284 if ((is_array($array1)) && (is_array($array2))) {
2285 // Merge all together
2286 return array_merge($array1, $array2);
2287 } elseif (is_array($array1)) {
2288 // Return left array
2292 // Something wired happened here...
2293 print(__FUNCTION__.":<pre>");
2294 debug_print_backtrace();
2297 // Debug message logger
2298 function DEBUG_LOG ($message) {
2299 // Is debug mode enabled?
2300 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
2301 // Log this message away
2302 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2303 fwrite($fp, date("d.m.Y|H:i:s", time())."|{$message}\n");
2307 // Reads a directory with PHP files in and gets only files back
2308 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2312 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2315 while ($baseFile = readdir($dirPointer)) {
2316 // Load file only if extension is active
2318 $file = $baseDir.$baseFile;
2320 // Is this a valid reset file?
2321 //* DEBUG: */ echo __FUNCTION__.":baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2322 if ((is_file($file)) && (is_readable($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2323 // Remove both for extension name
2324 $extName = substr($baseFile, strlen($prefix), -4);
2327 $extId = GET_EXT_ID($extName);
2329 // Is the extension valid and active?
2330 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2331 // Then add this file
2333 } elseif ($extId == 0) {
2334 // Add non-extension files as well
2341 closedir($dirPointer);
2343 // Return array with include files
2346 // Load more reset scripts
2347 function RESET_ADD_INCLUDES () {
2350 // Is the reset set or old sql_patches?
2351 if ((!isBooleanConstantAndTrue('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2356 // Get more daily reset scripts
2357 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2359 // Create current week mark
2360 $currWeek = date("W", time());
2363 if ($_CONFIG['last_week'] != $currWeek) {
2364 // Include weekly reset scripts
2365 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2368 UPDATE_CONFIG("last_week", $currWeek);
2371 // Create current month mark
2372 $currMonth = date("m", time());
2375 if ($_CONFIG['last_month'] != $currMonth) {
2376 // Include monthly reset scripts
2377 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2380 UPDATE_CONFIG("last_month", $currMonth);
2386 // Handle extra values
2387 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2388 // Default is the value itself
2391 // Do we have a special filter function?
2392 if (!empty($filterFunction)) {
2393 // Does the filter function exist?
2394 if (function_exists($filterFunction)) {
2395 // Do we have extra parameters here?
2396 if (!empty($extraValue)) {
2397 // Put both parameters in one new array by default
2398 $args = array($value, $extraValue);
2400 // If we have an array simply use it and pre-extend it with our value
2401 if (is_array($extraValue)) {
2402 // Make the new args array
2403 $args = array_merge(array($value), $extraValue);
2406 // Call the multi-parameter call-back
2407 $ret = call_user_func_array($filterFunction, $args);
2409 // One parameter call
2410 $ret = call_user_func($filterFunction, $value);
2418 // Check if given FQFN is a readable file
2419 function FILE_READABLE($fqfn) {
2421 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2423 // Converts timestamp selections into a timestamp
2424 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2425 // Init test variable
2428 // Get last three chars
2429 $TEST = substr($id, -3);
2431 // Improved way of checking! :-)
2432 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2433 // Found a multi-selection for timings?
2434 $TEST = substr($id, 0, -3);
2435 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)) {
2436 // Generate timestamp
2437 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2438 $DATA[] = "$TEST='".$POST[$TEST]."'";
2440 // Remove data from array
2441 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2442 unset($POST[$TEST."_".$rem]);
2446 unset($id); $skip = true; $TEST2 = $TEST;
2449 // Process this entry
2450 $skip = false; $TEST2 = "";
2453 // Reverts the german decimal comma into Computer decimal dot
2454 function REVERT_COMMA ($str) {
2455 // Default float is not a float... ;-)
2458 // Which language is selected?
2459 switch (GET_LANGUAGE()) {
2460 case "de": // German language
2461 // Remove german thousand dots first
2462 $str = str_replace(".", "", $str);
2464 // Replace german commata with decimal dot and cast it
2465 $float = (float)str_replace(",", ".", $str);
2468 default: // US and so on
2469 // Remove thousand dots first and cast
2470 $float = (float)str_replace(",", "", $str);
2477 // Handle menu-depending failed logins and return the rendered content
2478 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2479 // Default output is empty ;-)
2482 // Is the session data set?
2483 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2484 // Ignore zero values
2485 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2486 // Non-guest has login failtures found, get both data and prepare it for template
2487 //* DEBUG: */ echo __FUNCTION__.":accessLevel={$accessLevel}<br />\n";
2489 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2490 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2494 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2497 // Reset session data
2498 set_session('mxchange_'.$accessLevel.'_failtures', "");
2499 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2502 // Return rendered content
2506 function REBUILD_CACHE ($cache, $inc="") {
2507 global $cacheInstance;
2509 // Shall I remove the cache file?
2510 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2512 if ($cacheInstance->cache_file($cache, true)) {
2514 $cacheInstance->cache_destroy();
2516 // Include file given?
2518 // And rebuild it from scratch
2519 require_once(PATH."inc/loader/load_cache-".$inc.".php");
2524 // Purge admin menu cache
2525 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2526 global $_CONFIG, $cacheInstance;
2528 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2529 if (!EXT_IS_ACTIVE("cache")) {
2530 // Cache extension not active
2532 } elseif (!is_object($cacheInstance)) {
2533 // No cache instance!
2534 DEBUG_LOG(__FUNCTION__.": No cache instance found.");
2536 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2537 // Caching disabled (currently experiemental!)
2541 // Experiemental feature!
2542 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2545 //////////////////////////////////////////////////
2547 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2549 //////////////////////////////////////////////////
2551 if (!function_exists('html_entity_decode')) {
2552 // Taken from documentation on www.php.net
2553 function html_entity_decode($string) {
2554 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2555 $trans_tbl = array_flip($trans_tbl);
2556 return strtr($string, $trans_tbl);