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."\"";
74 $OUT .= ">\n<TR>\n<TD";
75 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
76 $OUT .= " class=\"".$CLASS."\">";
80 // Close a table (you may want to add some footer stuff here)
81 function CLOSE_TABLE($ADD="") {
82 OUTPUT_HTML(" </TD>\n</TR>");
83 if (!empty($ADD)) OUTPUT_HTML($ADD);
84 OUTPUT_HTML("</TABLE>");
87 // Output HTML code directly or "render" it. You addionally switch the new-line character off
88 function OUTPUT_HTML($HTML, $NEW_LINE = true) {
89 // Some global variables
90 global $OUTPUT, $footer, $CSS;
92 // Do we have HTML-Code here?
94 // Yes, so we handle it as you have configured
98 // That's why you don't need any \n at the end of your HTML code... :-)
99 if (_OB_CACHING == "on") {
100 // Output into PHP's internal buffer
103 // That's why you don't need any \n at the end of your HTML code... :-)
104 if ($NEW_LINE) echo "\n";
106 // Render mode for old or lame servers...
109 // That's why you don't need any \n at the end of your HTML code... :-)
110 if ($NEW_LINE) $OUTPUT .= "\n";
115 // If we are switching from render to direct output rendered code
116 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
118 // The same as above... ^
120 if ($NEW_LINE) echo "\n";
124 // Huh, something goes wrong or maybe you have edited config.php ???
125 die ("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
128 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
129 // Output cached HTML code
130 $OUTPUT = ob_get_contents();
132 // Clear output buffer for later output
135 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
136 $OUTPUT = REWRITE_LINKS($OUTPUT);
139 // Compile and run finished rendered HTML code
140 while (strpos($OUTPUT, '{!') > 0) {
141 $eval = "\$OUTPUT = \"" . COMPILE_CODE(addslashes($OUTPUT)) . "\";";
145 // Output code here, DO NOT REMOVE! ;-)
147 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
148 // Rewrite links when rewrite extension is active
149 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
150 $OUTPUT = REWRITE_LINKS($OUTPUT);
153 // Compile and run finished rendered HTML code
154 while (strpos($OUTPUT, '{!') > 0) {
155 $eval = "\$OUTPUT = \"" . COMPILE_CODE(addslashes($OUTPUT)) . "\";";
159 // Output code here, DO NOT REMOVE! ;-)
164 // Output the raw HTML code
165 function OUTPUT_RAW ($HTML) {
166 if ((isBooleanConstantAndTrue('mxchange_installed')) && (basename($_SERVER['PHP_SELF']) != "install.php")) {
167 // Not in install-mode so strip slashes away
168 echo stripslashes($HTML);
170 // Output directly in install-mode
178 // Add a fatal error message to the queue array
179 function ADD_FATAL ($message, $extra="") {
182 // Regular text message to add to $FATAL
185 // $message is text with a mask plus extras to insert into the text
186 $FATAL[] = sprintf($message, $extra);
190 // Load a template file and return it's content (only it's name; do not use ' or ")
191 function LOAD_TEMPLATE($template, $return=false, $content="") {
192 // Add more variables which you want to use in your template files
193 global $DATA, $_CONFIG, $username;
195 // Count the template load
196 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
197 $_CONFIG['num_templates']++;
200 $ACTION = SQL_ESCAPE($GLOBALS['action']);
201 $WHAT = SQL_ESCAPE($GLOBALS['what']);
203 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
204 $REFID = $GLOBALS['refid'];
206 if ($template == "member_support_form") {
207 // Support request of a member
208 $result = SQL_QUERY_ESC("SELECT sex, surname, family FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
209 array($GLOBALS['userid']), __FILE__, __LINE__);
210 list($sex, $surname, $family) = SQL_FETCHROW($result);
211 SQL_FREERESULT($result);
212 $salut = TRANSLATE_SEX($sex);
215 // Generate date/time string
216 $date_time = MAKE_DATETIME(time(), "1");
219 $BASE = PATH."templates/".GET_LANGUAGE()."/html/";
222 // Check for admin/guest/member templates
223 if (strpos($template, "admin_") > -1) {
224 // Admin template found
226 } elseif (strpos($template, "guest_") > -1) {
227 // Guest template found
229 } elseif (strpos($template, "member_") > -1) {
230 // Member template found
232 } elseif (strpos($template, "install_") > -1) {
233 // Installation template found
235 } elseif (strpos($template, "ext_") > -1) {
236 // Extension template found
238 } elseif (strpos($template, "la_") > -1) {
239 // "Logical-area" template found
242 // Test for extension
243 $test = substr($template, 0, strpos($template, "_"));
244 if (EXT_IS_ACTIVE($test)) {
245 // Set extra path to extension's name
250 ////////////////////////
251 // Generate file name //
252 ////////////////////////
253 $file = $BASE.$MODE.$template.".tpl";
255 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
256 // Select what depended header/footer template file for admin/guest/member area
257 $file2 = sprintf("%s%s%s_%s.tpl",
261 SQL_ESCAPE($GLOBALS['what'])
265 if (file_exists($file2)) $file = $file2;
267 // Remove variable from memory
271 // Does the special template exists?
272 if ((!file_exists($file)) || (!is_readable($file))) {
273 // Reset to default template
274 $file = $BASE.$template.".tpl";
277 // Now does the final template exists?
278 if ((file_exists($file)) && (is_readable($file))) {
279 // The local file does exists so we load it. :)
280 $tmpl_file = implode("", file($file));
282 // Replace ' to our own chars to preventing them being quoted
283 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
285 // Do we have to compile the code?
286 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
288 $tmpl_file = "\$ret=\"" . COMPILE_CODE(addslashes($tmpl_file)) . "\";";
291 // Simply return loaded code
295 // Add surrounding HTML comments to help finding bugs faster
296 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
297 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
298 // Only admins shall see this warning or when installation mode is active
299 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
300 (".basename($file).")<br />
303 <PRE>".print_r($content, true)."</PRE>
305 <PRE>".print_r($DATA, true)."</PRE>
309 // Do we have some content to output or return?
311 // Not empty so let's put it out! ;)
313 // Return the HTML code
319 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
320 // Warning, empty output!
321 return "E:".$template."<br />\n";
325 // Send mail out to an email address
326 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML='N', $FROM="") {
327 // Compile subject line (for POINTS constant etc.)
328 $eval = "\$SUBJECT = \"" . COMPILE_CODE(addslashes($SUBJECT)) . "\";";
330 $SUBJECT = html_entity_decode($SUBJECT);
333 if (!eregi("@", $TO)) {
334 // Value detected, load email from database
335 if (EXT_IS_ACTIVE("msg")) {
336 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
339 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
340 list($TO) = SQL_FETCHROW($result_email);
341 SQL_FREERESULT($result_email);
345 // Not in PHPMailer-Mode
346 if (!CHECK_PHPMAILER_USAGE()) {
348 // Load email header template
349 $FROM = LOAD_EMAIL_TEMPLATE("header");
352 $FROM .= LOAD_EMAIL_TEMPLATE("header");
354 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
356 // Load email header template
357 $FROM = LOAD_EMAIL_TEMPLATE("header");
360 $FROM .= LOAD_EMAIL_TEMPLATE("header");
364 // Fix HTML parameter (default is no!)
365 if (empty($HTML)) $HTML = 'N';
366 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
367 // In debug mode we want to display the mail instead of sending it away so we can debug this part
369 ".htmlentities(trim($FROM))."
371 Subject : ".$SUBJECT."
374 } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE("html_mail", true))) {
375 // Send mail as HTML away
376 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
377 } elseif (!empty($TO)) {
379 $TO = COMPILE_CODE($TO);
382 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
383 } elseif ($HTML == 'N') {
385 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
389 // Check if legacy or PHPMailer command
391 function CHECK_PHPMAILER_USAGE() {
392 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
396 * Send out a raw email with PHPMailer class or legacy mail() command
398 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
399 // Shall we use PHPMailer class or legacy mode?
400 if (CHECK_PHPMAILER_USAGE()) {
401 // Use PHPMailer class with SMTP enabled
402 require_once(PATH."inc/phpmailer/class.phpmailer.php");
403 require_once(PATH."inc/phpmailer/class.smtp.php");
406 $mail = new PHPMailer();
407 $mail->PluginDir = PATH."inc/phpmailer/";
410 $mail->SMTPAuth = true;
411 $mail->Host = SMTP_HOSTNAME;
413 $mail->Username = SMTP_USER;
414 $mail->Password = SMTP_PASSWORD;
416 $mail->FromName = MAIN_TITLE;
417 $mail->Subject = $subject;
418 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
420 $mail->AltBody = "Your mail program required HTML support to read this mail!";
421 $mail->WordWrap = 70;
426 $mail->AddAddress($to, "");
427 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
428 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
429 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
432 // Use legacy mail() command
433 @mail($to, $subject, $msg, $from);
438 // Generate a password in a specified length or use default password length
439 function GEN_PASS($LEN = 0) {
441 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
443 // Initialize array with all allowed chars
444 $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,-,+,_,/");
446 // Initialize randomizer
447 mt_srand((double) microtime() * 1000000);
449 // Start creating password
451 for ($i = 0; $i < $LEN; $i++) {
452 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
455 // When the size is below 40 we can also add additional security by scrambling it
456 if (strlen($PASS) <= 40) {
457 // Also scramble the password
458 $PASS = scrambleString($PASS);
461 // Return the password
465 function MAKE_DATETIME($time, $mode="0")
469 return NEVER_HAPPENED;
471 // Filter out numbers
472 $time = bigintval($time);
475 switch (GET_LANGUAGE())
477 case "de": // German date / time format
480 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
481 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
482 case "2": $ret = date("d.m.Y|H:i", $time); break;
483 case "3": $ret = date("d.m.Y", $time); break;
487 default: // Default is the US date / time format!
490 case "0": $ret = date("r", $time); break;
491 case "1": $ret = date("Y-m-d - g:i A", $time); break;
492 case "2": $ret = date("y-m-d|H:i", $time); break;
493 case "3": $ret = date("y-m-d", $time); break;
499 // Translates the american decimal dot into a german comma
500 function TRANSLATE_COMMA($dotted, $cut=true)
503 // Default is 3 you can change this in admin area "Misc -> Misc Options"
504 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
505 if (!ereg("\.", $dotted)) $dotted .= ".".str_repeat("0", $_CONFIG['max_comma']);
507 // Remove trailing zeros
508 $dot = str_replace(".", "x", $dotted);
509 while(substr($dot, -1, 1) == "0") {
510 $dot = substr($dot, 0, -1);
513 if (substr($dot, -1, 1) == "x") {
514 // Last char is the 'x'
515 $dotted = substr($dot, 0, -1);
517 // Last char is a number
518 $dotted = str_replace("x", ".", $dot);
523 switch (GET_LANGUAGE()) {
525 $pos = strpos($dotted, ".");
528 // Cut x numbers behind comma
529 $dotted = str_replace(".", ",", substr($dotted, 0, ($pos + $_CONFIG['max_comma'] + 1)));
531 // Replace comma with dot
532 $dotted = str_replace(".", ",", $dotted);
536 $dotted = "0,".str_repeat("0", $_CONFIG['max_comma']);
538 $dotted .= ",".str_repeat("0", $_CONFIG['max_comma']);
546 $dotted = substr($dotted, 0, ($pos + $_CONFIG['max_comma'] + 1));
548 $dotted .= ".".str_repeat("0", $_CONFIG['max_comma']);
557 function DEREFERER($URL) {
558 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(COMPILE_CODE($URL)));
563 function TRANSLATE_SEX($sex) {
566 case "M": $ret = SEX_M; break;
567 case "F": $ret = SEX_F; break;
568 case "C": $ret = SEX_C; break;
569 default : $ret = $sex; break;
574 function GET_POOL_TYPE($PT)
578 case "TEMP" : $ret = POOL_TEMP; break;
579 case "SEND" : $ret = POOL_SEND; break;
580 case "NEW" : $ret = POOL_NEW; break;
581 case "ADMIN" : $ret = POOL_ADMIN; break;
582 case "ACTIVE" : $ret = POOL_ACTIVE; break;
583 case "DELETED": $ret = POOL_DELETED; break;
584 default : $ret = POOL_UNKNOWN." (".$PT.")"; break;
589 function FRAMETESTER($URL)
592 $URL = URL."/modules.php?module=frametester&url=".urlencode(base64_encode(COMPILE_CODE($URL)));
596 function SELECTION_COUNT($array)
599 if (is_array($array))
601 foreach ($array as $key=>$sel)
603 if (!empty($sel)) $ret++;
609 function IMG_CODE ($code, $type, $DATA, $uid)
611 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
614 function TRANSLATE_STATUS($status)
619 $ret = ACCOUNT_UNCONFIRMED;
623 $ret = ACCOUNT_CONFIRMED;
627 $ret = ACCOUNT_LOCKED;
631 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
637 function GET_LANGUAGE() {
638 if (!empty($_GET['mx_lang'])) {
639 // Accept only first 2 chars
640 $lang = substr($_GET['mx_lang'], 0, 2);
646 // Set default return value to default language from config
649 // Check GET variable and cookie
651 // Check if main language file does exist
652 if (file_exists(PATH."inc/language/".$lang.".php")) {
653 // Okay found, so let's update cookies
656 } elseif (!isSessionVariableSet('mx_lang')) {
657 // Return stored value from cookie
658 $ret = get_session('mx_lang');
660 // Fixes a warning before the session has the mx_lang constant
661 if (empty($ret)) $ret = DEFAULT_LANG;
666 function SET_LANGUAGE($lang) {
669 // Accept only first 2 chars!
670 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
673 set_session("mx_lang", $lang);
676 function LOAD_EMAIL_TEMPLATE($template, $content="", $UID="0") {
677 global $DATA, $_CONFIG, $REPLACER;
679 // Keept for backward-compatiblity (please replace these variables against our new {--CONST--} syntax!)
680 $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
681 $surname = ""; $family = ""; $nick = ""; $sex = 'N';
683 // Prepare IP number and User Agent
684 $REMOTE_ADDR = getenv('REMOTE_ADDR');
685 $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
688 if (isSessionVariableSet('admin_login')) {
690 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
691 array(SQL_ESCAPE(get_session('admin_login'))), __FILE__, __LINE__);
692 list($ADMIN) = SQL_FETCHROW($result);
693 SQL_FREERESULT($result);
696 // Expiration in a nice output format
697 if ($_CONFIG['auto_purge'] == 0) {
698 // Will never expire!
699 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
700 } elseif (function_exists('CREATE_FANCY_TIME')) {
701 // Create nice date string
702 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
705 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
710 case "bonus-mail": // Load data for the bonus mail
713 $points = TRANSLATE_COMMA($DATA[4]);
715 $TARGET_URL = $DATA[8];
716 $CATEGORY = GET_CATEGORY($DATA[9]);
720 foreach ($REPLACER as $key=>$value)
722 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
728 $BLOCKS = $_CONFIG['max_send'];
731 $PAYMENT = GET_PAYMENT($DATA[3]);
732 $TARGET_URL = $DATA[5];
733 $CATEGORY = GET_CATEGORY($DATA[6]);
737 case "order-deleted":
739 $TARGET_URL = $DATA[0];
749 case "confirm-member":
750 $points = $_CONFIG['points_register'];
753 case "confirm-referral":
761 $SEND_UID = $DATA[1];
762 $CATEGORY = GET_CATEGORY($DATA[9]);
763 $TIME = GET_PAY_POINTS($DATA[5], "time");
764 $TARGET_URL = $DATA[7];
765 $points = TRANSLATE_COMMA(GET_PAY_POINTS($DATA[5], "payment"));
766 // Warning! This ID has changed from 10 to 11!
770 foreach ($REPLACER as $key=>$value)
772 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
778 $SEND_UID = $DATA[1];
779 $CATEGORY = GET_CATEGORY($DATA[9]);
780 $TARGET_URL = $DATA[7];
785 $points = TRANSLATE_COMMA($DATA[10]);
789 if (isset($_POST['points'])) {
790 $points = bigintval($_POST['points']);
792 $points = __POINTS_VALUE;
796 case "guest_request_confirm":
803 if (EXT_IS_ACTIVE("nickname")) {
805 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
806 array(bigintval($UID)), __FILE__, __LINE__);
807 list($surname, $family, $sex, $email, $nick) = SQL_FETCHROW($result);
808 SQL_FREERESULT($result);
811 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
812 array(bigintval($UID)), __FILE__, __LINE__);
813 list($surname, $family, $sex, $email) = SQL_FETCHROW($result);
814 SQL_FREERESULT($result);
818 // Neutral sex and email address is default
823 // Translate M to male or F to female
824 $salut = TRANSLATE_SEX($sex);
826 // Store email for some functions in global data array
827 $DATA['email'] = $email;
830 $BASE = PATH."templates/".GET_LANGUAGE()."/emails/";
832 // Check for admin/guest/member templates
833 if (strpos($template, "admin_") > -1) {
834 // Admin template found
835 $file = $BASE."admin/".$template.".tpl";
836 } elseif (strpos($template, "guest_") > -1) {
837 // Guest template found
838 $file = $BASE."guest/".$template.".tpl";
839 } elseif (strpos($template, "member_") > -1) {
840 // Member template found
841 $file = $BASE."member/".$template.".tpl";
843 // Test for extension
844 $test = substr($template, 0, strpos($template, "_"));
845 if (EXT_IS_ACTIVE($test)) {
846 // Set extra path to extension's name
847 $file = $BASE.$test."/".$template.".tpl";
849 // No special filename
850 $file = $BASE.$template.".tpl";
854 // Does the special template exists?
855 if ((!@file_exists($file)) || (!is_readable($file))) {
856 // Reset to default template
857 $file = $BASE.$template.".tpl";
860 // Now does the final template exists?
861 if ((@file_exists($file)) && (is_readable($file)))
863 // The local file does exists so we load it. :)
864 $tmpl_file = @implode("", @file($file));
865 $tmpl_file = addslashes($tmpl_file);
868 $tmpl_file = COMPILE_CODE($tmpl_file);
871 $tmpl_file = "\$content=\"".$tmpl_file."\";";
874 // Replace HTML confirm chars
875 $content = html_entity_decode($content);
877 elseif (!empty($template))
879 // Template file not found!
880 $content = TEMPLATE_404.": ".$template."<br />
882 <PRE>".print_r($content, true)."</PRE>
884 <PRE>".print_r($DATA, true)."</PRE>
887 // Debug mode not active? Then remove the HTML tags
888 if (!DEBUG_MODE) $content = strip_tags($content);
892 // No template name supplied!
893 $content = NO_TEMPLATE_SUPPLIED;
895 return COMPILE_CODE($content);
898 function MAKE_TIME($H, $M, $S, $stamp)
900 // Extract day, month and year from given timestamp
901 $DAY = date("d", $stamp);
902 $MONTH = date("m", $stamp);
903 $YEAR = date('Y', $stamp);
905 // Create timestamp for wished time which depends on extracted date
906 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
909 function LOAD_URL($URL, $addUrlData=true) {
910 global $CSS, $_CONFIG, $link, $db, $footer;
912 // Check if http(s):// is there
913 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
914 // Make all URLs full-qualified
918 // Compile out URI codes
919 $URL = COMPILE_CODE($URL);
922 $OUTPUT = ob_get_contents();
927 // Add some data to URL if cookies are not accepted
928 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
930 // Probe for bot from search engine
931 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
932 // Search engine bot detected so let's rewrite many chars for the link
933 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
935 // Output new location link as anchor
936 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
937 } elseif (!headers_sent()) {
938 // Load URL when headers are not sent
939 @header ("Location: ".str_replace("&", "&", $URL));
941 // Output error message
942 include(PATH."inc/header.php");
943 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
944 include(PATH."inc/footer.php");
949 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
950 global $SEC_CHARS, $URL_CHARS;
953 // Select smaller set of chars to replace when we e.g. want to compile URLs
954 if (!$full) $ARRAY = $URL_CHARS;
958 // BEFORE 0.2.1 : Language and data constants
959 // WITH 0.2.1+ : Only language constants
960 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
962 // BEFORE 0.2.1 : Not used
963 // WITH 0.2.1+ : Data constants
964 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
967 // Compile QUOT and other non-HTML codes
968 foreach ($ARRAY['to'] as $k => $to) {
969 // Do the reversed thing as in inc/libs/security_functions.php
970 $code = str_replace($to, $ARRAY['from'][$k], $code);
973 // But shall I keep simple quotes for later use?
974 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
976 // Find $content[bla][blub] entries
977 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
979 // Are some matches found?
980 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
981 // Replace all matches
982 $matchesFound = array();
983 foreach ($matches[0] as $key=>$match) {
984 // Avoid replacing matches multiple times
985 if (!isset($matchesFound[$match])) {
987 $code = str_replace($match, "\".".$match.".\"", $code);
988 $matchesFound[$match] = 1;
991 // Take all string elements
992 if (("".bigintval($matches[4][$key])."" != $matches[4][$key]) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
993 // Replace it in the code
994 $code = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $code);
995 $matchesFound[$key."_".$matches[4][$key]] = 1;
1000 // Return compiled code
1004 /************************************************************************
1006 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1007 * $a_sort sortiert: *
1009 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1010 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1011 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1012 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1013 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1015 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1016 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1017 * Sie, dass es doch nicht so schwer ist! :-) *
1019 ************************************************************************/
1020 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1023 while ($primary_key < count($a_sort))
1025 foreach ($dummy[$a_sort[$primary_key]] as $key=>$value)
1027 foreach ($dummy[$a_sort[$primary_key]] as $key2=>$value2)
1032 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1033 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1035 elseif ($key != $key2)
1037 // Sort numbers (E.g.: 9 < 10)
1038 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1039 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1043 // We have found two different values, so let's sort whole array
1044 foreach ($dummy as $sort_key=>$sort_val)
1046 $t = $dummy[$sort_key][$key];
1047 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1048 $dummy[$sort_key][$key2] = $t;
1059 // Write back sorted array
1063 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1065 global $MONTH_DESCR; $OUT = "";
1068 // This is a yes/no selection only!
1069 if ($id > 0) $prefix .= "[".$id."]";
1070 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1074 // Begin with regular selection box here
1075 if (!empty($prefix)) $prefix .= "_";
1077 if ($id > 0) $type2 .= "[".$id."]";
1078 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1083 for ($idx = 1; $idx < 32; $idx++)
1085 $OUT .= " <OPTION value=\"".$idx."\"";
1086 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1087 $OUT .= ">".$idx."</OPTION>\n";
1091 case "month": // Month
1092 foreach ($MONTH_DESCR as $month=>$descr)
1094 $OUT .= " <OPTION value=\"".$month."\"";
1095 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1096 $OUT .= ">".$descr."</OPTION>\n";
1100 case "year": // Year
1102 $YEAR = date('Y', time());
1104 // Check if the default value is larger than minimum and bigger than actual year
1105 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1107 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1109 $OUT .= " <OPTION value=\"".$idx."\"";
1110 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1111 $OUT .= ">".$idx."</OPTION>\n";
1114 elseif ($DEFAULT == -1)
1116 // Current year minus 1
1117 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1119 $OUT .= " <OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1124 // Get current year and subtract 16 (for erotic content)
1125 $OUT .= " <OPTION value=\"1929\"><1930</OPTION>\n";
1126 $YEAR = date('Y', time()) - 16;
1127 for ($idx = 1930; $idx <= $YEAR; $idx++)
1129 $OUT .= " <OPTION value=\"".$idx."\"";
1130 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1131 $OUT .= ">".$idx."</OPTION>\n";
1138 for ($idx = 0; $idx < 60; $idx+=5)
1140 if (strlen($idx) == 1) $idx = "0".$idx;
1141 $OUT .= " <OPTION value=\"".$idx."\"";
1142 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1143 $OUT .= ">".$idx."</OPTION>\n";
1148 for ($idx = 0; $idx < 24; $idx++)
1150 if (strlen($idx) == 1) $idx = "0".$idx;
1151 $OUT .= " <OPTION value=\"".$idx."\"";
1152 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1153 $OUT .= ">".$idx."</OPTION>\n";
1158 $OUT .= " <OPTION value=\"Y\"";
1159 if ($DEFAULT == 'Y') $OUT .= " selected=\"selected\"";
1160 $OUT .= ">".YES."</OPTION>
1161 <OPTION value=\"N\"";
1162 if ($DEFAULT == 'N') $OUT .= " selected=\"selected\"";
1163 $OUT .= ">".NO."</OPTION>\n";
1166 $OUT .= " </SELECT>\n";
1170 function TRANSLATE_YESNO($yn)
1174 case 'Y': $yn = YES; break;
1175 case 'N': $yn = NO; break;
1176 default : $yn = "??? (".$yn.")"; break;
1181 // Deprecated : $length
1184 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="")
1188 // Build server string
1189 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1192 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']).":".$_CONFIG['master_salt'];
1194 // Build string from misc data
1195 $data = $code.":".$uid.":".$DATA;
1197 // Add more additional data
1198 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1199 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1200 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1201 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1202 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1203 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1205 // Calculate number for generating the code
1206 $a = $code + _ADD - 1;
1208 // Generate hash with master salt from modula of number with the prime number and other data
1209 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1211 // Create number from hash
1212 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1214 // At least 10 numbers shall be secure enought!
1215 $len = $_CONFIG['code_length'];
1216 if ($len == 0) $len = 10;
1218 // Cut off requested counts of number
1219 $return = substr(str_replace('.', "", $rcode), 0, $len);
1221 // Done building code
1224 // Does only allow numbers
1225 function bigintval($num, $castValue = true)
1227 // Filter all numbers out
1228 $ret = preg_replace("/[^0123456789]/", "", $num);
1231 if ($castValue) $ret = (int) $ret;
1236 // Insert the code in $img_code into jpeg or PNG image
1237 function GENERATE_IMAGE($img_code, $header=true)
1240 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0))
1242 // Stop execution of function here because of over-sized code length
1247 // Return in an HTML code code
1248 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1251 switch ($_CONFIG['img_type'])
1255 $img = PATH."/theme/".GET_CURR_THEME()."/images/code_bg.jpg";
1256 if ((file_exists($img)) && (is_readable($img)))
1258 // Okay, load image and hide all errors
1259 $image = @imagecreatefromjpeg($img);
1263 // Exit function here
1270 $img = PATH."/theme/".GET_CURR_THEME()."/images/code_bg.png";
1271 if ((file_exists($img)) && (is_readable($img)))
1273 // Okay, load image and hide all errors
1274 $image = @imagecreatefrompng($img);
1278 // Exit function here
1284 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1285 $text_color = imagecolorallocate($image, 0, 0, 0);
1287 // Insert code into image
1288 imagestring($image, 5, 14, 2, $img_code, $text_color);
1290 // Return to browser
1291 header ("Content-Type: image/".$_CONFIG['img_type']);
1293 // Output image with matching image factory
1294 switch ($_CONFIG['img_type'])
1296 case "jpg": imagejpeg($image); break;
1297 case "png": imagepng($image); break;
1300 // Remove image from memory
1301 imagedestroy($image);
1303 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false)
1305 // Calculate 15-seconds timestamp (15-seconds-steps shall be fine ;) )
1306 $timestamp = round($timestamp / 15) * 15;
1307 // Do we have a leap year?
1309 $TEST = date('Y', time()) / 4;
1310 $M1 = date("m", time());
1311 $M2 = date("m", (time() + $timestamp));
1312 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1313 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1314 // First of all years...
1315 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1317 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1319 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1321 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1323 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1325 $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));
1326 // And at last seconds...
1327 $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));
1329 // Now we convert them in seconds...
1333 // Just put all data in an array for later use
1347 $OUT = "<DIV align=\"".$align."\">\n";
1348 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1350 if (ereg('Y', $display) || (empty($display)))
1352 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1354 if (ereg("M", $display) || (empty($display)))
1356 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1358 if (ereg("W", $display) || (empty($display)))
1360 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1362 if (ereg("D", $display) || (empty($display)))
1364 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1366 if (ereg("h", $display) || (empty($display)))
1368 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1370 if (ereg("m", $display) || (empty($display)))
1372 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1374 if (ereg("s", $display) || (empty($display)))
1376 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">".SECS."</STRONG></TD>\n";
1380 if (ereg('Y', $display) || (empty($display)))
1382 // Generate year selection
1383 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1384 for ($idx = 0; $idx <= 10; $idx++)
1386 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1387 if ($idx == $Y) $OUT .= " selected default";
1388 $OUT .= ">".$idx."</OPTION>\n";
1390 $OUT .= " </SELECT></TD>\n";
1394 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1396 if (ereg("M", $display) || (empty($display)))
1398 // Generate month selection
1399 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1400 for ($idx = 0; $idx <= 11; $idx++)
1402 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1403 if ($idx == $M) $OUT .= " selected default";
1404 $OUT .= ">".$idx."</OPTION>\n";
1406 $OUT .= " </SELECT></TD>\n";
1410 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1412 if (ereg("W", $display) || (empty($display)))
1414 // Generate week selection
1415 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1416 for ($idx = 0; $idx <= 4; $idx++)
1418 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1419 if ($idx == $W) $OUT .= " selected default";
1420 $OUT .= ">".$idx."</OPTION>\n";
1422 $OUT .= " </SELECT></TD>\n";
1426 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1428 if (ereg("D", $display) || (empty($display)))
1430 // Generate day selection
1431 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1432 for ($idx = 0; $idx <= 31; $idx++)
1434 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1435 if ($idx == $D) $OUT .= " selected default";
1436 $OUT .= ">".$idx."</OPTION>\n";
1438 $OUT .= " </SELECT></TD>\n";
1442 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1444 if (ereg("h", $display) || (empty($display)))
1446 // Generate hour selection
1447 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1448 for ($idx = 0; $idx <= 23; $idx++)
1450 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1451 if ($idx == $h) $OUT .= " selected default";
1452 $OUT .= ">".$idx."</OPTION>\n";
1454 $OUT .= " </SELECT></TD>\n";
1458 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1460 if (ereg("m", $display) || (empty($display)))
1462 // Generate minute selection
1463 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1464 for ($idx = 0; $idx <= 59; $idx++)
1466 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1467 if ($idx == $m) $OUT .= " selected default";
1468 $OUT .= ">".$idx."</OPTION>\n";
1470 $OUT .= " </SELECT></TD>\n";
1474 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1476 if (ereg("s", $display) || (empty($display)))
1478 // Generate second selection
1479 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1480 for ($idx = 0; $idx <= 45; $idx+=15)
1482 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1483 if ($idx == $s) $OUT .= " selected default";
1484 $OUT .= ">".$idx."</OPTION>\n";
1486 $OUT .= " </SELECT></TD>\n";
1490 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1493 $OUT .= "</TABLE>\n";
1495 // Return generated HTML code
1500 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1502 // Do we have a leap year?
1504 $TEST = date('Y', time()) / 4;
1505 $M1 = date("m", time());
1506 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1507 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1508 // First add years...
1509 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1511 $ret += $POST[$prefix."_mo"] * 2628000;
1513 $ret += $POST[$prefix."_we"] * 604800;
1515 $ret += $POST[$prefix."_da"] * 86400;
1517 $ret += $POST[$prefix."_ho"] * 3600;
1519 $ret += $POST[$prefix."_mi"] * 60;
1520 // And at last seconds...
1521 $ret += $POST[$prefix."_se"];
1522 // Return calculated value
1525 // Sends out mail to all administrators
1526 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content="", $UID="0") {
1527 // Trim template name
1528 $template = trim($template);
1530 // Load email template
1531 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1533 if (GET_EXT_VERSION("admins") < "0.4.0") {
1534 // Older version detected!
1535 return SEND_ADMIN_EMAILS($subj, $msg);
1538 // Check which admin shall receive this mail
1539 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1540 array($template), __FILE__, __LINE__);
1541 if (SQL_NUMROWS($result) == 0) {
1542 // Create new entry (to all admins)
1543 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1544 array($template), __FILE__, __LINE__);
1546 // Load admin IDs...
1548 while(list($aid) = SQL_FETCHROW($result)) {
1553 SQL_FREERESULT($result);
1555 // "implode" IDs and query string
1556 $aid = implode(",", $aids);
1558 // Add line to userlog
1559 USERLOG_ADD_LINE($subj, $msg, $UID);
1561 } elseif ($aid == "0") {
1562 // Select all email adresses
1563 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1565 // If Admin-ID is not "to-all" select
1566 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1570 // Load email addresses and send away
1571 while (list($email) = SQL_FETCHROW($result)) {
1572 SEND_EMAIL($email, $subj, $msg);
1576 SQL_FREERESULT($result);
1579 function CREATE_FANCY_TIME($stamp) {
1580 // Get data array with years/months/weeks/days/...
1581 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1583 foreach($data as $k=>$v) {
1585 // Value is greater than 0 "eval" data to return string
1586 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1592 // Remove first "comma,null" string
1593 $ret = substr($ret, 2);
1597 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1598 $SEP = ""; $TOP = "";
1601 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1605 for ($page = 1; $page <= $PAGES; $page++) {
1606 // Is the page currently selected or shall we generate a link to it?
1607 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1608 // Is currently selected, so only highlight it
1609 $NAV .= "<STRONG>-";
1611 // Open anchor tag and add base URL
1612 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1614 // Add userid when we shall show all mails from a single member
1615 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1617 // Close open anchor tag
1621 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1622 // Is currently selected, so only highlight it
1623 $NAV .= "-</STRONG>";
1629 // Add seperator if we have not yet reached total pages
1630 if ($page < $PAGES) $NAV .= " | ";
1633 // Define constants only once
1634 if (!defined('__NAV_OUTPUT')) {
1635 define('__NAV_OUTPUT' , $NAV);
1636 define('__NAV_COLSPAN', $colspan);
1637 define('__NAV_TOP' , $TOP);
1638 define('__NAV_SEP' , $SEP);
1641 // Load navigation template
1642 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1645 // Return generated HTML-Code
1654 function MXCHANGE_OPEN ($script) {
1655 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1656 // Compile the script name
1657 $script = COMPILE_CODE($script);
1658 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1660 // Use default SERVER_URL by default... ;) So?
1662 if (substr($script, 0, 7) == "http://") {
1663 // Use the hostname from script URL as new hostname
1664 $url = substr($script, 7);
1665 $extract = explode("/", $url);
1667 // Done extracting the URL :)
1670 // Extract host name
1671 $host = str_replace("http://", "", $url);
1672 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1674 // Generate relative URL
1675 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1676 if (substr(strtolower($script), 0, 7) == "http://") {
1677 // But only if http:// is in front!
1678 $script = substr($script, (strlen($url) + 7));
1679 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1681 $script = substr($script, (strlen($url) + 8));
1684 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1685 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1688 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1689 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1692 return array("", "", "");
1695 // Generate request header
1696 $request = "GET /".trim($script)." HTTP/1.0\r\n";
1697 $request .= "Host: ".$host."\r\n";
1698 $request .= "Referer: ".URL."/admin.php\r\n";
1699 $request .= "User-Agent: ".TITLE."/".FULL_VERSION."\r\n\r\n";
1702 $response = array();
1705 fputs($fp, $request);
1709 $response[] = trim(fgets($fp, 1024));
1715 // Was the request successfull?
1716 if ((!ereg("200 OK", $response[0])) && (empty($response[0]))) {
1717 // Not found / access forbidden
1718 $response = array("", "", "");
1724 // Taken from www.php.net eregi() user comments
1725 function VALIDATE_EMAIL($email) {
1727 $email = COMPILE_CODE($email);
1729 // Check first part of email address
1730 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1733 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1736 $regex = "^".$first."@".$domain."$";
1738 // Return check result
1739 return eregi($regex, $email);
1741 // Function taken from user comments on www.php.net / function eregi()
1742 function VALIDATE_URL ($URL, $compile=true) {
1743 // Trim URL a little
1744 $URL = trim(urldecode($URL));
1745 //* DEBUG: */ echo $URL."<br />";
1747 // Compile some chars out...
1748 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1749 //* DEBUG: */ echo $URL."<br />";
1751 // Check for the extension filter
1752 if (EXT_IS_ACTIVE("filter")) {
1753 // Use the extension's filter set
1754 return FILTER_VALIDATE_URL($URL, false);
1757 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1758 // https:// in front of the URLs
1759 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1762 function MEMBER_ACTION_LINKS($uid, $status="") {
1763 // Define all main targets
1764 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1766 // Begin of navigation links
1767 $eval = "\$OUT = \"[ ";
1769 foreach ($TARGETS as $tar) {
1770 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1771 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1772 if (($tar == "lock_user") && ($status == "LOCKED")) {
1773 // Locked accounts shall be unlocked
1774 $eval .= "UNLOCK_USER";
1776 // All other status is fine
1777 $eval .= strtoupper($tar);
1779 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1780 if (($tar == "lock_user") && ($status == "LOCKED")) {
1781 // Locked accounts shall be unlocked
1782 $eval .= "UNLOCK_USER";
1784 // All other status is fine
1785 $eval .= strtoupper($tar);
1787 $eval .= ".\"</A></SPAN> | ";
1790 // Finish navigation link
1791 $eval = substr($eval, 0, -7) . "]\";";
1797 // Function for backward-compatiblity
1798 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1799 // Load it from the register extension
1800 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1802 // Generate an email link
1803 function CREATE_EMAIL_LINK($email, $table="admins") {
1804 // Default email link (INSECURE! Spammer can read this by harvester programs)
1805 $EMAIL = "mailto:".$email;
1807 // Check for several extensions
1808 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1809 // Create email link for contacting admin in guest area
1810 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1811 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1812 // Create email link for contacting a member within admin area (or later in other areas, too?)
1813 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1814 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1815 // Create email link to contact sponsor within admin area (or like the link above?)
1816 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1819 // Shall I close the link when there is no admin?
1820 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1822 // Return email link
1825 // Generate a hash for extra-security for all passwords
1826 function generateHash ($plainText, $salt = "") {
1827 global $_CONFIG, $_SERVER;
1829 // Is the required extension "sql_patches" there?
1830 if ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) {
1831 // Extension sql_patches is missing/outdated so we return the plain text
1835 // When the salt is empty build a new one, else use the first x configured characters as the salt
1837 // Build server string
1838 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1841 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']).":".$_CONFIG['master_salt'];
1844 $data = $plainText.":".uniqid(rand(), true).":".time();
1846 // Calculate number for generating the code
1847 $a = time() + _ADD - 1;
1849 // Generate SHA1 sum from modula of number and the prime number
1850 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1851 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br>";
1852 $sha1 = scrambleString($sha1);
1853 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br>";
1854 //* DEBUG: */ $sha1b = descrambleString($sha1);
1855 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br>";
1857 // Generate the password salt string
1858 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1859 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1863 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1867 return $salt . sha1($salt . $plainText);
1870 function scrambleString($str) {
1876 // Final check, in case of failture it will return unscrambled string
1877 if (strlen($str) > 40) {
1878 // The string is to long
1880 } elseif (strlen($str) == 40) {
1882 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1884 // Generate new numbers
1885 $scrambleNums = explode(":", genScrambleString(strlen($str)));
1888 // Scramble string here
1889 //* DEBUG: */ echo "***Original=".$str."***<br />";
1890 for ($idx = 0; $idx < strlen($str); $idx++) {
1891 // Get char on scrambled position
1892 $char = substr($str, $scrambleNums[$idx], 1);
1894 // Add it to final output string
1895 $scrambled .= $char;
1898 // Return scrambled string
1899 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
1903 function descrambleString($str)
1906 // Scramble only 40 chars long strings
1907 if (strlen($str) != 40) return $str;
1909 // Load numbers from config
1910 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1913 if (count($scrambleNums) != 40) return $str;
1915 // Begin descrambling
1916 $orig = str_repeat(" ", 40);
1917 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
1918 for ($idx = 0; $idx < 40; $idx++)
1920 $char = substr($str, $idx, 1);
1921 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1924 // Return scrambled string
1925 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
1929 function genScrambleString($len) {
1930 // Prepare randomizer and array for the numbers
1931 mt_srand((double) microtime() * 1000000);
1932 $scrambleNumbers = array();
1934 // First we need to setup randomized numbers from 0 to 31
1935 for ($idx = 0; $idx < $len; $idx++) {
1937 $rand = mt_rand(0, ($len -1));
1939 // Check for it by creating more numbers
1940 while (array_key_exists($rand, $scrambleNumbers)) {
1941 $rand = mt_rand(0, ($len -1));
1945 $scrambleNumbers[$rand] = $rand;
1948 // So let's create the string for storing it in database
1949 $scrambleString = implode(":", $scrambleNumbers);
1950 return $scrambleString;
1952 // Append data like session ID referral ID to the given URL which would
1953 // normally be stored in cookies
1954 function ADD_URL_DATA($URL)
1959 // Determine URL binder
1961 if (strpos($URL, "?") !== false) $BIND = "&";
1963 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
1964 // Cookies are not accepted
1965 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
1966 // Cookie found in URL
1967 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
1968 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
1969 // Not found! So let's set default here
1970 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
1973 // Is there already added data? Then change the binder
1974 if (!empty($ADD)) $BIND = "&";
1977 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
1978 // Add session from URL
1979 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
1981 // Add current session
1982 $ADD .= $BIND."PHPSESSID=".session_id();
1986 // Add all together and return it
1990 function generatePassString($passHash) {
1993 // Return vanilla password hash
1996 // Is a secret key and master salt already initialized?
1997 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
1998 // Only calculate when the secret key is generated
1999 $newHash = ""; $start = 9;
2000 for ($idx = 0; $idx < 10; $idx++) {
2001 $part1 = hexdec(substr($passHash, $start, 4));
2002 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2003 $mod = dechex($idx);
2004 if ($part1 > $part2) {
2005 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2006 } elseif ($part2 > $part1) {
2007 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2009 $mod = substr(round($mod), 0, 4);
2010 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2011 //* DEBUG: */ echo "*".$start."=".$mod."*<br>";
2016 //* DEBUG: */ die($passHash."<br>".$newHash." (".strlen($newHash).")");
2017 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2020 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2021 $ret = md5($passHash);
2022 //* DEBUG: */ echo "++".$ret."++<br />\n";
2028 // Fix "deleted" cookies
2029 function FIX_DELETED_COOKIES ($cookies) {
2030 // Is this an array with entries?
2031 if ((is_array($cookies)) && (count($cookies) > 0)) {
2032 // Then check all cookies if they are marked as deleted!
2033 foreach ($cookies as $cookieName) {
2034 // Is the cookie set to "deleted"?
2035 if (get_session($cookieName) == "deleted") {
2036 set_session($cookieName, "");
2041 // Output error messages in a fasioned way and die...
2042 function mxchange_die ($msg) {
2045 // Load the message template
2046 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2049 include(PATH."inc/footer.php");
2055 // Display parsing time and number of SQL queries in footer
2056 function DISPLAY_PARSING_TIME_FOOTER() {
2057 global $startTime, $_CONFIG;
2058 $endTime = microtime(true);
2060 // Is the timer started?
2061 if (!isset($GLOBALS['startTime'])) {
2066 // "Explode" both times
2067 $start = explode(" ", $GLOBALS['startTime']);
2068 $end = explode(" ", $endTime);
2069 $runTime = $end[0] - $start[0];
2070 if ($runTime < 0) $runTime = 0;
2071 $runTime = TRANSLATE_COMMA($runTime);
2075 'runtime' => $runTime,
2076 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2077 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2080 // Load the template
2081 LOAD_TEMPLATE("show_timings", false, $content);
2084 // Unset/set session variables
2085 function set_session ($var, $value) {
2087 // Abort in CSS mode here
2088 if ($CSS == 1) return true;
2090 // Trim value and session variable
2091 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2093 // Is the session variable set?
2094 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2095 // Remove the session
2096 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2097 unset($_SESSION[$var]);
2098 return session_unregister($var);
2099 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2101 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2102 $_SESSION[$var] = $value;
2103 return session_register($var);
2106 // Return always true if the session variable is already set.
2107 // Keept me busy for a longer while...
2108 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2111 // Check wether a boolean constant is set
2112 // Taken from user comments in PHP documentation for function constant()
2113 function isBooleanConstantAndTrue($constname) { // : Boolean
2115 if (defined($constname)) $res = (constant($constname) === true);
2119 // Check wether a session variable is set
2120 function isSessionVariableSet($var) {
2121 return (isset($_SESSION[$var]));
2124 // Returns wether the value of the session variable or NULL if not set
2125 function get_session($var) {
2126 if (!isset($_SESSION)) session_start();
2128 // Default is not found! ;-)
2131 // Is the variable there?
2132 if (isSessionVariableSet($var)) {
2133 // Then get it secured!
2134 $value = SQL_ESCAPE($_SESSION[$var]);
2142 //////////////////////////////////////////////
2144 // AUTOMATICALLY RE-GNERATED FUNCTIONS ONLY //
2146 //////////////////////////////////////////////
2148 if (!function_exists('html_entity_decode'))
2150 // Taken from documentation on www.php.net
2151 function html_entity_decode($string)
2153 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2154 $trans_tbl = array_flip($trans_tbl);
2155 return strtr($string, $trans_tbl);