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();
887 // Clear it only if there is content
888 if (!empty($OUTPUT)) {
892 // Add some data to URL if cookies are not accepted
893 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
895 // Probe for bot from search engine
896 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
897 // Search engine bot detected so let's rewrite many chars for the link
898 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
900 // Output new location link as anchor
901 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
902 } elseif (!headers_sent()) {
903 // Load URL when headers are not sent
906 debug_print_backtrace();
907 die("</pre>URL={$URL}");
909 @header ("Location: ".str_replace("&", "&", $URL));
911 // Output error message
912 include(PATH."inc/header.php");
913 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
914 include(PATH."inc/footer.php");
919 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
920 global $SEC_CHARS, $URL_CHARS;
923 // Select smaller set of chars to replace when we e.g. want to compile URLs
924 if (!$full) $ARRAY = $URL_CHARS;
928 // BEFORE 0.2.1 : Language and data constants
929 // WITH 0.2.1+ : Only language constants
930 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
932 // BEFORE 0.2.1 : Not used
933 // WITH 0.2.1+ : Data constants
934 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
937 // Compile QUOT and other non-HTML codes
938 foreach ($ARRAY['to'] as $k => $to) {
939 // Do the reversed thing as in inc/libs/security_functions.php
940 $code = str_replace($to, $ARRAY['from'][$k], $code);
943 // But shall I keep simple quotes for later use?
944 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
946 // Find $content[bla][blub] entries
947 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
949 // Are some matches found?
950 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
951 // Replace all matches
952 $matchesFound = array();
953 foreach ($matches[0] as $key => $match) {
954 // Avoid replacing matches multiple times
955 if (!isset($matchesFound[$match])) {
957 $code = str_replace($match, "\".".$match.".\"", $code);
958 $matchesFound[$match] = 1;
961 // Take all string elements
962 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
963 // Replace it in the code
964 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
965 $code = str_replace($match, $newMatch, $code);
966 $matchesFound[$key."_".$matches[4][$key]] = 1;
971 // Return compiled code
975 /************************************************************************
977 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
978 * $a_sort sortiert: *
980 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
981 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
982 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
983 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
984 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
986 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
987 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
988 * Sie, dass es doch nicht so schwer ist! :-) *
990 ************************************************************************/
991 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
994 while ($primary_key < count($a_sort)) {
995 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
996 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
999 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1000 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1001 } elseif ($key != $key2) {
1002 // Sort numbers (E.g.: 9 < 10)
1003 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1004 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1008 // We have found two different values, so let's sort whole array
1009 foreach ($dummy as $sort_key => $sort_val) {
1010 $t = $dummy[$sort_key][$key];
1011 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1012 $dummy[$sort_key][$key2] = $t;
1023 // Write back sorted array
1027 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1029 global $MONTH_DESCR; $OUT = "";
1032 // This is a yes/no selection only!
1033 if ($id > 0) $prefix .= "[".$id."]";
1034 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1038 // Begin with regular selection box here
1039 if (!empty($prefix)) $prefix .= "_";
1041 if ($id > 0) $type2 .= "[".$id."]";
1042 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1047 for ($idx = 1; $idx < 32; $idx++)
1049 $OUT .= "<OPTION value=\"".$idx."\"";
1050 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1051 $OUT .= ">".$idx."</OPTION>\n";
1055 case "month": // Month
1056 foreach ($MONTH_DESCR as $month => $descr)
1058 $OUT .= "<OPTION value=\"".$month."\"";
1059 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1060 $OUT .= ">".$descr."</OPTION>\n";
1064 case "year": // Year
1066 $YEAR = date('Y', time());
1068 // Check if the default value is larger than minimum and bigger than actual year
1069 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1071 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1073 $OUT .= "<OPTION value=\"".$idx."\"";
1074 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1075 $OUT .= ">".$idx."</OPTION>\n";
1078 elseif ($DEFAULT == -1)
1080 // Current year minus 1
1081 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1083 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1088 // Get current year and subtract 16 (for erotic content)
1089 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1090 $YEAR = date('Y', time()) - 16;
1091 for ($idx = 1930; $idx <= $YEAR; $idx++)
1093 $OUT .= "<OPTION value=\"".$idx."\"";
1094 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1095 $OUT .= ">".$idx."</OPTION>\n";
1102 for ($idx = 0; $idx < 60; $idx+=5) {
1103 if (strlen($idx) == 1) $idx = "0".$idx;
1104 $OUT .= "<OPTION value=\"".$idx."\"";
1105 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1106 $OUT .= ">".$idx."</OPTION>\n";
1111 for ($idx = 0; $idx < 24; $idx++) {
1112 if (strlen($idx) == 1) $idx = "0".$idx;
1113 $OUT .= "<OPTION value=\"".$idx."\"";
1114 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1115 $OUT .= ">".$idx."</OPTION>\n";
1120 $OUT .= "<OPTION value=\"Y\"";
1121 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1122 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1123 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1124 $OUT .= ">".NO."</OPTION>\n";
1127 $OUT .= " </SELECT>\n";
1131 function TRANSLATE_YESNO($yn)
1135 case 'Y': $yn = YES; break;
1136 case 'N': $yn = NO; break;
1137 default : $yn = "??? (".$yn.")"; break;
1142 // Deprecated : $length
1145 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1148 // Fix missing _MAX constant
1149 if (!defined('_MAX')) define('_MAX', 15235);
1151 // Build server string
1152 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1155 $keys = SITE_KEY.":".DATE_KEY;
1156 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1157 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1158 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1159 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1161 // Build string from misc data
1162 $data = $code.":".$uid.":".$DATA;
1164 // Add more additional data
1165 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1166 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1167 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1168 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1169 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1170 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1172 // Calculate number for generating the code
1173 $a = $code + _ADD - 1;
1175 if (isset($_CONFIG['master_hash'])) {
1176 // Generate hash with master salt from modula of number with the prime number and other data
1177 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1179 // Create number from hash
1180 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1182 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1183 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1185 // Create number from hash
1186 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1189 // At least 10 numbers shall be secure enought!
1190 $len = $_CONFIG['code_length'];
1191 if ($len == 0) $len = $length;
1192 if ($len == 0) $len = 10;
1194 // Cut off requested counts of number
1195 $return = substr(str_replace('.', "", $rcode), 0, $len);
1197 // Done building code
1200 // Does only allow numbers
1201 function bigintval($num, $castValue = true) {
1202 // Filter all numbers out
1203 $ret = preg_replace("/[^0123456789]/", "", $num);
1206 if ($castValue) $ret = (double)$ret;
1208 // Has the whole value changed?
1209 if ("".$ret."" != "".$num."") {
1211 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1217 // Insert the code in $img_code into jpeg or PNG image
1218 function GENERATE_IMAGE($img_code, $header=true) {
1221 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1222 // Stop execution of function here because of over-sized code length
1224 } elseif (!$header) {
1225 // Return in an HTML code code
1226 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1230 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1231 if (FILE_READABLE($img)) {
1232 // Switch image type
1233 switch ($_CONFIG['img_type'])
1236 // Okay, load image and hide all errors
1237 $image = @imagecreatefromjpeg($img);
1241 // Okay, load image and hide all errors
1242 $image = @imagecreatefrompng($img);
1246 // Exit function here
1250 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1251 $text_color = imagecolorallocate($image, 0, 0, 0);
1253 // Insert code into image
1254 imagestring($image, 5, 14, 2, $img_code, $text_color);
1256 // Return to browser
1257 header ("Content-Type: image/".$_CONFIG['img_type']);
1259 // Output image with matching image factory
1260 switch ($_CONFIG['img_type']) {
1261 case "jpg": imagejpeg($image); break;
1262 case "png": imagepng($image); break;
1265 // Remove image from memory
1266 imagedestroy($image);
1268 // Create selection box or array of splitted timestamp
1269 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1270 // Calculate 2-seconds timestamp
1271 $stamp = round($timestamp / 2) * 2;
1273 // Do we have a leap year?
1275 $TEST = date('Y', time()) / 4;
1276 $M1 = date("m", time());
1277 $M2 = date("m", (time() + $stamp));
1279 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1280 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1282 // First of all years...
1283 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1285 $M = abs(floor($stamp / 2628000 - $Y * 12));
1287 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1289 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1291 $h = abs(floor($stamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1293 $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));
1294 // And at last seconds...
1295 $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));
1297 // Is seconds zero and time is < 60 seconds?
1298 if (($s == 0) && ($stamp < 60)) {
1300 $s = round($timestamp);
1304 // Now we convert them in seconds...
1306 if ($return_array) {
1307 // Just put all data in an array for later use
1319 $OUT = "<DIV align=\"".$align."\">\n";
1320 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1323 if (ereg('Y', $display) || (empty($display))) {
1324 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1327 if (ereg("M", $display) || (empty($display))) {
1328 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1331 if (ereg("W", $display) || (empty($display))) {
1332 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1335 if (ereg("D", $display) || (empty($display))) {
1336 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1339 if (ereg("h", $display) || (empty($display))) {
1340 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1343 if (ereg("m", $display) || (empty($display))) {
1344 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1347 if (ereg("s", $display) || (empty($display))) {
1348 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1354 if (ereg('Y', $display) || (empty($display))) {
1355 // Generate year selection
1356 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1357 for ($idx = 0; $idx <= 10; $idx++) {
1358 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1359 if ($idx == $Y) $OUT .= " selected default";
1360 $OUT .= ">".$idx."</OPTION>\n";
1362 $OUT .= " </SELECT></TD>\n";
1364 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1367 if (ereg("M", $display) || (empty($display))) {
1368 // Generate month selection
1369 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1370 for ($idx = 0; $idx <= 11; $idx++)
1372 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1373 if ($idx == $M) $OUT .= " selected default";
1374 $OUT .= ">".$idx."</OPTION>\n";
1376 $OUT .= " </SELECT></TD>\n";
1378 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1381 if (ereg("W", $display) || (empty($display))) {
1382 // Generate week selection
1383 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1384 for ($idx = 0; $idx <= 4; $idx++) {
1385 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1386 if ($idx == $W) $OUT .= " selected default";
1387 $OUT .= ">".$idx."</OPTION>\n";
1389 $OUT .= " </SELECT></TD>\n";
1391 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1394 if (ereg("D", $display) || (empty($display))) {
1395 // Generate day selection
1396 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1397 for ($idx = 0; $idx <= 31; $idx++) {
1398 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1399 if ($idx == $D) $OUT .= " selected default";
1400 $OUT .= ">".$idx."</OPTION>\n";
1402 $OUT .= " </SELECT></TD>\n";
1404 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1407 if (ereg("h", $display) || (empty($display))) {
1408 // Generate hour selection
1409 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1410 for ($idx = 0; $idx <= 23; $idx++) {
1411 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1412 if ($idx == $h) $OUT .= " selected default";
1413 $OUT .= ">".$idx."</OPTION>\n";
1415 $OUT .= " </SELECT></TD>\n";
1417 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1420 if (ereg("m", $display) || (empty($display))) {
1421 // Generate minute selection
1422 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1423 for ($idx = 0; $idx <= 59; $idx++) {
1424 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1425 if ($idx == $m) $OUT .= " selected default";
1426 $OUT .= ">".$idx."</OPTION>\n";
1428 $OUT .= " </SELECT></TD>\n";
1430 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1433 if (ereg("s", $display) || (empty($display))) {
1434 // Generate second selection
1435 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1436 for ($idx = 0; $idx <= 45; $idx += 15) {
1437 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1438 if ($idx == $s) $OUT .= " selected default";
1439 $OUT .= ">".$idx."</OPTION>\n";
1441 $OUT .= " </SELECT></TD>\n";
1443 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1446 $OUT .= "</TABLE>\n";
1448 // Return generated HTML code
1453 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1456 // Do we have a leap year?
1458 $TEST = date('Y', time()) / 4;
1459 $M1 = date("m", time());
1460 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1461 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1462 // First add years...
1463 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1465 $ret += $POST[$prefix."_mo"] * 2628000;
1467 $ret += $POST[$prefix."_we"] * 604800;
1469 $ret += $POST[$prefix."_da"] * 86400;
1471 $ret += $POST[$prefix."_ho"] * 3600;
1473 $ret += $POST[$prefix."_mi"] * 60;
1474 // And at last seconds...
1475 $ret += $POST[$prefix."_se"];
1476 // Return calculated value
1479 // Sends out mail to all administrators
1480 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1481 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1482 // Trim template name
1483 $template = trim($template);
1485 // Load email template
1486 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1488 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1489 // Older version detected!
1490 return SEND_ADMIN_EMAILS($subj, $msg);
1493 // Check which admin shall receive this mail
1494 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1495 array($template), __FILE__, __LINE__);
1496 if (SQL_NUMROWS($result) == 0) {
1497 // Create new entry (to all admins)
1498 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1499 array($template), __FILE__, __LINE__);
1501 // Load admin IDs...
1503 while(list($aid) = SQL_FETCHROW($result)) {
1508 SQL_FREERESULT($result);
1510 // "implode" IDs and query string
1511 $aid = implode(",", $aids);
1513 // Add line to userlog
1514 USERLOG_ADD_LINE($subj, $msg, $UID);
1516 } elseif ($aid == "0") {
1517 // Select all email adresses
1518 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1520 // If Admin-ID is not "to-all" select
1521 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1525 // Load email addresses and send away
1526 while (list($email) = SQL_FETCHROW($result)) {
1527 SEND_EMAIL($email, $subj, $msg);
1531 SQL_FREERESULT($result);
1534 function CREATE_FANCY_TIME($stamp) {
1535 // Get data array with years/months/weeks/days/...
1536 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1538 foreach($data as $k => $v) {
1540 // Value is greater than 0 "eval" data to return string
1541 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1547 // Do we have something there?
1548 if (strlen($ret) > 0) {
1549 // Remove leading commata and space
1550 $ret = substr($ret, 2);
1553 $ret = "0 "._SECONDS;
1556 // Return fancy time string
1560 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1561 $SEP = ""; $TOP = "";
1564 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1568 for ($page = 1; $page <= $PAGES; $page++) {
1569 // Is the page currently selected or shall we generate a link to it?
1570 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1571 // Is currently selected, so only highlight it
1572 $NAV .= "<STRONG>-";
1574 // Open anchor tag and add base URL
1575 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1577 // Add userid when we shall show all mails from a single member
1578 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1580 // Close open anchor tag
1584 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1585 // Is currently selected, so only highlight it
1586 $NAV .= "-</STRONG>";
1592 // Add seperator if we have not yet reached total pages
1593 if ($page < $PAGES) $NAV .= " | ";
1596 // Define constants only once
1597 if (!defined('__NAV_OUTPUT')) {
1598 define('__NAV_OUTPUT' , $NAV);
1599 define('__NAV_COLSPAN', $colspan);
1600 define('__NAV_TOP' , $TOP);
1601 define('__NAV_SEP' , $SEP);
1604 // Load navigation template
1605 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1608 // Return generated HTML-Code
1616 // Extract host from script name
1617 function EXTRACT_HOST (&$script) {
1618 // Use default SERVER_URL by default... ;) So?
1621 // Is this URL valid?
1622 if (substr($script, 0, 7) == "http://") {
1623 // Use the hostname from script URL as new hostname
1624 $url = substr($script, 7);
1625 $extract = explode("/", $url);
1627 // Done extracting the URL :)
1630 // Extract host name
1631 $host = str_replace("http://", "", $url);
1632 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1634 // Generate relative URL
1635 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1636 if (substr(strtolower($script), 0, 7) == "http://") {
1637 // But only if http:// is in front!
1638 $script = substr($script, (strlen($url) + 7));
1639 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1641 $script = substr($script, (strlen($url) + 8));
1644 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1645 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1651 // Send a GET request
1652 function GET_URL ($script) {
1653 // Compile the script name
1654 $script = COMPILE_CODE($script);
1656 // Extract host name from script
1657 $host = EXTRACT_HOST($script);
1659 // Generate GET request header
1660 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1661 $request .= "Host: " . $host . "\r\n";
1662 $request .= "Referer: " . URL . "/admin.php\r\n";
1663 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1664 $request .= "Content-Type: text/plain\r\n";
1665 $request .= "Cache-Control: no-cache\r\n";
1666 $request .= "Connection: Close\r\n\r\n";
1668 // Send the raw request
1669 $response = SEND_RAW_REQUEST($host, $request);
1671 // Return the result to the caller function
1675 // Send a POST request
1676 function POST_URL ($script, $postData) {
1677 // Is postData an array?
1678 if (!is_array($postData)) {
1680 return array("", "", "");
1683 // Compile the script name
1684 $script = COMPILE_CODE($script);
1686 // Extract host name from script
1687 $host = EXTRACT_HOST($script);
1689 // Construct request
1690 $data = http_build_query($postData, '', '&');
1692 // Generate POST request header
1693 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1694 $request .= "Host: " . $host . "\r\n";
1695 $request .= "Referer: " . URL . "/admin.php\r\n";
1696 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1697 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1698 $request .= "Content-length: " . strlen($data) . "\r\n";
1699 $request .= "Cache-Control: no-cache\r\n";
1700 $request .= "Connection: Close\r\n\r\n";
1703 // Send the raw request
1704 $response = SEND_RAW_REQUEST($host, $request);
1706 // Return the result to the caller function
1710 // Sends a raw request to another host
1711 function SEND_RAW_REQUEST ($host, $request) {
1715 $response = array("", "", "");
1717 // Default is not to use proxy
1720 // Are proxy settins set?
1721 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1727 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1729 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1731 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1735 if (!is_resource($fp)) {
1742 // Generate CONNECT request header
1743 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1744 $proxyTunnel .= "Host: ".$host."\r\n";
1746 // Use login data to proxy? (username at least!)
1747 if (!empty($_CONFIG['proxy_username'])) {
1749 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1750 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1753 // Add last new-line
1754 $proxyTunnel .= "\r\n";
1755 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1758 fputs($fp, $proxyTunnel);
1762 // No response received
1766 // Read the first line
1767 $resp = trim(fgets($fp, 10240));
1768 $respArray = explode(" ", $resp);
1769 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1770 // Invalid response!
1776 fputs($fp, $request);
1780 $response[] = trim(fgets($fp, 1024));
1786 // Skip first empty lines
1788 foreach ($resp as $idx => $line) {
1790 $line = trim($line);
1792 // Is this line empty?
1795 array_shift($response);
1797 // Abort on first non-empty line
1802 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1804 // Proxy agent found?
1805 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1806 // Proxy header detected, so remove two lines
1807 array_shift($response);
1808 array_shift($response);
1811 // Was the request successfull?
1812 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1813 // Not found / access forbidden
1814 $response = array("", "", "");
1820 // Taken from www.php.net eregi() user comments
1821 function VALIDATE_EMAIL($email) {
1823 $email = COMPILE_CODE($email);
1825 // Check first part of email address
1826 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1829 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1832 $regex = "^".$first."@".$domain."$";
1834 // Return check result
1835 return eregi($regex, $email);
1837 // Function taken from user comments on www.php.net / function eregi()
1838 function VALIDATE_URL ($URL, $compile=true) {
1839 // Trim URL a little
1840 $URL = trim(urldecode($URL));
1841 //* DEBUG: */ echo $URL."<br />";
1843 // Compile some chars out...
1844 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1845 //* DEBUG: */ echo $URL."<br />";
1847 // Check for the extension filter
1848 if (EXT_IS_ACTIVE("filter")) {
1849 // Use the extension's filter set
1850 return FILTER_VALIDATE_URL($URL, false);
1853 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1854 // https:// in front of the URLs
1855 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1858 function MEMBER_ACTION_LINKS($uid, $status="") {
1859 // Define all main targets
1860 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1862 // Begin of navigation links
1863 $eval = "\$OUT = \"[ ";
1865 foreach ($TARGETS as $tar) {
1866 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1867 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1868 if (($tar == "lock_user") && ($status == "LOCKED")) {
1869 // Locked accounts shall be unlocked
1870 $eval .= "UNLOCK_USER";
1872 // All other status is fine
1873 $eval .= strtoupper($tar);
1875 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1876 if (($tar == "lock_user") && ($status == "LOCKED")) {
1877 // Locked accounts shall be unlocked
1878 $eval .= "UNLOCK_USER";
1880 // All other status is fine
1881 $eval .= strtoupper($tar);
1883 $eval .= ".\"</A></SPAN> | ";
1886 // Finish navigation link
1887 $eval = substr($eval, 0, -7)."]\";";
1893 // Function for backward-compatiblity
1894 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1895 // Load it from the register extension
1896 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1898 // Generate an email link
1899 function CREATE_EMAIL_LINK($email, $table="admins") {
1900 // Default email link (INSECURE! Spammer can read this by harvester programs)
1901 $EMAIL = "mailto:".$email;
1903 // Check for several extensions
1904 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1905 // Create email link for contacting admin in guest area
1906 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1907 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1908 // Create email link for contacting a member within admin area (or later in other areas, too?)
1909 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1910 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1911 // Create email link to contact sponsor within admin area (or like the link above?)
1912 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1915 // Shall I close the link when there is no admin?
1916 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1918 // Return email link
1921 // Generate a hash for extra-security for all passwords
1922 function generateHash ($plainText, $salt = "") {
1923 global $_CONFIG, $_SERVER;
1925 // Is the required extension "sql_patches" there and a salt is not given?
1926 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == "")) && (empty($salt))) {
1927 // Extension sql_patches is missing/outdated so we return the plain text
1931 // Do we miss an arry element here?
1932 if (!isset($_CONFIG['file_hash'])) {
1934 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1935 debug_print_backtrace();
1939 // When the salt is empty build a new one, else use the first x configured characters as the salt
1941 // Build server string
1942 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1945 $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'];
1948 $data = $plainText.":".uniqid(rand(), true).":".time();
1950 // Calculate number for generating the code
1951 $a = time() + _ADD - 1;
1953 // Generate SHA1 sum from modula of number and the prime number
1954 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1955 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
1956 $sha1 = scrambleString($sha1);
1957 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
1958 //* DEBUG: */ $sha1b = descrambleString($sha1);
1959 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
1961 // Generate the password salt string
1962 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1963 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1966 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1967 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
1971 return $salt.sha1($salt.$plainText);
1974 function scrambleString($str) {
1980 // Final check, in case of failture it will return unscrambled string
1981 if (strlen($str) > 40) {
1982 // The string is to long
1984 } elseif (strlen($str) == 40) {
1986 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1988 // Generate new numbers
1989 $scrambleNums = explode(":", genScrambleString(strlen($str)));
1992 // Scramble string here
1993 //* DEBUG: */ echo "***Original=".$str."***<br />";
1994 for ($idx = 0; $idx < strlen($str); $idx++) {
1995 // Get char on scrambled position
1996 $char = substr($str, $scrambleNums[$idx], 1);
1998 // Add it to final output string
1999 $scrambled .= $char;
2002 // Return scrambled string
2003 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2007 function descrambleString($str) {
2009 // Scramble only 40 chars long strings
2010 if (strlen($str) != 40) return $str;
2012 // Load numbers from config
2013 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2016 if (count($scrambleNums) != 40) return $str;
2018 // Begin descrambling
2019 $orig = str_repeat(" ", 40);
2020 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2021 for ($idx = 0; $idx < 40; $idx++) {
2022 $char = substr($str, $idx, 1);
2023 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2026 // Return scrambled string
2027 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2031 function genScrambleString($len) {
2032 // Prepare randomizer and array for the numbers
2033 mt_srand((double) microtime() * 1000000);
2034 $scrambleNumbers = array();
2036 // First we need to setup randomized numbers from 0 to 31
2037 for ($idx = 0; $idx < $len; $idx++) {
2039 $rand = mt_rand(0, ($len -1));
2041 // Check for it by creating more numbers
2042 while (array_key_exists($rand, $scrambleNumbers)) {
2043 $rand = mt_rand(0, ($len -1));
2047 $scrambleNumbers[$rand] = $rand;
2050 // So let's create the string for storing it in database
2051 $scrambleString = implode(":", $scrambleNumbers);
2052 return $scrambleString;
2054 // Append data like session ID referral ID to the given URL which would
2055 // normally be stored in cookies
2056 function ADD_URL_DATA($URL) {
2060 // Determine URL binder
2062 if (strpos($URL, "?") !== false) $BIND = "&";
2064 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2065 // Cookies are not accepted
2066 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2067 // Cookie found in URL
2068 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2069 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2070 // Not found! So let's set default here
2071 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2074 // Is there already added data? Then change the binder
2075 if (!empty($ADD)) $BIND = "&";
2078 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2079 // Add session from URL
2080 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2082 // Add current session
2083 $ADD .= $BIND."PHPSESSID=".session_id();
2087 // Add all together and return it
2090 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2091 function generatePassString($passHash) {
2094 // Return vanilla password hash
2097 // Is a secret key and master salt already initialized?
2098 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2099 // Only calculate when the secret key is generated
2100 $newHash = ""; $start = 9;
2101 for ($idx = 0; $idx < 10; $idx++) {
2102 $part1 = hexdec(substr($passHash, $start, 4));
2103 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2104 $mod = dechex($idx);
2105 if ($part1 > $part2) {
2106 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2107 } elseif ($part2 > $part1) {
2108 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2110 $mod = substr(round($mod), 0, 4);
2111 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2112 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2117 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2118 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2119 //* DEBUG: */ print($ret."<br />\n");
2122 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2123 $ret = md5($passHash);
2124 //* DEBUG: */ echo "++".$ret."++<br />\n";
2131 // Fix "deleted" cookies
2132 function FIX_DELETED_COOKIES ($cookies) {
2133 // Is this an array with entries?
2134 if ((is_array($cookies)) && (count($cookies) > 0)) {
2135 // Then check all cookies if they are marked as deleted!
2136 foreach ($cookies as $cookieName) {
2137 // Is the cookie set to "deleted"?
2138 if (get_session($cookieName) == "deleted") {
2139 set_session($cookieName, "");
2145 // Output error messages in a fasioned way and die...
2146 function mxchange_die ($msg) {
2149 // Load the message template
2150 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2153 include(PATH."inc/footer.php");
2159 // Display parsing time and number of SQL queries in footer
2160 function DISPLAY_PARSING_TIME_FOOTER() {
2161 global $startTime, $_CONFIG;
2162 $endTime = microtime(true);
2164 // Is the timer started?
2165 if (!isset($GLOBALS['startTime'])) {
2170 // "Explode" both times
2171 $start = explode(" ", $GLOBALS['startTime']);
2172 $end = explode(" ", $endTime);
2173 $runTime = $end[0] - $start[0];
2174 if ($runTime < 0) $runTime = 0;
2175 $runTime = TRANSLATE_COMMA($runTime);
2179 'runtime' => $runTime,
2180 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2181 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2184 // Load the template
2185 LOAD_TEMPLATE("show_timings", false, $content);
2188 // Unset/set session variables
2189 function set_session ($var, $value) {
2192 // Abort in CSS mode here
2193 if ($CSS == 1) return true;
2195 // Trim value and session variable
2196 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2198 // Is the session variable set?
2199 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2200 // Remove the session
2201 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2202 unset($_SESSION[$var]);
2203 return session_unregister($var);
2204 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2206 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2207 $_SESSION[$var] = $value;
2208 return session_register($var);
2209 } elseif (!empty($value)) {
2211 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2212 $_SESSION[$var] = $value;
2216 // Ignored (but valid)
2217 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2221 // Check wether a boolean constant is set
2222 // Taken from user comments in PHP documentation for function constant()
2223 function isBooleanConstantAndTrue($constName) { // : Boolean
2226 // Failed by default
2230 if (isset($constCache[$constName])) {
2232 //* DEBUG: */ echo __FUNCTION__.": ".$constName."-CACHE!<br />\n";
2233 $res = $constCache[$constName];
2236 //* DEBUG: */ echo __FUNCTION__.": ".$constName."-RESOLVE!<br />\n";
2237 if (defined($constName)) $res = (constant($constName) === true);
2240 $constCache[$constName] = $res;
2242 //* DEBUG: */ var_dump($res);
2248 // Check wether a session variable is set
2249 function isSessionVariableSet($var) {
2250 //* DEBUG: */ echo __FUNCTION__.":var={$var}<br />\n";
2251 return (isset($_SESSION[$var]));
2253 // Returns wether the value of the session variable or NULL if not set
2254 function get_session($var) {
2257 // Default is not found! ;-)
2260 // Is the variable there or cached values?
2261 if (isset($cacheArray['session'][$var])) {
2262 // Get cached value (skips a lot SQL_ESCAPE() calles!
2263 $value = $cacheArray['session'][$var];
2264 } elseif (isSessionVariableSet($var)) {
2265 // Then get it secured!
2266 $value = SQL_ESCAPE($_SESSION[$var]);
2269 $cacheArray['session'][$var] = $value;
2275 // Send notification to admin
2276 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content="", $uid="0") {
2277 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2279 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2281 // Send outdated way
2282 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2283 SEND_ADMIN_EMAILS($subject, $msg);
2286 // Destroy user session
2287 function destroy_user_session () {
2288 // Remove all user data from session
2289 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2291 // Merges an array together but only if both are arrays
2292 function merge_array ($array1, $array2) {
2293 // Are both an array?
2294 if ((is_array($array1)) && (is_array($array2))) {
2295 // Merge all together
2296 return array_merge($array1, $array2);
2297 } elseif (is_array($array1)) {
2298 // Return left array
2302 // Something wired happened here...
2303 print(__FUNCTION__.":<pre>");
2304 debug_print_backtrace();
2307 // Debug message logger
2308 function DEBUG_LOG ($message, $force=false) {
2309 // Is debug mode enabled?
2310 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2311 // Log this message away
2312 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2313 fwrite($fp, date("d.m.Y|H:i:s", time())."|{$message}\n");
2317 // Reads a directory with PHP files in and gets only files back
2318 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2322 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2325 while ($baseFile = readdir($dirPointer)) {
2326 // Load file only if extension is active
2328 $file = $baseDir.$baseFile;
2330 // Is this a valid reset file?
2331 //* DEBUG: */ echo __FUNCTION__.":baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2332 if ((is_file($file)) && (is_readable($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2333 // Remove both for extension name
2334 $extName = substr($baseFile, strlen($prefix), -4);
2337 $extId = GET_EXT_ID($extName);
2339 // Is the extension valid and active?
2340 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2341 // Then add this file
2343 } elseif ($extId == 0) {
2344 // Add non-extension files as well
2351 closedir($dirPointer);
2353 // Return array with include files
2356 // Load more reset scripts
2357 function RESET_ADD_INCLUDES () {
2360 // Is the reset set or old sql_patches?
2361 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2366 // Get more daily reset scripts
2367 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2369 // Create current week mark
2370 $currWeek = date("W", time());
2373 if ($_CONFIG['last_week'] != $currWeek) {
2374 // Include weekly reset scripts
2375 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2378 UPDATE_CONFIG("last_week", $currWeek);
2381 // Create current month mark
2382 $currMonth = date("m", time());
2385 if ($_CONFIG['last_month'] != $currMonth) {
2386 // Include monthly reset scripts
2387 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2390 UPDATE_CONFIG("last_month", $currMonth);
2396 // Handle extra values
2397 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2398 // Default is the value itself
2401 // Do we have a special filter function?
2402 if (!empty($filterFunction)) {
2403 // Does the filter function exist?
2404 if (function_exists($filterFunction)) {
2405 // Do we have extra parameters here?
2406 if (!empty($extraValue)) {
2407 // Put both parameters in one new array by default
2408 $args = array($value, $extraValue);
2410 // If we have an array simply use it and pre-extend it with our value
2411 if (is_array($extraValue)) {
2412 // Make the new args array
2413 $args = array_merge(array($value), $extraValue);
2416 // Call the multi-parameter call-back
2417 $ret = call_user_func_array($filterFunction, $args);
2419 // One parameter call
2420 $ret = call_user_func($filterFunction, $value);
2428 // Check if given FQFN is a readable file
2429 function FILE_READABLE($fqfn) {
2431 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2433 // Converts timestamp selections into a timestamp
2434 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2435 // Init test variable
2438 // Get last three chars
2439 $TEST = substr($id, -3);
2441 // Improved way of checking! :-)
2442 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2443 // Found a multi-selection for timings?
2444 $TEST = substr($id, 0, -3);
2445 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)) {
2446 // Generate timestamp
2447 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2448 $DATA[] = "$TEST='".$POST[$TEST]."'";
2450 // Remove data from array
2451 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2452 unset($POST[$TEST."_".$rem]);
2456 unset($id); $skip = true; $TEST2 = $TEST;
2459 // Process this entry
2460 $skip = false; $TEST2 = "";
2463 // Reverts the german decimal comma into Computer decimal dot
2464 function REVERT_COMMA ($str) {
2465 // Default float is not a float... ;-)
2468 // Which language is selected?
2469 switch (GET_LANGUAGE()) {
2470 case "de": // German language
2471 // Remove german thousand dots first
2472 $str = str_replace(".", "", $str);
2474 // Replace german commata with decimal dot and cast it
2475 $float = (float)str_replace(",", ".", $str);
2478 default: // US and so on
2479 // Remove thousand dots first and cast
2480 $float = (float)str_replace(",", "", $str);
2487 // Handle menu-depending failed logins and return the rendered content
2488 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2489 // Default output is empty ;-)
2492 // Is the session data set?
2493 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2494 // Ignore zero values
2495 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2496 // Non-guest has login failtures found, get both data and prepare it for template
2497 //* DEBUG: */ echo __FUNCTION__.":accessLevel={$accessLevel}<br />\n";
2499 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2500 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2504 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2507 // Reset session data
2508 set_session('mxchange_'.$accessLevel.'_failtures', "");
2509 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2512 // Return rendered content
2516 function REBUILD_CACHE ($cache, $inc="") {
2517 global $cacheInstance;
2519 // Shall I remove the cache file?
2520 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2522 if ($cacheInstance->cache_file($cache, true)) {
2524 $cacheInstance->cache_destroy();
2526 // Include file given?
2528 // And rebuild it from scratch
2529 require_once(PATH."inc/loader/load_cache-".$inc.".php");
2534 // Purge admin menu cache
2535 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2536 global $_CONFIG, $cacheInstance;
2538 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2539 if (!EXT_IS_ACTIVE("cache")) {
2540 // Cache extension not active
2542 } elseif (!is_object($cacheInstance)) {
2543 // No cache instance!
2544 DEBUG_LOG(__FUNCTION__.": No cache instance found.");
2546 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2547 // Caching disabled (currently experiemental!)
2551 // Experiemental feature!
2552 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2555 //////////////////////////////////////////////////
2557 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2559 //////////////////////////////////////////////////
2561 if (!function_exists('html_entity_decode')) {
2562 // Taken from documentation on www.php.net
2563 function html_entity_decode($string) {
2564 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2565 $trans_tbl = array_flip($trans_tbl);
2566 return strtr($string, $trans_tbl);