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 // Extension "rewrite" installed?
137 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
138 $OUTPUT = REWRITE_LINKS($OUTPUT);
141 // Compile and run finished rendered HTML code
142 while (strpos($OUTPUT, '{!') > 0) {
143 // Prepare the content and eval() it...
145 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
148 // Was that eval okay?
149 if (empty($newContent)) {
150 // Something went wrong!
151 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
153 $OUTPUT = $newContent;
156 // Output code here, DO NOT REMOVE! ;-)
158 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
159 // Rewrite links when rewrite extension is active
160 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
161 $OUTPUT = REWRITE_LINKS($OUTPUT);
164 // Compile and run finished rendered HTML code
165 while (strpos($OUTPUT, '{!') > 0) {
166 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
170 // Output code here, DO NOT REMOVE! ;-)
175 // Output the raw HTML code
176 function OUTPUT_RAW ($HTML) {
177 // Output stripped HTML code to avoid broken JavaScript code, etc.
178 echo stripslashes(stripslashes($HTML));
180 // Flush the output if only _OB_CACHING is not "on"
181 if (_OB_CACHING != "on") {
187 // Add a fatal error message to the queue array
188 function ADD_FATAL ($message, $extra="") {
191 // Regular text message to add to $FATAL
194 // $message is text with a mask plus extras to insert into the text
195 $FATAL[] = sprintf($message, $extra);
199 // Load a template file and return it's content (only it's name; do not use ' or ")
200 function LOAD_TEMPLATE($template, $return=false, $content="") {
201 // Add more variables which you want to use in your template files
202 global $DATA, $_CONFIG, $username;
204 // Make all template names lowercase
205 $template = strtolower($template);
207 // Count the template load
208 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
209 $_CONFIG['num_templates']++;
213 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
215 // @DEPRECATED Try to remove this if() block
216 if ($template == "member_support_form") {
217 // Support request of a member
218 $result = SQL_QUERY_ESC("SELECT gender, surname, family, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
219 array($GLOBALS['userid']), __FILE__, __LINE__);
221 // @TODO Merge this data into $content
222 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
225 $gender = TRANSLATE_GENDER($gender);
227 // Insert data if content is an array
228 if (is_array($content)) {
229 // Please switch to $content[bla] in all your templates! Direct
230 // variables are deprecated as of 09/13/2008.
231 $content['gender'] = $gender;
232 $content['surname'] = $surname;
233 $content['family'] = $family;
234 $content['email'] = $email;
238 SQL_FREERESULT($result);
241 // Generate date/time string
242 $date_time = MAKE_DATETIME(time(), "1");
245 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
248 // Check for admin/guest/member templates
249 if (strpos($template, "admin_") > -1) {
250 // Admin template found
252 } elseif (strpos($template, "guest_") > -1) {
253 // Guest template found
255 } elseif (strpos($template, "member_") > -1) {
256 // Member template found
258 } elseif (strpos($template, "install_") > -1) {
259 // Installation template found
261 } elseif (strpos($template, "ext_") > -1) {
262 // Extension template found
264 } elseif (strpos($template, "la_") > -1) {
265 // "Logical-area" template found
268 // Test for extension
269 $test = substr($template, 0, strpos($template, "_"));
270 if (EXT_IS_ACTIVE($test)) {
271 // Set extra path to extension's name
276 ////////////////////////
277 // Generate file name //
278 ////////////////////////
279 $file = $BASE.$MODE.$template.".tpl";
281 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
282 // Select what depended header/footer template file for admin/guest/member area
283 $file2 = sprintf("%s%s%s_%s.tpl",
287 SQL_ESCAPE($GLOBALS['what'])
291 if (FILE_READABLE($file2)) $file = $file2;
293 // Remove variable from memory
297 // Does the special template exists?
298 if (!FILE_READABLE($file)) {
299 // Reset to default template
300 $file = $BASE.$template.".tpl";
303 // Now does the final template exists?
304 if (FILE_READABLE($file)) {
305 // The local file does exists so we load it. :)
306 $tmpl_file = implode("", file($file));
308 // Replace ' to our own chars to preventing them being quoted
309 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
311 // Do we have to compile the code?
313 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
315 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
318 // Simply return loaded code
322 // Add surrounding HTML comments to help finding bugs faster
323 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
324 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!defined('mxchange_installed')))) {
325 // Only admins shall see this warning or when installation mode is active
326 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
327 (".basename($file).")<br />
330 <PRE>".print_r($content, true)."</PRE>
332 <PRE>".print_r($DATA, true)."</PRE>
336 // Do we have some content to output or return?
338 // Not empty so let's put it out! ;)
340 // Return the HTML code
346 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
347 // Warning, empty output!
348 return "E:".$template."<br />\n";
352 // Send mail out to an email address
353 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = 'N', $FROM = "") {
354 // Compile subject line (for POINTS constant etc.)
355 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
359 if ((!eregi("@", $TO)) && ($TO > 0)) {
360 // Value detected, load email from database
361 if (EXT_IS_ACTIVE("msg")) {
362 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
365 // Load email address
366 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
368 // Does the user exist?
369 if (SQL_NUMROWS($result_email)) {
370 // Load email address
371 list($TO) = SQL_FETCHROW($result_email);
378 SQL_FREERESULT($result_email);
380 } elseif ("$TO" == "0") {
385 // Check for PHPMailer or debug-mode
386 if (!CHECK_PHPMAILER_USAGE()) {
387 // Not in PHPMailer-Mode
389 // Load email header template
390 $FROM = LOAD_EMAIL_TEMPLATE("header");
393 $FROM .= LOAD_EMAIL_TEMPLATE("header");
395 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
397 // Load email header template
398 $FROM = LOAD_EMAIL_TEMPLATE("header");
401 $FROM .= LOAD_EMAIL_TEMPLATE("header");
406 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
409 // Fix HTML parameter (default is no!)
410 if (empty($HTML)) $HTML = "N";
411 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
412 // In debug mode we want to display the mail instead of sending it away so we can debug this part
414 ".htmlentities(trim($FROM))."
416 Subject : ".$SUBJECT."
419 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail", true))) {
420 // Send mail as HTML away
421 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
422 } elseif (!empty($TO)) {
424 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
425 } elseif ($HTML == "N") {
427 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
431 // Check if legacy or PHPMailer command
433 function CHECK_PHPMAILER_USAGE() {
434 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
438 * Send out a raw email with PHPMailer class or legacy mail() command
440 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
441 // Shall we use PHPMailer class or legacy mode?
442 if (CHECK_PHPMAILER_USAGE()) {
443 // Use PHPMailer class with SMTP enabled
444 require_once(PATH."inc/phpmailer/class.phpmailer.php");
445 require_once(PATH."inc/phpmailer/class.smtp.php");
448 $mail = new PHPMailer();
449 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
452 $mail->SMTPAuth = true;
453 $mail->Host = SMTP_HOSTNAME;
455 $mail->Username = SMTP_USER;
456 $mail->Password = SMTP_PASSWORD;
458 $mail->From = WEBMASTER;
462 $mail->FromName = MAIN_TITLE;
463 $mail->Subject = $subject;
464 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
466 $mail->AltBody = "Your mail program required HTML support to read this mail!";
467 $mail->WordWrap = 70;
472 $mail->AddAddress($to, "");
473 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
474 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
475 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
478 // Use legacy mail() command
479 @mail($to, $subject, $msg, $from);
484 // Generate a password in a specified length or use default password length
485 function GEN_PASS($LEN = 0) {
487 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
489 // Initialize array with all allowed chars
490 $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,-,+,_,/");
492 // Initialize randomizer
493 mt_srand((double) microtime() * 1000000);
495 // Start creating password
497 for ($i = 0; $i < $LEN; $i++) {
498 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
501 // When the size is below 40 we can also add additional security by scrambling it
502 if (strlen($PASS) <= 40) {
503 // Also scramble the password
504 $PASS = scrambleString($PASS);
507 // Return the password
511 function MAKE_DATETIME ($time, $mode="0")
515 return NEVER_HAPPENED;
517 // Filter out numbers
518 $time = bigintval($time);
521 switch (GET_LANGUAGE())
523 case "de": // German date / time format
525 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
526 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
527 case "2": $ret = date("d.m.Y|H:i", $time); break;
528 case "3": $ret = date("d.m.Y", $time); break;
532 default: // Default is the US date / time format!
534 case "0": $ret = date("r", $time); break;
535 case "1": $ret = date("Y-m-d - g:i A", $time); break;
536 case "2": $ret = date("y-m-d|H:i", $time); break;
537 case "3": $ret = date("y-m-d", $time); break;
543 // Translates the american decimal dot into a german comma
544 function TRANSLATE_COMMA ($dotted, $cut=true) {
547 // Default is 3 you can change this in admin area "Misc -> Misc Options"
548 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
549 $maxComma = $_CONFIG['max_comma'];
553 // Test for commata if in cut-mode
554 $com = explode(".", $dotted);
555 if (count($com) > 1) {
556 // Commata found, so only zeros?
557 if ($com[1] == str_repeat("0", strlen($com[1]))) {
558 // Only zeros, so don't display them
562 // Don't display commatas even if there are none... ;-)
568 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
571 switch (GET_LANGUAGE()) {
573 $dotted = number_format($dotted, $maxComma, ",", ".");
577 $dotted = number_format($dotted, $maxComma, ".", ",");
581 // Return translated value
586 function DEREFERER ($URL) {
587 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
592 function TRANSLATE_GENDER ($gender) {
595 case "M": $ret = GENDER_M; break;
596 case "F": $ret = GENDER_F; break;
597 case "C": $ret = GENDER_C; break;
598 default : $ret = $gender; break;
603 function GET_POOL_TYPE($PT) {
604 // Unknown pool type is default
605 $ret = POOL_UNKNOWN." (".$PT.")";
607 // Generate constant name
608 $constantName = sprintf("POOL_%s", $PT);
610 // Is the type known?
611 if (defined($constantName)) {
612 // Prepare eval command
613 $eval = sprintf("\$ret = %s;", $constantName);
621 function FRAMETESTER($URL) {
622 // Prepare frametester URL
623 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
625 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
627 return $frametesterUrl;
630 function SELECTION_COUNT($array) {
632 if (is_array($array)) {
633 foreach ($array as $key => $sel) {
634 if (!empty($sel)) $ret++;
640 function IMG_CODE ($code, $type, $DATA, $uid) {
641 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
644 function TRANSLATE_STATUS($status) {
648 $ret = ACCOUNT_UNCONFIRMED;
652 $ret = ACCOUNT_CONFIRMED;
656 $ret = ACCOUNT_LOCKED;
660 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
666 function GET_LANGUAGE() {
667 if (!empty($_GET['mx_lang'])) {
668 // Accept only first 2 chars
669 $lang = substr($_GET['mx_lang'], 0, 2);
675 // Set default return value to default language from config
678 // Check GET variable and cookie
680 // Check if main language file does exist
681 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
682 // Okay found, so let's update cookies
685 } elseif (!isSessionVariableSet('mx_lang')) {
686 // Return stored value from cookie
687 $ret = get_session('mx_lang');
689 // Fixes a warning before the session has the mx_lang constant
690 if (empty($ret)) $ret = DEFAULT_LANG;
695 function SET_LANGUAGE($lang) {
698 // Accept only first 2 chars!
699 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
702 set_session("mx_lang", $lang);
705 function LOAD_EMAIL_TEMPLATE($template, $content="", $UID="0") {
706 global $DATA, $_CONFIG, $REPLACER;
708 // Make sure all template names are lowercase!
709 $template = strtolower($template);
711 // Default "nickname" if extension is not installed
714 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
715 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
717 // Init variables (DEPRECATED! Use $content[bla] instead.
723 // Prepare IP number and User Agent
724 $REMOTE_ADDR = getenv('REMOTE_ADDR');
725 $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
728 if (isSessionVariableSet('admin_login')) {
730 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
731 array(get_session('admin_login')), __FILE__, __LINE__);
732 list($ADMIN) = SQL_FETCHROW($result);
733 SQL_FREERESULT($result);
736 // Expiration in a nice output format
737 if ($_CONFIG['auto_purge'] == 0) {
738 // Will never expire!
739 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
740 } elseif (function_exists('CREATE_FANCY_TIME')) {
741 // Create nice date string
742 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
745 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
748 // Is content an array?
749 if (is_array($content)) {
750 // Add expiration to array, $EXPIRATION is now deprecated!
751 $content['expiration'] = $EXPIRATION;
756 if (EXT_IS_ACTIVE("nickname")) {
758 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
759 array(bigintval($UID)), __FILE__, __LINE__);
760 list($surname, $family, $gender, $email, $nick) = SQL_FETCHROW($result);
761 SQL_FREERESULT($result);
764 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
765 array(bigintval($UID)), __FILE__, __LINE__);
766 list($surname, $family, $gender, $email) = SQL_FETCHROW($result);
767 SQL_FREERESULT($result);
770 // Neutral gender and email address is default
775 // Translate M to male or F to female
776 $gender = TRANSLATE_GENDER($gender);
778 // Insert data if content is an array
779 if (is_array($content)) {
780 // Please do no longer use direct variable names, use $content[bla]
782 $content['gender'] = $gender;
783 $content['surname'] = $surname;
784 $content['family'] = $family;
785 $content['email'] = $email;
786 $content['nick'] = $nick;
789 // Store email for some functions in global data array
790 $DATA['email'] = $email;
793 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
795 // Check for admin/guest/member templates
796 if (strpos($template, "admin_") > -1) {
797 // Admin template found
798 $file = $BASE."admin/".$template.".tpl";
799 } elseif (strpos($template, "guest_") > -1) {
800 // Guest template found
801 $file = $BASE."guest/".$template.".tpl";
802 } elseif (strpos($template, "member_") > -1) {
803 // Member template found
804 $file = $BASE."member/".$template.".tpl";
806 // Test for extension
807 $test = substr($template, 0, strpos($template, "_"));
808 if (EXT_IS_ACTIVE($test)) {
809 // Set extra path to extension's name
810 $file = $BASE.$test."/".$template.".tpl";
812 // No special filename
813 $file = $BASE.$template.".tpl";
817 // Does the special template exists?
818 if (!FILE_READABLE($file)) {
819 // Reset to default template
820 $file = $BASE.$template.".tpl";
823 // Now does the final template exists?
825 if (FILE_READABLE($file)) {
826 // The local file does exists so we load it. :)
827 $tmpl_file = @implode("", @file($file));
828 $tmpl_file = addslashes($tmpl_file);
831 $tmpl_file = "\$newContent=\"".COMPILE_CODE($tmpl_file)."\";";
834 // Replace HTML conform chars
835 $newContent = html_entity_decode($newContent);
836 } elseif (!empty($template)) {
837 // Template file not found!
838 $newContent = TEMPLATE_404.": ".$template."<br />
840 <PRE>".print_r($newContent, true)."</PRE>
842 <PRE>".print_r($DATA, true)."</PRE>
845 // Debug mode not active? Then remove the HTML tags
846 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
848 // No template name supplied!
849 $newContent = NO_TEMPLATE_SUPPLIED;
852 // Is there some content?
853 if (empty($newContent)) {
855 $newContent = "Compiler error for template {$template}!";
858 // Return compiled content
859 return COMPILE_CODE($newContent);
862 function MAKE_TIME($H, $M, $S, $stamp) {
863 // Extract day, month and year from given timestamp
864 $DAY = date("d", $stamp);
865 $MONTH = date("m", $stamp);
866 $YEAR = date('Y', $stamp);
868 // Create timestamp for wished time which depends on extracted date
869 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
872 function LOAD_URL($URL, $addUrlData=true) {
873 global $CSS, $_CONFIG, $footer;
875 // Check if http(s):// is there
876 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
877 // Make all URLs full-qualified
881 // Compile out URI codes
882 $URL = COMPILE_CODE($URL);
885 $OUTPUT = ob_get_contents();
890 // Add some data to URL if cookies are not accepted
891 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
893 // Probe for bot from search engine
894 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
895 // Search engine bot detected so let's rewrite many chars for the link
896 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
898 // Output new location link as anchor
899 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
900 } elseif (!headers_sent()) {
901 // Load URL when headers are not sent
904 debug_print_backtrace();
905 die("</pre>URL={$URL}");
907 @header ("Location: ".str_replace("&", "&", $URL));
909 // Output error message
910 include(PATH."inc/header.php");
911 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
912 include(PATH."inc/footer.php");
917 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
918 global $SEC_CHARS, $URL_CHARS;
921 // Select smaller set of chars to replace when we e.g. want to compile URLs
922 if (!$full) $ARRAY = $URL_CHARS;
926 // BEFORE 0.2.1 : Language and data constants
927 // WITH 0.2.1+ : Only language constants
928 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
930 // BEFORE 0.2.1 : Not used
931 // WITH 0.2.1+ : Data constants
932 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
935 // Compile QUOT and other non-HTML codes
936 foreach ($ARRAY['to'] as $k => $to) {
937 // Do the reversed thing as in inc/libs/security_functions.php
938 $code = str_replace($to, $ARRAY['from'][$k], $code);
941 // But shall I keep simple quotes for later use?
942 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
944 // Find $content[bla][blub] entries
945 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
947 // Are some matches found?
948 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
949 // Replace all matches
950 $matchesFound = array();
951 foreach ($matches[0] as $key => $match) {
952 // Avoid replacing matches multiple times
953 if (!isset($matchesFound[$match])) {
955 $code = str_replace($match, "\".".$match.".\"", $code);
956 $matchesFound[$match] = 1;
959 // Take all string elements
960 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
961 // Replace it in the code
962 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
963 $code = str_replace($match, $newMatch, $code);
964 $matchesFound[$key."_".$matches[4][$key]] = 1;
969 // Return compiled code
973 /************************************************************************
975 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
976 * $a_sort sortiert: *
978 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
979 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
980 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
981 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
982 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
984 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
985 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
986 * Sie, dass es doch nicht so schwer ist! :-) *
988 ************************************************************************/
989 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
992 while ($primary_key < count($a_sort)) {
993 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
994 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
997 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
998 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
999 } elseif ($key != $key2) {
1000 // Sort numbers (E.g.: 9 < 10)
1001 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1002 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1006 // We have found two different values, so let's sort whole array
1007 foreach ($dummy as $sort_key => $sort_val) {
1008 $t = $dummy[$sort_key][$key];
1009 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1010 $dummy[$sort_key][$key2] = $t;
1021 // Write back sorted array
1025 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1027 global $MONTH_DESCR; $OUT = "";
1030 // This is a yes/no selection only!
1031 if ($id > 0) $prefix .= "[".$id."]";
1032 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1036 // Begin with regular selection box here
1037 if (!empty($prefix)) $prefix .= "_";
1039 if ($id > 0) $type2 .= "[".$id."]";
1040 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1045 for ($idx = 1; $idx < 32; $idx++)
1047 $OUT .= "<OPTION value=\"".$idx."\"";
1048 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1049 $OUT .= ">".$idx."</OPTION>\n";
1053 case "month": // Month
1054 foreach ($MONTH_DESCR as $month => $descr)
1056 $OUT .= "<OPTION value=\"".$month."\"";
1057 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1058 $OUT .= ">".$descr."</OPTION>\n";
1062 case "year": // Year
1064 $YEAR = date('Y', time());
1066 // Check if the default value is larger than minimum and bigger than actual year
1067 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1069 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1071 $OUT .= "<OPTION value=\"".$idx."\"";
1072 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1073 $OUT .= ">".$idx."</OPTION>\n";
1076 elseif ($DEFAULT == -1)
1078 // Current year minus 1
1079 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1081 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1086 // Get current year and subtract 16 (for erotic content)
1087 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1088 $YEAR = date('Y', time()) - 16;
1089 for ($idx = 1930; $idx <= $YEAR; $idx++)
1091 $OUT .= "<OPTION value=\"".$idx."\"";
1092 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1093 $OUT .= ">".$idx."</OPTION>\n";
1100 for ($idx = 0; $idx < 60; $idx+=5) {
1101 if (strlen($idx) == 1) $idx = "0".$idx;
1102 $OUT .= "<OPTION value=\"".$idx."\"";
1103 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1104 $OUT .= ">".$idx."</OPTION>\n";
1109 for ($idx = 0; $idx < 24; $idx++) {
1110 if (strlen($idx) == 1) $idx = "0".$idx;
1111 $OUT .= "<OPTION value=\"".$idx."\"";
1112 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1113 $OUT .= ">".$idx."</OPTION>\n";
1118 $OUT .= "<OPTION value=\"Y\"";
1119 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1120 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1121 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1122 $OUT .= ">".NO."</OPTION>\n";
1125 $OUT .= " </SELECT>\n";
1129 function TRANSLATE_YESNO($yn)
1133 case 'Y': $yn = YES; break;
1134 case 'N': $yn = NO; break;
1135 default : $yn = "??? (".$yn.")"; break;
1140 // Deprecated : $length
1143 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1146 // Fix missing _MAX constant
1147 if (!defined('_MAX')) define('_MAX', 15235);
1149 // Build server string
1150 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1153 $keys = SITE_KEY.":".DATE_KEY;
1154 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1155 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1156 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1157 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1159 // Build string from misc data
1160 $data = $code.":".$uid.":".$DATA;
1162 // Add more additional data
1163 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1164 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1165 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1166 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1167 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1168 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1170 // Calculate number for generating the code
1171 $a = $code + _ADD - 1;
1173 if (isset($_CONFIG['master_hash'])) {
1174 // Generate hash with master salt from modula of number with the prime number and other data
1175 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1177 // Create number from hash
1178 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1180 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1181 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1183 // Create number from hash
1184 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1187 // At least 10 numbers shall be secure enought!
1188 $len = $_CONFIG['code_length'];
1189 if ($len == 0) $len = $length;
1190 if ($len == 0) $len = 10;
1192 // Cut off requested counts of number
1193 $return = substr(str_replace('.', "", $rcode), 0, $len);
1195 // Done building code
1198 // Does only allow numbers
1199 function bigintval($num, $castValue = true) {
1200 // Filter all numbers out
1201 $ret = preg_replace("/[^0123456789]/", "", $num);
1204 if ($castValue) $ret = (double)$ret;
1206 // Has the whole value changed?
1207 if ("".$ret."" != "".$num."") {
1209 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1215 // Insert the code in $img_code into jpeg or PNG image
1216 function GENERATE_IMAGE($img_code, $header=true) {
1219 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1220 // Stop execution of function here because of over-sized code length
1222 } elseif (!$header) {
1223 // Return in an HTML code code
1224 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1228 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1229 if (FILE_READABLE($img)) {
1230 // Switch image type
1231 switch ($_CONFIG['img_type'])
1234 // Okay, load image and hide all errors
1235 $image = @imagecreatefromjpeg($img);
1239 // Okay, load image and hide all errors
1240 $image = @imagecreatefrompng($img);
1244 // Exit function here
1248 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1249 $text_color = imagecolorallocate($image, 0, 0, 0);
1251 // Insert code into image
1252 imagestring($image, 5, 14, 2, $img_code, $text_color);
1254 // Return to browser
1255 header ("Content-Type: image/".$_CONFIG['img_type']);
1257 // Output image with matching image factory
1258 switch ($_CONFIG['img_type']) {
1259 case "jpg": imagejpeg($image); break;
1260 case "png": imagepng($image); break;
1263 // Remove image from memory
1264 imagedestroy($image);
1266 // Create selection box or array of splitted timestamp
1267 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1268 // Calculate 2-seconds timestamp
1269 $stamp = round($timestamp / 2) * 2;
1271 // Do we have a leap year?
1273 $TEST = date('Y', time()) / 4;
1274 $M1 = date("m", time());
1275 $M2 = date("m", (time() + $stamp));
1277 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1278 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1280 // First of all years...
1281 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1283 $M = abs(floor($stamp / 2628000 - $Y * 12));
1285 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1287 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1289 $h = abs(floor($stamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1291 $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));
1292 // And at last seconds...
1293 $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));
1295 // Is seconds zero and time is < 60 seconds?
1296 if (($s == 0) && ($stamp < 60)) {
1298 $s = round($timestamp);
1302 // Now we convert them in seconds...
1304 if ($return_array) {
1305 // Just put all data in an array for later use
1317 $OUT = "<DIV align=\"".$align."\">\n";
1318 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1321 if (ereg('Y', $display) || (empty($display))) {
1322 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1325 if (ereg("M", $display) || (empty($display))) {
1326 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1329 if (ereg("W", $display) || (empty($display))) {
1330 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1333 if (ereg("D", $display) || (empty($display))) {
1334 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1337 if (ereg("h", $display) || (empty($display))) {
1338 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1341 if (ereg("m", $display) || (empty($display))) {
1342 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1345 if (ereg("s", $display) || (empty($display))) {
1346 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1352 if (ereg('Y', $display) || (empty($display))) {
1353 // Generate year selection
1354 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1355 for ($idx = 0; $idx <= 10; $idx++) {
1356 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1357 if ($idx == $Y) $OUT .= " selected default";
1358 $OUT .= ">".$idx."</OPTION>\n";
1360 $OUT .= " </SELECT></TD>\n";
1362 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1365 if (ereg("M", $display) || (empty($display))) {
1366 // Generate month selection
1367 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1368 for ($idx = 0; $idx <= 11; $idx++)
1370 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1371 if ($idx == $M) $OUT .= " selected default";
1372 $OUT .= ">".$idx."</OPTION>\n";
1374 $OUT .= " </SELECT></TD>\n";
1376 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1379 if (ereg("W", $display) || (empty($display))) {
1380 // Generate week selection
1381 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1382 for ($idx = 0; $idx <= 4; $idx++) {
1383 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1384 if ($idx == $W) $OUT .= " selected default";
1385 $OUT .= ">".$idx."</OPTION>\n";
1387 $OUT .= " </SELECT></TD>\n";
1389 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1392 if (ereg("D", $display) || (empty($display))) {
1393 // Generate day selection
1394 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1395 for ($idx = 0; $idx <= 31; $idx++) {
1396 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1397 if ($idx == $D) $OUT .= " selected default";
1398 $OUT .= ">".$idx."</OPTION>\n";
1400 $OUT .= " </SELECT></TD>\n";
1402 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1405 if (ereg("h", $display) || (empty($display))) {
1406 // Generate hour selection
1407 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1408 for ($idx = 0; $idx <= 23; $idx++) {
1409 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1410 if ($idx == $h) $OUT .= " selected default";
1411 $OUT .= ">".$idx."</OPTION>\n";
1413 $OUT .= " </SELECT></TD>\n";
1415 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1418 if (ereg("m", $display) || (empty($display))) {
1419 // Generate minute selection
1420 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1421 for ($idx = 0; $idx <= 59; $idx++) {
1422 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1423 if ($idx == $m) $OUT .= " selected default";
1424 $OUT .= ">".$idx."</OPTION>\n";
1426 $OUT .= " </SELECT></TD>\n";
1428 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1431 if (ereg("s", $display) || (empty($display))) {
1432 // Generate second selection
1433 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1434 for ($idx = 0; $idx <= 45; $idx += 15) {
1435 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1436 if ($idx == $s) $OUT .= " selected default";
1437 $OUT .= ">".$idx."</OPTION>\n";
1439 $OUT .= " </SELECT></TD>\n";
1441 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1444 $OUT .= "</TABLE>\n";
1446 // Return generated HTML code
1451 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1454 // Do we have a leap year?
1456 $TEST = date('Y', time()) / 4;
1457 $M1 = date("m", time());
1458 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1459 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1460 // First add years...
1461 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1463 $ret += $POST[$prefix."_mo"] * 2628000;
1465 $ret += $POST[$prefix."_we"] * 604800;
1467 $ret += $POST[$prefix."_da"] * 86400;
1469 $ret += $POST[$prefix."_ho"] * 3600;
1471 $ret += $POST[$prefix."_mi"] * 60;
1472 // And at last seconds...
1473 $ret += $POST[$prefix."_se"];
1474 // Return calculated value
1477 // Sends out mail to all administrators
1478 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1479 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1480 // Trim template name
1481 $template = trim($template);
1483 // Load email template
1484 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1486 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1487 // Older version detected!
1488 return SEND_ADMIN_EMAILS($subj, $msg);
1491 // Check which admin shall receive this mail
1492 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1493 array($template), __FILE__, __LINE__);
1494 if (SQL_NUMROWS($result) == 0) {
1495 // Create new entry (to all admins)
1496 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1497 array($template), __FILE__, __LINE__);
1499 // Load admin IDs...
1501 while(list($aid) = SQL_FETCHROW($result)) {
1506 SQL_FREERESULT($result);
1508 // "implode" IDs and query string
1509 $aid = implode(",", $aids);
1511 // Add line to userlog
1512 USERLOG_ADD_LINE($subj, $msg, $UID);
1514 } elseif ($aid == "0") {
1515 // Select all email adresses
1516 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1518 // If Admin-ID is not "to-all" select
1519 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1523 // Load email addresses and send away
1524 while (list($email) = SQL_FETCHROW($result)) {
1525 SEND_EMAIL($email, $subj, $msg);
1529 SQL_FREERESULT($result);
1532 function CREATE_FANCY_TIME($stamp) {
1533 // Get data array with years/months/weeks/days/...
1534 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1536 foreach($data as $k => $v) {
1538 // Value is greater than 0 "eval" data to return string
1539 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1545 // Do we have something there?
1546 if (strlen($ret) > 0) {
1547 // Remove leading commata and space
1548 $ret = substr($ret, 2);
1551 $ret = "0 "._SECONDS;
1554 // Return fancy time string
1558 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1559 $SEP = ""; $TOP = "";
1562 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1566 for ($page = 1; $page <= $PAGES; $page++) {
1567 // Is the page currently selected or shall we generate a link to it?
1568 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1569 // Is currently selected, so only highlight it
1570 $NAV .= "<STRONG>-";
1572 // Open anchor tag and add base URL
1573 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1575 // Add userid when we shall show all mails from a single member
1576 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1578 // Close open anchor tag
1582 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1583 // Is currently selected, so only highlight it
1584 $NAV .= "-</STRONG>";
1590 // Add seperator if we have not yet reached total pages
1591 if ($page < $PAGES) $NAV .= " | ";
1594 // Define constants only once
1595 if (!defined('__NAV_OUTPUT')) {
1596 define('__NAV_OUTPUT' , $NAV);
1597 define('__NAV_COLSPAN', $colspan);
1598 define('__NAV_TOP' , $TOP);
1599 define('__NAV_SEP' , $SEP);
1602 // Load navigation template
1603 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1606 // Return generated HTML-Code
1614 // Extract host from script name
1615 function EXTRACT_HOST (&$script) {
1616 // Use default SERVER_URL by default... ;) So?
1619 // Is this URL valid?
1620 if (substr($script, 0, 7) == "http://") {
1621 // Use the hostname from script URL as new hostname
1622 $url = substr($script, 7);
1623 $extract = explode("/", $url);
1625 // Done extracting the URL :)
1628 // Extract host name
1629 $host = str_replace("http://", "", $url);
1630 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1632 // Generate relative URL
1633 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1634 if (substr(strtolower($script), 0, 7) == "http://") {
1635 // But only if http:// is in front!
1636 $script = substr($script, (strlen($url) + 7));
1637 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1639 $script = substr($script, (strlen($url) + 8));
1642 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1643 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1649 // Send a GET request
1650 function GET_URL ($script) {
1651 // Compile the script name
1652 $script = COMPILE_CODE($script);
1654 // Extract host name from script
1655 $host = EXTRACT_HOST($script);
1657 // Generate GET request header
1658 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1659 $request .= "Host: " . $host . "\r\n";
1660 $request .= "Referer: " . URL . "/admin.php\r\n";
1661 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1662 $request .= "Content-Type: text/plain\r\n";
1663 $request .= "Cache-Control: no-cache\r\n";
1664 $request .= "Connection: Close\r\n\r\n";
1666 // Send the raw request
1667 $response = SEND_RAW_REQUEST($host, $request);
1669 // Return the result to the caller function
1673 // Send a POST request
1674 function POST_URL ($script, $postData) {
1675 // Is postData an array?
1676 if (!is_array($postData)) {
1678 return array("", "", "");
1681 // Compile the script name
1682 $script = COMPILE_CODE($script);
1684 // Extract host name from script
1685 $host = EXTRACT_HOST($script);
1687 // Construct request
1688 $data = http_build_query($postData, '', '&');
1690 // Generate POST request header
1691 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1692 $request .= "Host: " . $host . "\r\n";
1693 $request .= "Referer: " . URL . "/admin.php\r\n";
1694 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1695 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1696 $request .= "Content-length: " . strlen($data) . "\r\n";
1697 $request .= "Cache-Control: no-cache\r\n";
1698 $request .= "Connection: Close\r\n\r\n";
1701 // Send the raw request
1702 $response = SEND_RAW_REQUEST($host, $request);
1704 // Return the result to the caller function
1708 // Sends a raw request to another host
1709 function SEND_RAW_REQUEST ($host, $request) {
1713 $response = array("", "", "");
1715 // Default is not to use proxy
1718 // Are proxy settins set?
1719 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1725 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1727 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1729 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1733 if (!is_resource($fp)) {
1740 // Generate CONNECT request header
1741 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1742 $proxyTunnel .= "Host: ".$host."\r\n";
1744 // Use login data to proxy? (username at least!)
1745 if (!empty($_CONFIG['proxy_username'])) {
1747 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1748 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1751 // Add last new-line
1752 $proxyTunnel .= "\r\n";
1753 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1756 fputs($fp, $proxyTunnel);
1760 // No response received
1764 // Read the first line
1765 $resp = trim(fgets($fp, 10240));
1766 $respArray = explode(" ", $resp);
1767 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1768 // Invalid response!
1774 fputs($fp, $request);
1778 $response[] = trim(fgets($fp, 1024));
1784 // Skip first empty lines
1786 foreach ($resp as $idx => $line) {
1788 $line = trim($line);
1790 // Is this line empty?
1793 array_shift($response);
1795 // Abort on first non-empty line
1800 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1802 // Proxy agent found?
1803 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1804 // Proxy header detected, so remove two lines
1805 array_shift($response);
1806 array_shift($response);
1809 // Was the request successfull?
1810 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1811 // Not found / access forbidden
1812 $response = array("", "", "");
1818 // Taken from www.php.net eregi() user comments
1819 function VALIDATE_EMAIL($email) {
1821 $email = COMPILE_CODE($email);
1823 // Check first part of email address
1824 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1827 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1830 $regex = "^".$first."@".$domain."$";
1832 // Return check result
1833 return eregi($regex, $email);
1835 // Function taken from user comments on www.php.net / function eregi()
1836 function VALIDATE_URL ($URL, $compile=true) {
1837 // Trim URL a little
1838 $URL = trim(urldecode($URL));
1839 //* DEBUG: */ echo $URL."<br />";
1841 // Compile some chars out...
1842 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1843 //* DEBUG: */ echo $URL."<br />";
1845 // Check for the extension filter
1846 if (EXT_IS_ACTIVE("filter")) {
1847 // Use the extension's filter set
1848 return FILTER_VALIDATE_URL($URL, false);
1851 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1852 // https:// in front of the URLs
1853 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1856 function MEMBER_ACTION_LINKS($uid, $status="") {
1857 // Define all main targets
1858 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1860 // Begin of navigation links
1861 $eval = "\$OUT = \"[ ";
1863 foreach ($TARGETS as $tar) {
1864 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1865 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1866 if (($tar == "lock_user") && ($status == "LOCKED")) {
1867 // Locked accounts shall be unlocked
1868 $eval .= "UNLOCK_USER";
1870 // All other status is fine
1871 $eval .= strtoupper($tar);
1873 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1874 if (($tar == "lock_user") && ($status == "LOCKED")) {
1875 // Locked accounts shall be unlocked
1876 $eval .= "UNLOCK_USER";
1878 // All other status is fine
1879 $eval .= strtoupper($tar);
1881 $eval .= ".\"</A></SPAN> | ";
1884 // Finish navigation link
1885 $eval = substr($eval, 0, -7)."]\";";
1891 // Function for backward-compatiblity
1892 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1893 // Load it from the register extension
1894 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1896 // Generate an email link
1897 function CREATE_EMAIL_LINK($email, $table="admins") {
1898 // Default email link (INSECURE! Spammer can read this by harvester programs)
1899 $EMAIL = "mailto:".$email;
1901 // Check for several extensions
1902 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1903 // Create email link for contacting admin in guest area
1904 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1905 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1906 // Create email link for contacting a member within admin area (or later in other areas, too?)
1907 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1908 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1909 // Create email link to contact sponsor within admin area (or like the link above?)
1910 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1913 // Shall I close the link when there is no admin?
1914 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1916 // Return email link
1919 // Generate a hash for extra-security for all passwords
1920 function generateHash ($plainText, $salt = "") {
1921 global $_CONFIG, $_SERVER;
1923 // Is the required extension "sql_patches" there and a salt is not given?
1924 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == "")) && (empty($salt))) {
1925 // Extension sql_patches is missing/outdated so we return the plain text
1929 // Do we miss an arry element here?
1930 if (!isset($_CONFIG['file_hash'])) {
1932 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1933 debug_print_backtrace();
1937 // When the salt is empty build a new one, else use the first x configured characters as the salt
1939 // Build server string
1940 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1943 $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'];
1946 $data = $plainText.":".uniqid(rand(), true).":".time();
1948 // Calculate number for generating the code
1949 $a = time() + _ADD - 1;
1951 // Generate SHA1 sum from modula of number and the prime number
1952 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1953 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
1954 $sha1 = scrambleString($sha1);
1955 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
1956 //* DEBUG: */ $sha1b = descrambleString($sha1);
1957 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
1959 // Generate the password salt string
1960 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1961 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1964 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1965 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
1969 return $salt.sha1($salt.$plainText);
1972 function scrambleString($str) {
1978 // Final check, in case of failture it will return unscrambled string
1979 if (strlen($str) > 40) {
1980 // The string is to long
1982 } elseif (strlen($str) == 40) {
1984 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1986 // Generate new numbers
1987 $scrambleNums = explode(":", genScrambleString(strlen($str)));
1990 // Scramble string here
1991 //* DEBUG: */ echo "***Original=".$str."***<br />";
1992 for ($idx = 0; $idx < strlen($str); $idx++) {
1993 // Get char on scrambled position
1994 $char = substr($str, $scrambleNums[$idx], 1);
1996 // Add it to final output string
1997 $scrambled .= $char;
2000 // Return scrambled string
2001 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2005 function descrambleString($str) {
2007 // Scramble only 40 chars long strings
2008 if (strlen($str) != 40) return $str;
2010 // Load numbers from config
2011 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2014 if (count($scrambleNums) != 40) return $str;
2016 // Begin descrambling
2017 $orig = str_repeat(" ", 40);
2018 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2019 for ($idx = 0; $idx < 40; $idx++) {
2020 $char = substr($str, $idx, 1);
2021 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2024 // Return scrambled string
2025 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2029 function genScrambleString($len) {
2030 // Prepare randomizer and array for the numbers
2031 mt_srand((double) microtime() * 1000000);
2032 $scrambleNumbers = array();
2034 // First we need to setup randomized numbers from 0 to 31
2035 for ($idx = 0; $idx < $len; $idx++) {
2037 $rand = mt_rand(0, ($len -1));
2039 // Check for it by creating more numbers
2040 while (array_key_exists($rand, $scrambleNumbers)) {
2041 $rand = mt_rand(0, ($len -1));
2045 $scrambleNumbers[$rand] = $rand;
2048 // So let's create the string for storing it in database
2049 $scrambleString = implode(":", $scrambleNumbers);
2050 return $scrambleString;
2052 // Append data like session ID referral ID to the given URL which would
2053 // normally be stored in cookies
2054 function ADD_URL_DATA($URL) {
2058 // Determine URL binder
2060 if (strpos($URL, "?") !== false) $BIND = "&";
2062 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2063 // Cookies are not accepted
2064 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2065 // Cookie found in URL
2066 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2067 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2068 // Not found! So let's set default here
2069 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2072 // Is there already added data? Then change the binder
2073 if (!empty($ADD)) $BIND = "&";
2076 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2077 // Add session from URL
2078 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2080 // Add current session
2081 $ADD .= $BIND."PHPSESSID=".session_id();
2085 // Add all together and return it
2088 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2089 function generatePassString($passHash) {
2092 // Return vanilla password hash
2095 // Is a secret key and master salt already initialized?
2096 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2097 // Only calculate when the secret key is generated
2098 $newHash = ""; $start = 9;
2099 for ($idx = 0; $idx < 10; $idx++) {
2100 $part1 = hexdec(substr($passHash, $start, 4));
2101 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2102 $mod = dechex($idx);
2103 if ($part1 > $part2) {
2104 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2105 } elseif ($part2 > $part1) {
2106 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2108 $mod = substr(round($mod), 0, 4);
2109 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2110 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2115 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2116 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2117 //* DEBUG: */ print($ret."<br />\n");
2120 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2121 $ret = md5($passHash);
2122 //* DEBUG: */ echo "++".$ret."++<br />\n";
2129 // Fix "deleted" cookies
2130 function FIX_DELETED_COOKIES ($cookies) {
2131 // Is this an array with entries?
2132 if ((is_array($cookies)) && (count($cookies) > 0)) {
2133 // Then check all cookies if they are marked as deleted!
2134 foreach ($cookies as $cookieName) {
2135 // Is the cookie set to "deleted"?
2136 if (get_session($cookieName) == "deleted") {
2137 set_session($cookieName, "");
2143 // Output error messages in a fasioned way and die...
2144 function mxchange_die ($msg) {
2147 // Load the message template
2148 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2151 include(PATH."inc/footer.php");
2157 // Display parsing time and number of SQL queries in footer
2158 function DISPLAY_PARSING_TIME_FOOTER() {
2159 global $startTime, $_CONFIG;
2160 $endTime = microtime(true);
2162 // Is the timer started?
2163 if (!isset($GLOBALS['startTime'])) {
2168 // "Explode" both times
2169 $start = explode(" ", $GLOBALS['startTime']);
2170 $end = explode(" ", $endTime);
2171 $runTime = $end[0] - $start[0];
2172 if ($runTime < 0) $runTime = 0;
2173 $runTime = TRANSLATE_COMMA($runTime);
2177 'runtime' => $runTime,
2178 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2179 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2182 // Load the template
2183 LOAD_TEMPLATE("show_timings", false, $content);
2186 // Unset/set session variables
2187 function set_session ($var, $value) {
2190 // Abort in CSS mode here
2191 if ($CSS == 1) return true;
2193 // Trim value and session variable
2194 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2196 // Is the session variable set?
2197 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2198 // Remove the session
2199 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2200 unset($_SESSION[$var]);
2201 return session_unregister($var);
2202 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2204 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2205 $_SESSION[$var] = $value;
2206 return session_register($var);
2207 } elseif (!empty($value)) {
2209 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2210 $_SESSION[$var] = $value;
2214 // Ignored (but valid)
2215 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2219 // Check wether a boolean constant is set
2220 // Taken from user comments in PHP documentation for function constant()
2221 function isBooleanConstantAndTrue($constName) { // : Boolean
2224 // Failed by default
2228 if (isset($constCache[$constName])) {
2230 //* DEBUG: */ echo __FUNCTION__.": ".$constName."-CACHE!<br />\n";
2231 $res = $constCache[$constName];
2234 //* DEBUG: */ echo __FUNCTION__.": ".$constName."-RESOLVE!<br />\n";
2235 if (defined($constName)) $res = (constant($constName) === true);
2238 $constCache[$constName] = $res;
2240 //* DEBUG: */ var_dump($res);
2246 // Check wether a session variable is set
2247 function isSessionVariableSet($var) {
2248 //* DEBUG: */ echo __FUNCTION__.":var={$var}<br />\n";
2249 return (isset($_SESSION[$var]));
2251 // Returns wether the value of the session variable or NULL if not set
2252 function get_session($var) {
2255 // Default is not found! ;-)
2258 // Is the variable there or cached values?
2259 if (isset($cacheArray['session'][$var])) {
2260 // Get cached value (skips a lot SQL_ESCAPE() calles!
2261 $value = $cacheArray['session'][$var];
2262 } elseif (isSessionVariableSet($var)) {
2263 // Then get it secured!
2264 $value = SQL_ESCAPE($_SESSION[$var]);
2267 $cacheArray['session'][$var] = $value;
2273 // Send notification to admin
2274 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content="", $uid="0") {
2275 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2277 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2279 // Send outdated way
2280 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2281 SEND_ADMIN_EMAILS($subject, $msg);
2284 // Destroy user session
2285 function destroy_user_session () {
2286 // Remove all user data from session
2287 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2289 // Merges an array together but only if both are arrays
2290 function merge_array ($array1, $array2) {
2291 // Are both an array?
2292 if ((is_array($array1)) && (is_array($array2))) {
2293 // Merge all together
2294 return array_merge($array1, $array2);
2295 } elseif (is_array($array1)) {
2296 // Return left array
2300 // Something wired happened here...
2301 print(__FUNCTION__.":<pre>");
2302 debug_print_backtrace();
2305 // Debug message logger
2306 function DEBUG_LOG ($message, $force=false) {
2307 // Is debug mode enabled?
2308 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2309 // Log this message away
2310 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2311 fwrite($fp, date("d.m.Y|H:i:s", time())."|{$message}\n");
2315 // Reads a directory with PHP files in and gets only files back
2316 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2320 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2323 while ($baseFile = readdir($dirPointer)) {
2324 // Load file only if extension is active
2326 $file = $baseDir.$baseFile;
2328 // Is this a valid reset file?
2329 //* DEBUG: */ echo __FUNCTION__.":baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2330 if ((is_file($file)) && (is_readable($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2331 // Remove both for extension name
2332 $extName = substr($baseFile, strlen($prefix), -4);
2335 $extId = GET_EXT_ID($extName);
2337 // Is the extension valid and active?
2338 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2339 // Then add this file
2341 } elseif ($extId == 0) {
2342 // Add non-extension files as well
2349 closedir($dirPointer);
2351 // Return array with include files
2354 // Load more reset scripts
2355 function RESET_ADD_INCLUDES () {
2358 // Is the reset set or old sql_patches?
2359 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2364 // Get more daily reset scripts
2365 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2367 // Create current week mark
2368 $currWeek = date("W", time());
2371 if ($_CONFIG['last_week'] != $currWeek) {
2372 // Include weekly reset scripts
2373 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2376 UPDATE_CONFIG("last_week", $currWeek);
2379 // Create current month mark
2380 $currMonth = date("m", time());
2383 if ($_CONFIG['last_month'] != $currMonth) {
2384 // Include monthly reset scripts
2385 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2388 UPDATE_CONFIG("last_month", $currMonth);
2394 // Handle extra values
2395 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2396 // Default is the value itself
2399 // Do we have a special filter function?
2400 if (!empty($filterFunction)) {
2401 // Does the filter function exist?
2402 if (function_exists($filterFunction)) {
2403 // Do we have extra parameters here?
2404 if (!empty($extraValue)) {
2405 // Put both parameters in one new array by default
2406 $args = array($value, $extraValue);
2408 // If we have an array simply use it and pre-extend it with our value
2409 if (is_array($extraValue)) {
2410 // Make the new args array
2411 $args = array_merge(array($value), $extraValue);
2414 // Call the multi-parameter call-back
2415 $ret = call_user_func_array($filterFunction, $args);
2417 // One parameter call
2418 $ret = call_user_func($filterFunction, $value);
2426 // Check if given FQFN is a readable file
2427 function FILE_READABLE($fqfn) {
2429 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2431 // Converts timestamp selections into a timestamp
2432 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2433 // Init test variable
2436 // Get last three chars
2437 $TEST = substr($id, -3);
2439 // Improved way of checking! :-)
2440 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2441 // Found a multi-selection for timings?
2442 $TEST = substr($id, 0, -3);
2443 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)) {
2444 // Generate timestamp
2445 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2446 $DATA[] = "$TEST='".$POST[$TEST]."'";
2448 // Remove data from array
2449 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2450 unset($POST[$TEST."_".$rem]);
2454 unset($id); $skip = true; $TEST2 = $TEST;
2457 // Process this entry
2458 $skip = false; $TEST2 = "";
2461 // Reverts the german decimal comma into Computer decimal dot
2462 function REVERT_COMMA ($str) {
2463 // Default float is not a float... ;-)
2466 // Which language is selected?
2467 switch (GET_LANGUAGE()) {
2468 case "de": // German language
2469 // Remove german thousand dots first
2470 $str = str_replace(".", "", $str);
2472 // Replace german commata with decimal dot and cast it
2473 $float = (float)str_replace(",", ".", $str);
2476 default: // US and so on
2477 // Remove thousand dots first and cast
2478 $float = (float)str_replace(",", "", $str);
2485 // Handle menu-depending failed logins and return the rendered content
2486 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2487 // Default output is empty ;-)
2490 // Is the session data set?
2491 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2492 // Ignore zero values
2493 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2494 // Non-guest has login failtures found, get both data and prepare it for template
2495 //* DEBUG: */ echo __FUNCTION__.":accessLevel={$accessLevel}<br />\n";
2497 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2498 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2502 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2505 // Reset session data
2506 set_session('mxchange_'.$accessLevel.'_failtures', "");
2507 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2510 // Return rendered content
2514 function REBUILD_CACHE ($cache, $inc="") {
2515 global $cacheInstance;
2517 // Shall I remove the cache file?
2518 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2520 if ($cacheInstance->cache_file($cache, true)) {
2522 $cacheInstance->cache_destroy();
2524 // Include file given?
2526 // And rebuild it from scratch
2527 require_once(PATH."inc/loader/load_cache-".$inc.".php");
2532 // Purge admin menu cache
2533 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2534 global $_CONFIG, $cacheInstance;
2536 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2537 if (!EXT_IS_ACTIVE("cache")) {
2538 // Cache extension not active
2540 } elseif (!is_object($cacheInstance)) {
2541 // No cache instance!
2542 DEBUG_LOG(__FUNCTION__.": No cache instance found.");
2544 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2545 // Caching disabled (currently experiemental!)
2549 // Experiemental feature!
2550 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2553 //////////////////////////////////////////////////
2555 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2557 //////////////////////////////////////////////////
2559 if (!function_exists('html_entity_decode')) {
2560 // Taken from documentation on www.php.net
2561 function html_entity_decode($string) {
2562 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2563 $trans_tbl = array_flip($trans_tbl);
2564 return strtr($string, $trans_tbl);