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 (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
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) {
56 // Count tables so we can generate CSS classes for every table... :-)
58 // Class is empty so count one up and create a class
59 $table_cnt++; $CLASS = "class".$table_cnt;
61 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
63 // Shall I add the classes to TABLE and TD or only to TD?
64 if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
67 if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
70 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
72 // Vertical align is given
73 if (!empty($VALIGN)) $OUT .= " valign=\"".$VALIGN."\"";
77 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
78 $OUT .= " class=\"".$CLASS."\">";
82 // Close a table (you may want to add some footer stuff here)
83 function CLOSE_TABLE($ADD="") {
86 if (!empty($ADD)) OUTPUT_HTML($ADD);
87 OUTPUT_HTML("</TABLE>");
90 // Output HTML code directly or "render" it. You addionally switch the new-line character off
91 function OUTPUT_HTML($HTML, $NEW_LINE = true) {
92 // Some global variables
93 global $OUTPUT, $footer, $CSS;
95 // Do we have HTML-Code here?
97 // Yes, so we handle it as you have configured
101 // That's why you don't need any \n at the end of your HTML code... :-)
102 if (_OB_CACHING == "on") {
103 // Output into PHP's internal buffer
106 // That's why you don't need any \n at the end of your HTML code... :-)
107 if ($NEW_LINE) echo "\n";
109 // Render mode for old or lame servers...
112 // That's why you don't need any \n at the end of your HTML code... :-)
113 if ($NEW_LINE) $OUTPUT .= "\n";
118 // If we are switching from render to direct output rendered code
119 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
121 // The same as above... ^
123 if ($NEW_LINE) echo "\n";
127 // Huh, something goes wrong or maybe you have edited config.php ???
128 die ("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
131 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
132 // Output cached HTML code
133 $OUTPUT = ob_get_contents();
135 // Clear output buffer for later output
138 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
139 $OUTPUT = REWRITE_LINKS($OUTPUT);
142 // Compile and run finished rendered HTML code
143 while (strpos($OUTPUT, "{!") > 0) {
144 $eval = "\$OUTPUT = \"" . COMPILE_CODE(addslashes($OUTPUT)) . "\";";
148 // Output code here, DO NOT REMOVE! ;-)
150 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
151 // Rewrite links when rewrite extension is active
152 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
153 $OUTPUT = REWRITE_LINKS($OUTPUT);
156 // Compile and run finished rendered HTML code
157 while (strpos($OUTPUT, "{!") > 0) {
158 $eval = "\$OUTPUT = \"" . COMPILE_CODE(addslashes($OUTPUT)) . "\";";
162 // Output code here, DO NOT REMOVE! ;-)
167 // Output the raw HTML code
168 function OUTPUT_RAW ($HTML) {
169 if ((isBooleanConstantAndTrue('mxchange_installed')) && (basename($_SERVER['PHP_SELF']) != "install.php")) {
170 // Not in install-mode so strip slashes away
171 echo stripslashes($HTML);
173 // Output directly in install-mode
181 // Add a fatal error message to the queue array
182 function ADD_FATAL ($message, $extra="")
186 // Regular text message to add to $FATAL
189 // $message is text with a mask plus extras to insert into the text
190 $FATAL[] = sprintf($message, $extra);
194 // Load a template file and return it's content (only it's name; do not use ' or ")
195 function LOAD_TEMPLATE($template, $return=false, $content="") {
196 // Add more variables which you want to use in your template files
197 global $DATA, $_CONFIG, $username;
199 // Count the template load
200 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
201 $_CONFIG['num_templates']++;
204 $ACTION = SQL_ESCAPE($GLOBALS['action']);
205 $WHAT = SQL_ESCAPE($GLOBALS['what']);
207 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
208 $REFID = $GLOBALS['refid'];
210 if ($template == "member_support_form") {
211 // Support request of a member
212 $result = SQL_QUERY_ESC("SELECT sex, surname, family FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
213 array($GLOBALS['userid']), __FILE__, __LINE__);
214 list($sex, $surname, $family) = SQL_FETCHROW($result);
215 SQL_FREERESULT($result);
216 $salut = TRANSLATE_SEX($sex);
219 // Generate date/time string
220 $date_time = MAKE_DATETIME(time(), "1");
223 $BASE = PATH."templates/".GET_LANGUAGE()."/html/";
226 // Check for admin/guest/member templates
227 if (strpos($template, "admin_") > -1) {
228 // Admin template found
230 } elseif (strpos($template, "guest_") > -1) {
231 // Guest template found
233 } elseif (strpos($template, "member_") > -1) {
234 // Member template found
236 } elseif (strpos($template, "install_") > -1) {
237 // Installation template found
239 } elseif (strpos($template, "ext_") > -1) {
240 // Extension template found
242 } elseif (strpos($template, "la_") > -1) {
243 // "Logical-area" template found
246 // Test for extension
247 $test = substr($template, 0, strpos($template, "_"));
248 if (EXT_IS_ACTIVE($test)) {
249 // Set extra path to extension's name
254 ////////////////////////
255 // Generate file name //
256 ////////////////////////
257 $file = $BASE.$MODE.$template.".tpl";
259 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
260 // Select what depended header/footer template file for admin/guest/member area
261 $file2 = sprintf("%s%s%s_%s.tpl",
265 SQL_ESCAPE($GLOBALS['what'])
269 if (file_exists($file2)) $file = $file2;
271 // Remove variable from memory
275 // Does the special template exists?
276 if ((!file_exists($file)) || (!is_readable($file))) {
277 // Reset to default template
278 $file = $BASE.$template.".tpl";
281 // Now does the final template exists?
282 if ((file_exists($file)) && (is_readable($file))) {
283 // The local file does exists so we load it. :)
284 $tmpl_file = implode("", file($file));
286 // Replace ' to our own chars to preventing them being quoted
287 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", "{QUOT}", $tmpl_file); }
289 // Do we have to compile the code?
290 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
292 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
295 // Simply return loaded code
299 // Add surrounding HTML comments to help finding bugs faster
300 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
301 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
302 // Only admins shall see this warning or when installation mode is active
303 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
304 (".basename($file).")<br />
307 <PRE>".print_r($content, true)."</PRE>
309 <PRE>".print_r($DATA, true)."</PRE>
313 // Do we have some content to output or return?
315 // Not empty so let's put it out! ;)
317 // Return the HTML code
323 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
324 // Warning, empty output!
325 return "E:".$template."<br />\n";
329 // Send mail out to an email address
330 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML='N', $FROM="") {
331 // Compile subject line (for POINTS constant etc.)
332 $eval = "\$SUBJECT = \"".COMPILE_CODE(addslashes($SUBJECT))."\";";
334 $SUBJECT = html_entity_decode($SUBJECT);
337 if (!eregi("@", $TO)) {
338 // Value detected, load email from database
339 if (EXT_IS_ACTIVE("msg")) {
340 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
343 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
344 list($TO) = SQL_FETCHROW($result_email);
345 SQL_FREERESULT($result_email);
349 // Not in PHPMailer-Mode
350 if (!CHECK_PHPMAILER_USAGE()) {
352 // Load email header template
353 $FROM = LOAD_EMAIL_TEMPLATE("header");
356 $FROM .= LOAD_EMAIL_TEMPLATE("header");
358 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
360 // Load email header template
361 $FROM = LOAD_EMAIL_TEMPLATE("header");
364 $FROM .= LOAD_EMAIL_TEMPLATE("header");
368 // Fix HTML parameter (default is no!)
369 if (empty($HTML)) $HTML = 'N';
370 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
371 // In debug mode we want to display the mail instead of sending it away so we can debug this part
373 ".htmlentities(trim($FROM))."
375 Subject : ".$SUBJECT."
378 } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE("html_mail", true))) {
379 // Send mail as HTML away
380 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
381 } elseif (!empty($TO)) {
383 $TO = COMPILE_CODE($TO);
386 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
387 } elseif ($HTML == 'N') {
389 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
393 // Check if legacy or PHPMailer command
395 function CHECK_PHPMAILER_USAGE() {
396 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
400 * Send out a raw email with PHPMailer class or legacy mail() command
402 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
403 // Shall we use PHPMailer class or legacy mode?
404 if (CHECK_PHPMAILER_USAGE()) {
405 // Use PHPMailer class with SMTP enabled
406 require_once(PATH."inc/phpmailer/class.phpmailer.php");
407 require_once(PATH."inc/phpmailer/class.smtp.php");
410 $mail = new PHPMailer();
411 $mail->PluginDir = PATH."inc/phpmailer/";
414 $mail->SMTPAuth = true;
415 $mail->Host = SMTP_HOSTNAME;
417 $mail->Username = SMTP_USER;
418 $mail->Password = SMTP_PASSWORD;
420 $mail->FromName = MAIN_TITLE;
421 $mail->Subject = $subject;
422 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
424 $mail->AltBody = "Your mail program required HTML support to read this mail!";
425 $mail->WordWrap = 70;
430 $mail->AddAddress($to, "");
431 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
432 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
433 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
436 // Use legacy mail() command
437 @mail($to, $subject, $msg, $from);
442 // Generate a password in a specified length or use default password length
443 function GEN_PASS($LEN = 0) {
445 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
447 // Initialize array with all allowed chars
448 $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,-,+,_,/");
450 // Initialize randomizer
451 mt_srand((double) microtime() * 1000000);
453 // Start creating password
455 for ($i = 0; $i < $LEN; $i++) {
456 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
459 // When the size is below 40 we can also add additional security by scrambling it
460 if (strlen($PASS) <= 40) {
461 // Also scramble the password
462 $PASS = scrambleString($PASS);
465 // Return the password
469 function MAKE_DATETIME($time, $mode="0")
473 return NEVER_HAPPENED;
475 // Filter out numbers
476 $time = bigintval($time);
479 switch (GET_LANGUAGE())
481 case "de": // German date / time format
484 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
485 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
486 case "2": $ret = date("d.m.Y|H:i", $time); break;
487 case "3": $ret = date("d.m.Y", $time); break;
491 default: // Default is the US date / time format!
494 case "0": $ret = date("r", $time); break;
495 case "1": $ret = date("Y-m-d - g:i A", $time); break;
496 case "2": $ret = date("y-m-d|H:i", $time); break;
497 case "3": $ret = date("y-m-d", $time); break;
503 // Translates the american decimal dot into a german comma
504 function TRANSLATE_COMMA($dotted, $cut=true)
507 // Default is 3 you can change this in admin area "Misc -> Misc Options"
508 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
509 if (!ereg("\.", $dotted)) $dotted .= ".".str_repeat("0", $_CONFIG['max_comma']);
511 // Remove trailing zeros
512 $dot = str_replace(".", "x", $dotted);
513 while(substr($dot, -1, 1) == "0") {
514 $dot = substr($dot, 0, -1);
517 if (substr($dot, -1, 1) == "x") {
518 // Last char is the 'x'
519 $dotted = substr($dot, 0, -1);
521 // Last char is a number
522 $dotted = str_replace("x", ".", $dot);
527 switch (GET_LANGUAGE()) {
529 $pos = strpos($dotted, ".");
532 // Cut x numbers behind comma
533 $dotted = str_replace(".", ",", substr($dotted, 0, ($pos + $_CONFIG['max_comma'] + 1)));
535 // Replace comma with dot
536 $dotted = str_replace(".", ",", $dotted);
540 $dotted = "0,".str_repeat("0", $_CONFIG['max_comma']);
542 $dotted .= ",".str_repeat("0", $_CONFIG['max_comma']);
550 $dotted = substr($dotted, 0, ($pos + $_CONFIG['max_comma'] + 1));
552 $dotted .= ".".str_repeat("0", $_CONFIG['max_comma']);
561 function DEREFERER($URL) {
562 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(COMPILE_CODE($URL)));
567 function TRANSLATE_SEX($sex) {
570 case "M": $ret = SEX_M; break;
571 case "F": $ret = SEX_F; break;
572 case "C": $ret = SEX_C; break;
573 default : $ret = $sex; break;
578 function GET_POOL_TYPE($PT)
582 case "TEMP" : $ret = POOL_TEMP; break;
583 case "SEND" : $ret = POOL_SEND; break;
584 case "NEW" : $ret = POOL_NEW; break;
585 case "ADMIN" : $ret = POOL_ADMIN; break;
586 case "ACTIVE" : $ret = POOL_ACTIVE; break;
587 case "DELETED": $ret = POOL_DELETED; break;
588 default : $ret = POOL_UNKNOWN." (".$PT.")"; break;
593 function FRAMETESTER($URL)
596 $URL = URL."/modules.php?module=frametester&url=".urlencode(base64_encode(COMPILE_CODE($URL)));
600 function SELECTION_COUNT($array)
603 if (is_array($array))
605 foreach ($array as $key=>$sel)
607 if (!empty($sel)) $ret++;
613 function IMG_CODE ($code, $type, $DATA, $uid)
615 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
618 function TRANSLATE_STATUS($status)
623 $ret = ACCOUNT_UNCONFIRMED;
627 $ret = ACCOUNT_CONFIRMED;
631 $ret = ACCOUNT_LOCKED;
635 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
641 function GET_LANGUAGE() {
642 if (!empty($_GET['mx_lang'])) {
643 // Accept only first 2 chars
644 $lang = substr($_GET['mx_lang'], 0, 2);
650 // Set default return value to default language from config
653 // Check GET variable and cookie
655 // Check if main language file does exist
656 if (file_exists(PATH."inc/language/".$lang.".php")) {
657 // Okay found, so let's update cookies
660 } elseif (!isSessionVariableSet('mx_lang')) {
661 // Return stored value from cookie
662 $ret = get_session('mx_lang');
667 function SET_LANGUAGE($lang) {
670 // Accept only first 2 chars!
671 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
674 set_session("mx_lang", $lang);
677 function LOAD_EMAIL_TEMPLATE($template, $content="", $UID="0") {
678 global $DATA, $_CONFIG, $REPLACER;
680 // Keept for backward-compatiblity (please replace these variables against our new {--CONST--} syntax!)
681 $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
682 $surname = ""; $family = ""; $nick = ""; $sex = 'N';
684 // Prepare IP number and User Agent
685 $REMOTE_ADDR = getenv('REMOTE_ADDR');
686 $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
689 if (isSessionVariableSet('admin_login')) {
691 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
692 array(SQL_ESCAPE(get_session('admin_login'))), __FILE__, __LINE__);
693 list($ADMIN) = SQL_FETCHROW($result);
694 SQL_FREERESULT($result);
697 // Expiration in a nice output format
698 if ($_CONFIG['auto_purge'] == 0) {
699 // Will never expire!
700 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
701 } elseif (function_exists('CREATE_FANCY_TIME')) {
702 // Create nice date string
703 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
706 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
711 case "bonus-mail": // Load data for the bonus mail
714 $points = TRANSLATE_COMMA($DATA[4]);
716 $TARGET_URL = $DATA[8];
717 $CATEGORY = GET_CATEGORY($DATA[9]);
721 foreach ($REPLACER as $key=>$value)
723 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
729 $BLOCKS = $_CONFIG['max_send'];
732 $PAYMENT = GET_PAYMENT($DATA[3]);
733 $TARGET_URL = $DATA[5];
734 $CATEGORY = GET_CATEGORY($DATA[6]);
738 case "order-deleted":
740 $TARGET_URL = $DATA[0];
750 case "confirm-member":
751 $points = $_CONFIG['points_register'];
754 case "confirm-referral":
762 $SEND_UID = $DATA[1];
763 $CATEGORY = GET_CATEGORY($DATA[9]);
764 $TIME = GET_PAY_POINTS($DATA[5], "time");
765 $TARGET_URL = $DATA[7];
766 $points = TRANSLATE_COMMA(GET_PAY_POINTS($DATA[5], "payment"));
767 // Warning! This ID has changed from 10 to 11!
771 foreach ($REPLACER as $key=>$value)
773 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
779 $SEND_UID = $DATA[1];
780 $CATEGORY = GET_CATEGORY($DATA[9]);
781 $TARGET_URL = $DATA[7];
786 $points = TRANSLATE_COMMA($DATA[10]);
790 $points = bigintval($_POST['points']);
793 case "guest_request_confirm":
800 if (EXT_IS_ACTIVE("nickname")) {
802 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
803 array(bigintval($UID)), __FILE__, __LINE__);
804 list($surname, $family, $sex, $email, $nick) = SQL_FETCHROW($result);
805 SQL_FREERESULT($result);
808 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
809 array(bigintval($UID)), __FILE__, __LINE__);
810 list($surname, $family, $sex, $email) = SQL_FETCHROW($result);
811 SQL_FREERESULT($result);
815 // Neutral sex and email address is default
820 // Translate M to male or F to female
821 $salut = TRANSLATE_SEX($sex);
823 // Store email for some functions in global data array
824 $DATA['email'] = $email;
827 $BASE = PATH."templates/".GET_LANGUAGE()."/emails/";
829 // Check for admin/guest/member templates
830 if (strpos($template, "admin_") > -1) {
831 // Admin template found
832 $file = $BASE."admin/".$template.".tpl";
833 } elseif (strpos($template, "guest_") > -1) {
834 // Guest template found
835 $file = $BASE."guest/".$template.".tpl";
836 } elseif (strpos($template, "member_") > -1) {
837 // Member template found
838 $file = $BASE."member/".$template.".tpl";
840 // Test for extension
841 $test = substr($template, 0, strpos($template, "_"));
842 if (EXT_IS_ACTIVE($test)) {
843 // Set extra path to extension's name
844 $file = $BASE.$test."/".$template.".tpl";
846 // No special filename
847 $file = $BASE.$template.".tpl";
851 // Does the special template exists?
852 if ((!@file_exists($file)) || (!is_readable($file))) {
853 // Reset to default template
854 $file = $BASE.$template.".tpl";
857 // Now does the final template exists?
858 if ((@file_exists($file)) && (is_readable($file)))
860 // The local file does exists so we load it. :)
861 $tmpl_file = @implode("", @file($file));
862 $tmpl_file = addslashes($tmpl_file);
865 $tmpl_file = COMPILE_CODE($tmpl_file);
868 $tmpl_file = "\$content=\"".$tmpl_file."\";";
871 // Replace HTML confirm chars
872 $content = html_entity_decode($content);
874 elseif (!empty($template))
876 // Template file not found!
877 $content = TEMPLATE_404.": ".$template."<br />
879 <PRE>".print_r($content, true)."</PRE>
881 <PRE>".print_r($DATA, true)."</PRE>
884 // Debug mode not active? Then remove the HTML tags
885 if (!DEBUG_MODE) $content = strip_tags($content);
889 // No template name supplied!
890 $content = NO_TEMPLATE_SUPPLIED;
892 return COMPILE_CODE($content);
895 function MAKE_TIME($H, $M, $S, $stamp)
897 // Extract day, month and year from given timestamp
898 $DAY = date("d", $stamp);
899 $MONTH = date("m", $stamp);
900 $YEAR = date('Y', $stamp);
902 // Create timestamp for wished time which depends on extracted date
903 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
906 function LOAD_URL($URL, $addUrlData=true) {
907 global $CSS, $_CONFIG, $link, $db, $footer;
909 // Check if http(s):// is there
910 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
911 // Make all URLs full-qualified
915 // Compile out URI codes
916 $URL = COMPILE_CODE($URL);
918 // Add some data to URL if cookies are not accepted
919 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
921 // Probe for bot from search engine
922 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
923 // Search engine bot detected so let's rewrite many chars for the link
924 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
926 // Output new location link as anchor
927 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
928 } elseif (!headers_sent()) {
929 // Load URL when headers are not sent
930 @header ("Location: ".str_replace("&", "&", $URL));
932 // Output error message
933 include(PATH."inc/header.php");
934 OUTPUT_HTML(LOAD_URL_ERROR_1.$URL.LOAD_URL_ERROR_2);
935 include(PATH."inc/footer.php");
940 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
941 global $SEC_CHARS, $URL_CHARS;
944 // Select smaller set of chars to replace when we e.g. want to compile URLs
945 if (!$full) $ARRAY = $URL_CHARS;
949 // BEFORE 0.2.1 : Language and data constants
950 // WITH 0.2.1+ : Only language constants
951 $code = str_replace("{--", '".', str_replace("--}", '."', $code));
953 // BEFORE 0.2.1 : Not used
954 // WITH 0.2.1+ : Data constants
955 $code = str_replace("{!", '".', str_replace("!}", '."', $code));
958 // Compile QUOT and other non-HTML codes
959 foreach ($ARRAY['to'] as $k => $to) {
960 // Do the reversed thing as in inc/libs/security_functions.php
961 $code = str_replace($to, $ARRAY['from'][$k], $code);
964 // But shall I keep simple quotes for later use?
965 if ($simple) $code = str_replace("\'", "{QUOT}", $code);
967 // Find $content[bla][blub] entries
968 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
970 // Are some matches found?
971 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
972 // Replace all matches
973 $matchesFound = array();
974 foreach ($matches[0] as $key=>$match) {
975 // Avoid replacing matches multiple times
976 if (!isset($matchesFound[$match])) {
978 $code = str_replace($match, "\".".$match.".\"", $code);
979 $matchesFound[$match] = 1;
982 // Take all string elements
983 if (("".bigintval($matches[4][$key])."" != $matches[4][$key]) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
984 // Replace it in the code
985 $code = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $code);
986 $matchesFound[$key."_".$matches[4][$key]] = 1;
991 // Return compiled code
995 /************************************************************************
997 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
998 * $a_sort sortiert: *
1000 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1001 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1002 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1003 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1004 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1006 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1007 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1008 * Sie, dass es doch nicht so schwer ist! :-) *
1010 ************************************************************************/
1011 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1014 while ($primary_key < count($a_sort))
1016 foreach ($dummy[$a_sort[$primary_key]] as $key=>$value)
1018 foreach ($dummy[$a_sort[$primary_key]] as $key2=>$value2)
1023 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1024 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1026 elseif ($key != $key2)
1028 // Sort numbers (E.g.: 9 < 10)
1029 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1030 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1034 // We have found two different values, so let's sort whole array
1035 foreach ($dummy as $sort_key=>$sort_val)
1037 $t = $dummy[$sort_key][$key];
1038 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1039 $dummy[$sort_key][$key2] = $t;
1050 // Write back sorted array
1054 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1056 global $MONTH_DESCR; $OUT = "";
1059 // This is a yes/no selection only!
1060 if ($id > 0) $prefix .= "[".$id."]";
1061 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1065 // Begin with regular selection box here
1066 if (!empty($prefix)) $prefix .= "_";
1068 if ($id > 0) $type2 .= "[".$id."]";
1069 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1074 for ($idx = 1; $idx < 32; $idx++)
1076 $OUT .= " <OPTION value=\"".$idx."\"";
1077 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1078 $OUT .= ">".$idx."</OPTION>\n";
1082 case "month": // Month
1083 foreach ($MONTH_DESCR as $month=>$descr)
1085 $OUT .= " <OPTION value=\"".$month."\"";
1086 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1087 $OUT .= ">".$descr."</OPTION>\n";
1091 case "year": // Year
1093 $YEAR = date('Y', time());
1095 // Check if the default value is larger than minimum and bigger than actual year
1096 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1098 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1100 $OUT .= " <OPTION value=\"".$idx."\"";
1101 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1102 $OUT .= ">".$idx."</OPTION>\n";
1105 elseif ($DEFAULT == -1)
1107 // Current year minus 1
1108 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1110 $OUT .= " <OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1115 // Get current year and subtract 16 (for erotic content)
1116 $OUT .= " <OPTION value=\"1929\"><1930</OPTION>\n";
1117 $YEAR = date('Y', time()) - 16;
1118 for ($idx = 1930; $idx <= $YEAR; $idx++)
1120 $OUT .= " <OPTION value=\"".$idx."\"";
1121 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1122 $OUT .= ">".$idx."</OPTION>\n";
1129 for ($idx = 0; $idx < 60; $idx+=5)
1131 if (strlen($idx) == 1) $idx = "0".$idx;
1132 $OUT .= " <OPTION value=\"".$idx."\"";
1133 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1134 $OUT .= ">".$idx."</OPTION>\n";
1139 for ($idx = 0; $idx < 24; $idx++)
1141 if (strlen($idx) == 1) $idx = "0".$idx;
1142 $OUT .= " <OPTION value=\"".$idx."\"";
1143 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1144 $OUT .= ">".$idx."</OPTION>\n";
1149 $OUT .= " <OPTION value=\"Y\"";
1150 if ($DEFAULT == 'Y') $OUT .= " selected=\"selected\"";
1151 $OUT .= ">".YES."</OPTION>
1152 <OPTION value=\"N\"";
1153 if ($DEFAULT == 'N') $OUT .= " selected=\"selected\"";
1154 $OUT .= ">".NO."</OPTION>\n";
1157 $OUT .= " </SELECT>\n";
1161 function TRANSLATE_YESNO($yn)
1165 case 'Y': $yn = YES; break;
1166 case 'N': $yn = NO; break;
1167 default : $yn = "??? (".$yn.")"; break;
1172 // Deprecated : $length
1175 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="")
1179 // Build server string
1180 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1183 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']).":".$_CONFIG['master_salt'];
1185 // Build string from misc data
1186 $data = $code.":".$uid.":".$DATA;
1188 // Add more additional data
1189 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1190 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1191 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1192 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1193 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1194 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1196 // Calculate number for generating the code
1197 $a = $code + _ADD - 1;
1199 // Generate hash with master salt from modula of number with the prime number and other data
1200 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1202 // Create number from hash
1203 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1205 // At least 10 numbers shall be secure enought!
1206 $len = $_CONFIG['code_length'];
1207 if ($len == 0) $len = 10;
1209 // Cut off requested counts of number
1210 $return = substr(str_replace('.', '', $rcode), 0, $len);
1212 // Done building code
1215 // Does only allow numbers
1216 function bigintval($num)
1218 $ret = (int) preg_replace("/[^0123456789]/", "", $num);
1221 // Insert the code in $img_code into jpeg or PNG image
1222 function GENERATE_IMAGE($img_code, $header=true)
1225 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0))
1227 // Stop execution of function here because of over-sized code length
1232 // Return in an HTML code code
1233 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1236 switch ($_CONFIG['img_type'])
1240 $img = PATH."/theme/".GET_CURR_THEME()."/images/code_bg.jpg";
1241 if ((file_exists($img)) && (is_readable($img)))
1243 // Okay, load image and hide all errors
1244 $image = @imagecreatefromjpeg($img);
1248 // Exit function here
1255 $img = PATH."/theme/".GET_CURR_THEME()."/images/code_bg.png";
1256 if ((file_exists($img)) && (is_readable($img)))
1258 // Okay, load image and hide all errors
1259 $image = @imagecreatefrompng($img);
1263 // Exit function here
1269 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1270 $text_color = imagecolorallocate($image, 0, 0, 0);
1272 // Insert code into image
1273 imagestring($image, 5, 14, 2, $img_code, $text_color);
1275 // Return to browser
1276 header ("Content-Type: image/".$_CONFIG['img_type']);
1278 // Output image with matching image factory
1279 switch ($_CONFIG['img_type'])
1281 case "jpg": imagejpeg($image); break;
1282 case "png": imagepng($image); break;
1285 // Remove image from memory
1286 imagedestroy($image);
1288 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false)
1290 // Calculate 15-seconds timestamp (15-seconds-steps shall be fine ;) )
1291 $timestamp = round($timestamp / 15) * 15;
1292 // Do we have a leap year?
1294 $TEST = date('Y', time()) / 4;
1295 $M1 = date("m", time());
1296 $M2 = date("m", (time() + $timestamp));
1297 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1298 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1299 // First of all years...
1300 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1302 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1304 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1306 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1308 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1310 $m = abs(floor($timestamp / 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));
1311 // And at last seconds...
1312 $s = abs(floor($timestamp - $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));
1314 // Now we convert them in seconds...
1318 // Just put all data in an array for later use
1332 $OUT = "<DIV align=\"".$align."\">\n";
1333 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1335 if (ereg('Y', $display) || (empty($display)))
1337 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1339 if (ereg("M", $display) || (empty($display)))
1341 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1343 if (ereg("W", $display) || (empty($display)))
1345 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1347 if (ereg("D", $display) || (empty($display)))
1349 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1351 if (ereg("h", $display) || (empty($display)))
1353 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1355 if (ereg("m", $display) || (empty($display)))
1357 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1359 if (ereg("s", $display) || (empty($display)))
1361 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">".SECS."</STRONG></TD>\n";
1365 if (ereg('Y', $display) || (empty($display)))
1367 // Generate year selection
1368 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1369 for ($idx = 0; $idx <= 10; $idx++)
1371 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1372 if ($idx == $Y) $OUT .= " selected default";
1373 $OUT .= ">".$idx."</OPTION>\n";
1375 $OUT .= " </SELECT></TD>\n";
1379 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1381 if (ereg("M", $display) || (empty($display)))
1383 // Generate month selection
1384 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1385 for ($idx = 0; $idx <= 11; $idx++)
1387 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1388 if ($idx == $M) $OUT .= " selected default";
1389 $OUT .= ">".$idx."</OPTION>\n";
1391 $OUT .= " </SELECT></TD>\n";
1395 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1397 if (ereg("W", $display) || (empty($display)))
1399 // Generate week selection
1400 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1401 for ($idx = 0; $idx <= 4; $idx++)
1403 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1404 if ($idx == $W) $OUT .= " selected default";
1405 $OUT .= ">".$idx."</OPTION>\n";
1407 $OUT .= " </SELECT></TD>\n";
1411 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1413 if (ereg("D", $display) || (empty($display)))
1415 // Generate day selection
1416 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1417 for ($idx = 0; $idx <= 31; $idx++)
1419 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1420 if ($idx == $D) $OUT .= " selected default";
1421 $OUT .= ">".$idx."</OPTION>\n";
1423 $OUT .= " </SELECT></TD>\n";
1427 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1429 if (ereg("h", $display) || (empty($display)))
1431 // Generate hour selection
1432 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1433 for ($idx = 0; $idx <= 23; $idx++)
1435 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1436 if ($idx == $h) $OUT .= " selected default";
1437 $OUT .= ">".$idx."</OPTION>\n";
1439 $OUT .= " </SELECT></TD>\n";
1443 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1445 if (ereg("m", $display) || (empty($display)))
1447 // Generate minute selection
1448 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1449 for ($idx = 0; $idx <= 59; $idx++)
1451 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1452 if ($idx == $m) $OUT .= " selected default";
1453 $OUT .= ">".$idx."</OPTION>\n";
1455 $OUT .= " </SELECT></TD>\n";
1459 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1461 if (ereg("s", $display) || (empty($display)))
1463 // Generate second selection
1464 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1465 for ($idx = 0; $idx <= 45; $idx+=15)
1467 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1468 if ($idx == $s) $OUT .= " selected default";
1469 $OUT .= ">".$idx."</OPTION>\n";
1471 $OUT .= " </SELECT></TD>\n";
1475 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1478 $OUT .= "</TABLE>\n";
1480 // Return generated HTML code
1485 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1487 // Do we have a leap year?
1489 $TEST = date('Y', time()) / 4;
1490 $M1 = date("m", time());
1491 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1492 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1493 // First add years...
1494 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1496 $ret += $POST[$prefix."_mo"] * 2628000;
1498 $ret += $POST[$prefix."_we"] * 604800;
1500 $ret += $POST[$prefix."_da"] * 86400;
1502 $ret += $POST[$prefix."_ho"] * 3600;
1504 $ret += $POST[$prefix."_mi"] * 60;
1505 // And at last seconds...
1506 $ret += $POST[$prefix."_se"];
1507 // Return calculated value
1510 // Sends out mail to all administrators
1511 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content="", $UID="0") {
1512 // Trim template name
1513 $template = trim($template);
1515 // Load email template
1516 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1518 if (GET_EXT_VERSION("admins") < "0.4.0") {
1519 // Older version detected!
1520 return SEND_ADMIN_EMAILS($subj, $msg);
1523 // Check which admin shall receive this mail
1524 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1525 array($template), __FILE__, __LINE__);
1526 if (SQL_NUMROWS($result) == 0) {
1527 // Create new entry (to all admins)
1528 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1529 array($template), __FILE__, __LINE__);
1531 // Load admin IDs...
1533 while(list($aid) = SQL_FETCHROW($result)) {
1538 SQL_FREERESULT($result);
1540 // "implode" IDs and query string
1541 $aid = implode(",", $aids);
1543 // Add line to userlog
1544 USERLOG_ADD_LINE($subj, $msg, $UID);
1546 } elseif ($aid == "0") {
1547 // Select all email adresses
1548 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1550 // If Admin-ID is not "to-all" select
1551 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1555 // Load email addresses and send away
1556 while (list($email) = SQL_FETCHROW($result)) {
1557 SEND_EMAIL($email, $subj, $msg);
1561 SQL_FREERESULT($result);
1564 function CREATE_FANCY_TIME($stamp) {
1565 // Get data array with years/months/weeks/days/...
1566 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1568 foreach($data as $k=>$v) {
1570 // Value is greater than 0 "eval" data to return string
1571 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1577 // Remove first "comma,null" string
1578 $ret = substr($ret, 2);
1582 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1583 $SEP = ""; $TOP = "";
1586 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1590 for ($page = 1; $page <= $PAGES; $page++) {
1591 // Is the page currently selected or shall we generate a link to it?
1592 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1593 // Is currently selected, so only highlight it
1594 $NAV .= "<STRONG>-";
1596 // Open anchor tag and add base URL
1597 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1599 // Add userid when we shall show all mails from a single member
1600 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1602 // Close open anchor tag
1606 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1607 // Is currently selected, so only highlight it
1608 $NAV .= "-</STRONG>";
1614 // Add seperator if we have not yet reached total pages
1615 if ($page < $PAGES) $NAV .= " | ";
1618 // Define constants only once
1619 if (!defined('__NAV_OUTPUT')) {
1620 define('__NAV_OUTPUT' , $NAV);
1621 define('__NAV_COLSPAN', $colspan);
1622 define('__NAV_TOP' , $TOP);
1623 define('__NAV_SEP' , $SEP);
1626 // Load navigation template
1627 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1630 // Return generated HTML-Code
1639 function MXCHANGE_OPEN($script) {
1640 // Compile the script name
1641 $script = COMPILE_CODE($script);
1643 // Use default SERVER_URL by default... ;) So?
1645 if (substr($script, 0, 7) == "http://") {
1646 // Use the hostname from script URL as new hostname
1647 $url = substr($script, 7);
1648 $extract = explode("/", $url);
1650 // Done extracting the URL :)
1653 // Extract host name
1654 $host = str_replace("http://", "", $url);
1655 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1657 // Generate relative URL
1658 $script = substr($script, (strlen($url) + 7));
1659 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1662 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1666 return array("", "", "");
1669 // Generate request header
1670 $request = "GET /".trim($script)." HTTP/1.0\r\n";
1671 $request .= "Host: ".$host."\r\n";
1672 $request .= "Referer: ".URL."/admin.php\r\n";
1673 $request .= "User-Agent: ".TITLE."/".FULL_VERSION."\r\n\r\n";
1676 $response = array();
1679 fputs($fp, $request);
1683 $response[] = fgets($fp, 1024);
1689 // Was the request successfull?
1690 if ((!ereg("200 OK", $response[0])) && (empty($response[0]))) {
1691 // Not found / access forbidden
1692 $response = array("", "", "");
1698 // Taken from www.php.net eregi() user comments
1699 function VALIDATE_EMAIL($email) {
1701 $email = COMPILE_CODE($email);
1703 // Check first part of email address
1704 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1707 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1710 $regex = "^".$first."@".$domain."$";
1712 // Return check result
1713 return eregi($regex, $email);
1715 // Function taken from user comments on www.php.net / function eregi()
1716 function VALIDATE_URL ($URL, $compile=true) {
1717 // Trim URL a little
1718 $URL = trim(urldecode($URL));
1719 //* DEBUG: */ echo $URL."<br />";
1721 // Compile some chars out...
1722 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1723 //* DEBUG: */ echo $URL."<br />";
1725 // Check for the extension filter
1726 if (EXT_IS_ACTIVE("filter")) {
1727 // Use the extension's filter set
1728 return FILTER_VALIDATE_URL($URL, false);
1731 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1732 // https:// in front of the URLs
1733 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1736 function MEMBER_ACTION_LINKS($uid, $status="") {
1737 // Define all main targets
1738 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1740 // Begin of navigation links
1741 $eval = "\$OUT = \"[ ";
1743 foreach ($TARGETS as $tar) {
1744 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1745 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1746 if (($tar == "lock_user") && ($status == "LOCKED")) {
1747 // Locked accounts shall be unlocked
1748 $eval .= "UNLOCK_USER";
1750 // All other status is fine
1751 $eval .= strtoupper($tar);
1753 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1754 if (($tar == "lock_user") && ($status == "LOCKED")) {
1755 // Locked accounts shall be unlocked
1756 $eval .= "UNLOCK_USER";
1758 // All other status is fine
1759 $eval .= strtoupper($tar);
1761 $eval .= ".\"</A></SPAN> | ";
1764 // Finish navigation link
1765 $eval = substr($eval, 0, -7) . "]\";";
1771 // Function for backward-compatiblity
1772 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1773 // Load it from the register extension
1774 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1776 // Generate an email link
1777 function CREATE_EMAIL_LINK($email, $table="admins") {
1778 // Default email link (INSECURE! Spammer can read this by harvester programs)
1779 $EMAIL = "mailto:".$email;
1781 // Check for several extensions
1782 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1783 // Create email link for contacting admin in guest area
1784 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1785 } elseif ((GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1786 // Create email link for contacting a member within admin area (or later in other areas, too?)
1787 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1788 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1789 // Create email link to contact sponsor within admin area (or like the link above?)
1790 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1793 // Shall I close the link when there is no admin?
1794 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1796 // Return email link
1799 // Generate a hash for extra-security for all passwords
1800 function generateHash($plainText, $salt = "") {
1801 global $_CONFIG, $_SERVER;
1803 // Is the required extension "sql_patches" there?
1804 if ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) {
1805 // Extension sql_patches is missing/outdated so we return the plain text
1809 // When the salt is empty build a new one, else use the first x configured characters as the salt
1811 // Build server string
1812 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1815 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']).":".$_CONFIG['master_salt'];
1818 $data = $plainText.":".uniqid(rand(), true).":".time();
1820 // Calculate number for generating the code
1821 $a = time() + _ADD - 1;
1823 // Generate SHA1 sum from modula of number and the prime number
1824 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1825 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br>";
1826 $sha1 = scrambleString($sha1);
1827 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br>";
1828 //* DEBUG: */ $sha1b = descrambleString($sha1);
1829 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br>";
1831 // Generate the password salt string
1832 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1833 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1837 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1841 return $salt . sha1($salt . $plainText);
1844 function scrambleString($str) {
1850 // Final check, in case of failture it will return unscrambled string
1851 if (strlen($str) > 40) {
1852 // The string is to long
1854 } elseif (strlen($str) == 40) {
1856 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1858 // Generate new numbers
1859 $scrambleNums = explode(":", genScrambleString(strlen($str)));
1862 // Scramble string here
1863 //* DEBUG: */ echo "***Original=".$str."***<br />";
1864 for ($idx = 0; $idx < strlen($str); $idx++) {
1865 // Get char on scrambled position
1866 $char = substr($str, $scrambleNums[$idx], 1);
1868 // Add it to final output string
1869 $scrambled .= $char;
1872 // Return scrambled string
1873 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
1877 function descrambleString($str)
1880 // Scramble only 40 chars long strings
1881 if (strlen($str) != 40) return $str;
1883 // Load numbers from config
1884 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1887 if (count($scrambleNums) != 40) return $str;
1889 // Begin descrambling
1890 $orig = str_repeat(" ", 40);
1891 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
1892 for ($idx = 0; $idx < 40; $idx++)
1894 $char = substr($str, $idx, 1);
1895 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1898 // Return scrambled string
1899 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
1903 function genScrambleString($len) {
1904 // Prepare randomizer and array for the numbers
1905 mt_srand((double) microtime() * 1000000);
1906 $scrambleNumbers = array();
1908 // First we need to setup randomized numbers from 0 to 31
1909 for ($idx = 0; $idx < $len; $idx++) {
1911 $rand = mt_rand(0, ($len -1));
1913 // Check for it by creating more numbers
1914 while (array_key_exists($rand, $scrambleNumbers)) {
1915 $rand = mt_rand(0, ($len -1));
1919 $scrambleNumbers[$rand] = $rand;
1922 // So let's create the string for storing it in database
1923 $scrambleString = implode(":", $scrambleNumbers);
1924 return $scrambleString;
1926 // Append data like session ID referral ID to the given URL which would
1927 // normally be stored in cookies
1928 function ADD_URL_DATA($URL)
1933 // Determine URL binder
1935 if (strpos($URL, "?") !== false) $BIND = "&";
1937 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
1938 // Cookies are not accepted
1939 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
1940 // Cookie found in URL
1941 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
1942 } elseif ((GET_EXT_VERSION("sql_patches") != "") && ($_CONFIG['def_refid'] > 0)) {
1943 // Not found! So let's set default here
1944 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
1947 // Is there already added data? Then change the binder
1948 if (!empty($ADD)) $BIND = "&";
1951 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
1952 // Add session from URL
1953 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
1955 // Add current session
1956 $ADD .= $BIND."PHPSESSID=".session_id();
1960 // Add all together and return it
1964 function generatePassString($passHash) {
1967 // Return vanilla password hash
1970 // Is a secret key and master salt already initialized?
1971 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
1972 // Only calculate when the secret key is generated
1973 $newHash = ""; $start = 9;
1974 for ($idx = 0; $idx < 10; $idx++) {
1975 $part1 = hexdec(substr($passHash, $start, 4));
1976 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
1977 $mod = dechex($idx);
1978 if ($part1 > $part2) {
1979 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
1980 } elseif ($part2 > $part1) {
1981 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
1983 $mod = substr(round($mod), 0, 4);
1984 $mod = str_repeat('0', 4-strlen($mod)).$mod;
1985 //* DEBUG: */ echo "*".$start."=".$mod."*<br>";
1990 //* DEBUG: */ die($passHash."<br>".$newHash." (".strlen($newHash).")");
1991 $ret = generateHash($newHash, $_CONFIG['master_salt']);
1997 // Fix "deleted" cookies
1998 function FIX_DELETED_COOKIES ($cookies) {
1999 // Is this an array with entries?
2000 if ((is_array($cookies)) && (count($cookies) > 0)) {
2001 // Then check all cookies if they are marked as deleted!
2002 foreach ($cookies as $cookieName) {
2003 // Is the cookie set to "deleted"?
2004 if (get_session($cookieName) == "deleted") {
2005 set_session($cookieName, "");
2010 // Output error messages in a fasioned way and die...
2011 function mxchange_die ($msg) {
2014 // Load the message template
2015 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2018 include(PATH."inc/footer.php");
2024 // Display parsing time and number of SQL queries in footer
2025 function DISPLAY_PARSING_TIME_FOOTER() {
2026 global $startTime, $_CONFIG;
2027 $endTime = microtime(true);
2029 // Is the timer started?
2030 if (!isset($GLOBALS['startTime'])) {
2035 // "Explode" both times
2036 $start = explode(" ", $GLOBALS['startTime']);
2037 $end = explode(" ", $endTime);
2038 $runTime = $end[0] - $start[0];
2039 if ($runTime < 0) $runTime = 0;
2040 $runTime = TRANSLATE_COMMA($runTime);
2044 'runtime' => $runTime,
2045 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2046 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2049 // Load the template
2050 LOAD_TEMPLATE("footer_stats", false, $content);
2053 // Unset/set session variables
2054 function set_session ($var, $value) {
2056 // Abort in CSS mode here
2057 if ($CSS == 1) return true;
2059 // Trim value and session variable
2060 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2062 // Is the session variable set?
2063 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2064 // Remove the session
2065 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2066 unset($_SESSION[$var]);
2067 return session_unregister($var);
2068 } elseif (("".$value."" != "") && (!isSessionVariableSet($var))) {
2070 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2071 $_SESSION[$var] = $value;
2072 return session_register($var);
2075 // Return always true if the session variable is already set.
2076 // Keept me busy for a longer while...
2077 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2080 // Check wether a boolean constant is set
2081 // Taken from user comments in PHP documentation for function constant()
2082 function isBooleanConstantAndTrue($constname) { // : Boolean
2084 if (defined($constname)) $res = (constant($constname) === true);
2088 // Check wether a session variable is set
2089 function isSessionVariableSet($var) {
2090 return (isset($_SESSION[$var]));
2093 // Returns wether the value of the session variable or NULL if not set
2094 function get_session($var) {
2095 if (!isset($_SESSION)) session_start();
2097 // Default is not found! ;-)
2100 // Is the variable there?
2101 if (isSessionVariableSet($var)) {
2102 // Then get it secured!
2103 $value = SQL_ESCAPE($_SESSION[$var]);
2111 //////////////////////////////////////////////
2113 // AUTOMATICALLY RE-GNERATED FUNCTIONS ONLY //
2115 //////////////////////////////////////////////
2117 if (!function_exists('html_entity_decode'))
2119 // Taken from documentation on www.php.net
2120 function html_entity_decode($string)
2122 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2123 $trans_tbl = array_flip($trans_tbl);
2124 return strtr($string, $trans_tbl);