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 // Output stripped HTML code to avoid broken JavaScript code, etc.
167 echo stripslashes($HTML);
169 // Flush the output if only _OB_CACHING is not "on"
170 if (_OB_CACHING != "on") {
176 // Add a fatal error message to the queue array
177 function ADD_FATAL ($message, $extra="") {
180 // Regular text message to add to $FATAL
183 // $message is text with a mask plus extras to insert into the text
184 $FATAL[] = sprintf($message, $extra);
188 // Load a template file and return it's content (only it's name; do not use ' or ")
189 function LOAD_TEMPLATE($template, $return=false, $content="") {
190 // Add more variables which you want to use in your template files
191 global $DATA, $_CONFIG, $username;
193 // Count the template load
194 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
195 $_CONFIG['num_templates']++;
198 $ACTION = SQL_ESCAPE($GLOBALS['action']);
199 $WHAT = SQL_ESCAPE($GLOBALS['what']);
201 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
202 $REFID = $GLOBALS['refid'];
204 if ($template == "member_support_form") {
205 // Support request of a member
206 $result = SQL_QUERY_ESC("SELECT sex, surname, family FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
207 array($GLOBALS['userid']), __FILE__, __LINE__);
208 list($sex, $surname, $family) = SQL_FETCHROW($result);
209 SQL_FREERESULT($result);
210 $salut = TRANSLATE_SEX($sex);
213 // Generate date/time string
214 $date_time = MAKE_DATETIME(time(), "1");
217 $BASE = PATH."templates/".GET_LANGUAGE()."/html/";
220 // Check for admin/guest/member templates
221 if (strpos($template, "admin_") > -1) {
222 // Admin template found
224 } elseif (strpos($template, "guest_") > -1) {
225 // Guest template found
227 } elseif (strpos($template, "member_") > -1) {
228 // Member template found
230 } elseif (strpos($template, "install_") > -1) {
231 // Installation template found
233 } elseif (strpos($template, "ext_") > -1) {
234 // Extension template found
236 } elseif (strpos($template, "la_") > -1) {
237 // "Logical-area" template found
240 // Test for extension
241 $test = substr($template, 0, strpos($template, "_"));
242 if (EXT_IS_ACTIVE($test)) {
243 // Set extra path to extension's name
248 ////////////////////////
249 // Generate file name //
250 ////////////////////////
251 $file = $BASE.$MODE.$template.".tpl";
253 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
254 // Select what depended header/footer template file for admin/guest/member area
255 $file2 = sprintf("%s%s%s_%s.tpl",
259 SQL_ESCAPE($GLOBALS['what'])
263 if (file_exists($file2)) $file = $file2;
265 // Remove variable from memory
269 // Does the special template exists?
270 if ((!file_exists($file)) || (!is_readable($file))) {
271 // Reset to default template
272 $file = $BASE.$template.".tpl";
275 // Now does the final template exists?
276 if ((file_exists($file)) && (is_readable($file))) {
277 // The local file does exists so we load it. :)
278 $tmpl_file = implode("", file($file));
280 // Replace ' to our own chars to preventing them being quoted
281 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
283 // Do we have to compile the code?
284 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
286 $tmpl_file = "\$ret=\"" . COMPILE_CODE(addslashes($tmpl_file)) . "\";";
289 // Simply return loaded code
293 // Add surrounding HTML comments to help finding bugs faster
294 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
295 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
296 // Only admins shall see this warning or when installation mode is active
297 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
298 (".basename($file).")<br />
301 <PRE>".print_r($content, true)."</PRE>
303 <PRE>".print_r($DATA, true)."</PRE>
307 // Do we have some content to output or return?
309 // Not empty so let's put it out! ;)
311 // Return the HTML code
317 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
318 // Warning, empty output!
319 return "E:".$template."<br />\n";
323 // Send mail out to an email address
324 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML='N', $FROM="") {
325 // Compile subject line (for POINTS constant etc.)
326 $eval = "\$SUBJECT = \"" . COMPILE_CODE(addslashes($SUBJECT)) . "\";";
328 $SUBJECT = html_entity_decode($SUBJECT);
331 if (!eregi("@", $TO)) {
332 // Value detected, load email from database
333 if (EXT_IS_ACTIVE("msg")) {
334 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
337 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
338 list($TO) = SQL_FETCHROW($result_email);
339 SQL_FREERESULT($result_email);
343 // Not in PHPMailer-Mode
344 if (!CHECK_PHPMAILER_USAGE()) {
346 // Load email header template
347 $FROM = LOAD_EMAIL_TEMPLATE("header");
350 $FROM .= LOAD_EMAIL_TEMPLATE("header");
352 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
354 // Load email header template
355 $FROM = LOAD_EMAIL_TEMPLATE("header");
358 $FROM .= LOAD_EMAIL_TEMPLATE("header");
362 // Fix HTML parameter (default is no!)
363 if (empty($HTML)) $HTML = 'N';
364 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
365 // In debug mode we want to display the mail instead of sending it away so we can debug this part
367 ".htmlentities(trim($FROM))."
369 Subject : ".$SUBJECT."
372 } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE("html_mail", true))) {
373 // Send mail as HTML away
374 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
375 } elseif (!empty($TO)) {
377 $TO = COMPILE_CODE($TO);
380 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
381 } elseif ($HTML == 'N') {
383 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
387 // Check if legacy or PHPMailer command
389 function CHECK_PHPMAILER_USAGE() {
390 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
394 * Send out a raw email with PHPMailer class or legacy mail() command
396 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
397 // Shall we use PHPMailer class or legacy mode?
398 if (CHECK_PHPMAILER_USAGE()) {
399 // Use PHPMailer class with SMTP enabled
400 require_once(PATH."inc/phpmailer/class.phpmailer.php");
401 require_once(PATH."inc/phpmailer/class.smtp.php");
404 $mail = new PHPMailer();
405 $mail->PluginDir = PATH."inc/phpmailer/";
408 $mail->SMTPAuth = true;
409 $mail->Host = SMTP_HOSTNAME;
411 $mail->Username = SMTP_USER;
412 $mail->Password = SMTP_PASSWORD;
414 $mail->FromName = MAIN_TITLE;
415 $mail->Subject = $subject;
416 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
418 $mail->AltBody = "Your mail program required HTML support to read this mail!";
419 $mail->WordWrap = 70;
424 $mail->AddAddress($to, "");
425 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
426 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
427 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
430 // Use legacy mail() command
431 @mail($to, $subject, $msg, $from);
436 // Generate a password in a specified length or use default password length
437 function GEN_PASS($LEN = 0) {
439 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
441 // Initialize array with all allowed chars
442 $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,-,+,_,/");
444 // Initialize randomizer
445 mt_srand((double) microtime() * 1000000);
447 // Start creating password
449 for ($i = 0; $i < $LEN; $i++) {
450 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
453 // When the size is below 40 we can also add additional security by scrambling it
454 if (strlen($PASS) <= 40) {
455 // Also scramble the password
456 $PASS = scrambleString($PASS);
459 // Return the password
463 function MAKE_DATETIME($time, $mode="0")
467 return NEVER_HAPPENED;
469 // Filter out numbers
470 $time = bigintval($time);
473 switch (GET_LANGUAGE())
475 case "de": // German date / time format
478 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
479 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
480 case "2": $ret = date("d.m.Y|H:i", $time); break;
481 case "3": $ret = date("d.m.Y", $time); break;
485 default: // Default is the US date / time format!
488 case "0": $ret = date("r", $time); break;
489 case "1": $ret = date("Y-m-d - g:i A", $time); break;
490 case "2": $ret = date("y-m-d|H:i", $time); break;
491 case "3": $ret = date("y-m-d", $time); break;
497 // Translates the american decimal dot into a german comma
498 function TRANSLATE_COMMA($dotted, $cut=true)
501 // Default is 3 you can change this in admin area "Misc -> Misc Options"
502 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
503 if (!ereg("\.", $dotted)) $dotted .= ".".str_repeat("0", $_CONFIG['max_comma']);
505 // Remove trailing zeros
506 $dot = str_replace(".", "x", $dotted);
507 while(substr($dot, -1, 1) == "0") {
508 $dot = substr($dot, 0, -1);
511 if (substr($dot, -1, 1) == "x") {
512 // Last char is the 'x'
513 $dotted = substr($dot, 0, -1);
515 // Last char is a number
516 $dotted = str_replace("x", ".", $dot);
521 switch (GET_LANGUAGE()) {
523 $pos = strpos($dotted, ".");
526 // Cut x numbers behind comma
527 $dotted = str_replace(".", ",", substr($dotted, 0, ($pos + $_CONFIG['max_comma'] + 1)));
529 // Replace comma with dot
530 $dotted = str_replace(".", ",", $dotted);
534 $dotted = "0,".str_repeat("0", $_CONFIG['max_comma']);
536 $dotted .= ",".str_repeat("0", $_CONFIG['max_comma']);
544 $dotted = substr($dotted, 0, ($pos + $_CONFIG['max_comma'] + 1));
546 $dotted .= ".".str_repeat("0", $_CONFIG['max_comma']);
555 function DEREFERER($URL) {
556 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(COMPILE_CODE($URL)));
561 function TRANSLATE_SEX($sex) {
564 case "M": $ret = SEX_M; break;
565 case "F": $ret = SEX_F; break;
566 case "C": $ret = SEX_C; break;
567 default : $ret = $sex; break;
572 function GET_POOL_TYPE($PT)
576 case "TEMP" : $ret = POOL_TEMP; break;
577 case "SEND" : $ret = POOL_SEND; break;
578 case "NEW" : $ret = POOL_NEW; break;
579 case "ADMIN" : $ret = POOL_ADMIN; break;
580 case "ACTIVE" : $ret = POOL_ACTIVE; break;
581 case "DELETED": $ret = POOL_DELETED; break;
582 default : $ret = POOL_UNKNOWN." (".$PT.")"; break;
587 function FRAMETESTER($URL)
590 $URL = URL."/modules.php?module=frametester&url=".urlencode(base64_encode(COMPILE_CODE($URL)));
594 function SELECTION_COUNT($array)
597 if (is_array($array))
599 foreach ($array as $key=>$sel)
601 if (!empty($sel)) $ret++;
607 function IMG_CODE ($code, $type, $DATA, $uid)
609 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
612 function TRANSLATE_STATUS($status)
617 $ret = ACCOUNT_UNCONFIRMED;
621 $ret = ACCOUNT_CONFIRMED;
625 $ret = ACCOUNT_LOCKED;
629 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
635 function GET_LANGUAGE() {
636 if (!empty($_GET['mx_lang'])) {
637 // Accept only first 2 chars
638 $lang = substr($_GET['mx_lang'], 0, 2);
644 // Set default return value to default language from config
647 // Check GET variable and cookie
649 // Check if main language file does exist
650 if (file_exists(PATH."inc/language/".$lang.".php")) {
651 // Okay found, so let's update cookies
654 } elseif (!isSessionVariableSet('mx_lang')) {
655 // Return stored value from cookie
656 $ret = get_session('mx_lang');
658 // Fixes a warning before the session has the mx_lang constant
659 if (empty($ret)) $ret = DEFAULT_LANG;
664 function SET_LANGUAGE($lang) {
667 // Accept only first 2 chars!
668 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
671 set_session("mx_lang", $lang);
674 function LOAD_EMAIL_TEMPLATE($template, $content="", $UID="0") {
675 global $DATA, $_CONFIG, $REPLACER;
677 // Keept for backward-compatiblity (please replace these variables against our new {--CONST--} syntax!)
678 $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
679 $surname = ""; $family = ""; $nick = ""; $sex = 'N';
681 // Prepare IP number and User Agent
682 $REMOTE_ADDR = getenv('REMOTE_ADDR');
683 $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
686 if (isSessionVariableSet('admin_login')) {
688 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
689 array(SQL_ESCAPE(get_session('admin_login'))), __FILE__, __LINE__);
690 list($ADMIN) = SQL_FETCHROW($result);
691 SQL_FREERESULT($result);
694 // Expiration in a nice output format
695 if ($_CONFIG['auto_purge'] == 0) {
696 // Will never expire!
697 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
698 } elseif (function_exists('CREATE_FANCY_TIME')) {
699 // Create nice date string
700 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
703 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
708 case "bonus-mail": // Load data for the bonus mail
711 $points = TRANSLATE_COMMA($DATA[4]);
713 $TARGET_URL = $DATA[8];
714 $CATEGORY = GET_CATEGORY($DATA[9]);
718 foreach ($REPLACER as $key=>$value)
720 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
726 $BLOCKS = $_CONFIG['max_send'];
729 $PAYMENT = GET_PAYMENT($DATA[3]);
730 $TARGET_URL = $DATA[5];
731 $CATEGORY = GET_CATEGORY($DATA[6]);
735 case "order-deleted":
737 $TARGET_URL = $DATA[0];
747 case "confirm-member":
748 $points = $_CONFIG['points_register'];
751 case "confirm-referral":
759 $SEND_UID = $DATA[1];
760 $CATEGORY = GET_CATEGORY($DATA[9]);
761 $TIME = GET_PAY_POINTS($DATA[5], "time");
762 $TARGET_URL = $DATA[7];
763 $points = TRANSLATE_COMMA(GET_PAY_POINTS($DATA[5], "payment"));
764 // Warning! This ID has changed from 10 to 11!
768 foreach ($REPLACER as $key=>$value)
770 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
776 $SEND_UID = $DATA[1];
777 $CATEGORY = GET_CATEGORY($DATA[9]);
778 $TARGET_URL = $DATA[7];
783 $points = TRANSLATE_COMMA($DATA[10]);
787 if (isset($_POST['points'])) {
788 $points = bigintval($_POST['points']);
790 $points = __POINTS_VALUE;
794 case "guest_request_confirm":
801 if (EXT_IS_ACTIVE("nickname")) {
803 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
804 array(bigintval($UID)), __FILE__, __LINE__);
805 list($surname, $family, $sex, $email, $nick) = SQL_FETCHROW($result);
806 SQL_FREERESULT($result);
809 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
810 array(bigintval($UID)), __FILE__, __LINE__);
811 list($surname, $family, $sex, $email) = SQL_FETCHROW($result);
812 SQL_FREERESULT($result);
816 // Neutral sex and email address is default
821 // Translate M to male or F to female
822 $salut = TRANSLATE_SEX($sex);
824 // Store email for some functions in global data array
825 $DATA['email'] = $email;
828 $BASE = PATH."templates/".GET_LANGUAGE()."/emails/";
830 // Check for admin/guest/member templates
831 if (strpos($template, "admin_") > -1) {
832 // Admin template found
833 $file = $BASE."admin/".$template.".tpl";
834 } elseif (strpos($template, "guest_") > -1) {
835 // Guest template found
836 $file = $BASE."guest/".$template.".tpl";
837 } elseif (strpos($template, "member_") > -1) {
838 // Member template found
839 $file = $BASE."member/".$template.".tpl";
841 // Test for extension
842 $test = substr($template, 0, strpos($template, "_"));
843 if (EXT_IS_ACTIVE($test)) {
844 // Set extra path to extension's name
845 $file = $BASE.$test."/".$template.".tpl";
847 // No special filename
848 $file = $BASE.$template.".tpl";
852 // Does the special template exists?
853 if ((!@file_exists($file)) || (!is_readable($file))) {
854 // Reset to default template
855 $file = $BASE.$template.".tpl";
858 // Now does the final template exists?
859 if ((@file_exists($file)) && (is_readable($file)))
861 // The local file does exists so we load it. :)
862 $tmpl_file = @implode("", @file($file));
863 $tmpl_file = addslashes($tmpl_file);
866 $tmpl_file = COMPILE_CODE($tmpl_file);
869 $tmpl_file = "\$content=\"".$tmpl_file."\";";
872 // Replace HTML confirm chars
873 $content = html_entity_decode($content);
875 elseif (!empty($template))
877 // Template file not found!
878 $content = TEMPLATE_404.": ".$template."<br />
880 <PRE>".print_r($content, true)."</PRE>
882 <PRE>".print_r($DATA, true)."</PRE>
885 // Debug mode not active? Then remove the HTML tags
886 if (!DEBUG_MODE) $content = strip_tags($content);
890 // No template name supplied!
891 $content = NO_TEMPLATE_SUPPLIED;
893 return COMPILE_CODE($content);
896 function MAKE_TIME($H, $M, $S, $stamp)
898 // Extract day, month and year from given timestamp
899 $DAY = date("d", $stamp);
900 $MONTH = date("m", $stamp);
901 $YEAR = date('Y', $stamp);
903 // Create timestamp for wished time which depends on extracted date
904 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
907 function LOAD_URL($URL, $addUrlData=true) {
908 global $CSS, $_CONFIG, $link, $db, $footer;
910 // Check if http(s):// is there
911 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
912 // Make all URLs full-qualified
916 // Compile out URI codes
917 $URL = COMPILE_CODE($URL);
920 $OUTPUT = ob_get_contents();
925 // Add some data to URL if cookies are not accepted
926 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
928 // Probe for bot from search engine
929 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
930 // Search engine bot detected so let's rewrite many chars for the link
931 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
933 // Output new location link as anchor
934 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
935 } elseif (!headers_sent()) {
936 // Load URL when headers are not sent
937 @header ("Location: ".str_replace("&", "&", $URL));
939 // Output error message
940 include(PATH."inc/header.php");
941 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
942 include(PATH."inc/footer.php");
947 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
948 global $SEC_CHARS, $URL_CHARS;
951 // Select smaller set of chars to replace when we e.g. want to compile URLs
952 if (!$full) $ARRAY = $URL_CHARS;
956 // BEFORE 0.2.1 : Language and data constants
957 // WITH 0.2.1+ : Only language constants
958 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
960 // BEFORE 0.2.1 : Not used
961 // WITH 0.2.1+ : Data constants
962 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
965 // Compile QUOT and other non-HTML codes
966 foreach ($ARRAY['to'] as $k => $to) {
967 // Do the reversed thing as in inc/libs/security_functions.php
968 $code = str_replace($to, $ARRAY['from'][$k], $code);
971 // But shall I keep simple quotes for later use?
972 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
974 // Find $content[bla][blub] entries
975 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
977 // Are some matches found?
978 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
979 // Replace all matches
980 $matchesFound = array();
981 foreach ($matches[0] as $key=>$match) {
982 // Avoid replacing matches multiple times
983 if (!isset($matchesFound[$match])) {
985 $code = str_replace($match, "\".".$match.".\"", $code);
986 $matchesFound[$match] = 1;
989 // Take all string elements
990 if (("".bigintval($matches[4][$key])."" != $matches[4][$key]) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
991 // Replace it in the code
992 $code = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $code);
993 $matchesFound[$key."_".$matches[4][$key]] = 1;
998 // Return compiled code
1002 /************************************************************************
1004 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1005 * $a_sort sortiert: *
1007 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1008 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1009 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1010 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1011 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1013 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1014 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1015 * Sie, dass es doch nicht so schwer ist! :-) *
1017 ************************************************************************/
1018 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1021 while ($primary_key < count($a_sort))
1023 foreach ($dummy[$a_sort[$primary_key]] as $key=>$value)
1025 foreach ($dummy[$a_sort[$primary_key]] as $key2=>$value2)
1030 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1031 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1033 elseif ($key != $key2)
1035 // Sort numbers (E.g.: 9 < 10)
1036 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1037 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1041 // We have found two different values, so let's sort whole array
1042 foreach ($dummy as $sort_key=>$sort_val)
1044 $t = $dummy[$sort_key][$key];
1045 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1046 $dummy[$sort_key][$key2] = $t;
1057 // Write back sorted array
1061 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1063 global $MONTH_DESCR; $OUT = "";
1066 // This is a yes/no selection only!
1067 if ($id > 0) $prefix .= "[".$id."]";
1068 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1072 // Begin with regular selection box here
1073 if (!empty($prefix)) $prefix .= "_";
1075 if ($id > 0) $type2 .= "[".$id."]";
1076 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1081 for ($idx = 1; $idx < 32; $idx++)
1083 $OUT .= " <OPTION value=\"".$idx."\"";
1084 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1085 $OUT .= ">".$idx."</OPTION>\n";
1089 case "month": // Month
1090 foreach ($MONTH_DESCR as $month=>$descr)
1092 $OUT .= " <OPTION value=\"".$month."\"";
1093 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1094 $OUT .= ">".$descr."</OPTION>\n";
1098 case "year": // Year
1100 $YEAR = date('Y', time());
1102 // Check if the default value is larger than minimum and bigger than actual year
1103 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1105 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1107 $OUT .= " <OPTION value=\"".$idx."\"";
1108 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1109 $OUT .= ">".$idx."</OPTION>\n";
1112 elseif ($DEFAULT == -1)
1114 // Current year minus 1
1115 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1117 $OUT .= " <OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1122 // Get current year and subtract 16 (for erotic content)
1123 $OUT .= " <OPTION value=\"1929\"><1930</OPTION>\n";
1124 $YEAR = date('Y', time()) - 16;
1125 for ($idx = 1930; $idx <= $YEAR; $idx++)
1127 $OUT .= " <OPTION value=\"".$idx."\"";
1128 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1129 $OUT .= ">".$idx."</OPTION>\n";
1136 for ($idx = 0; $idx < 60; $idx+=5)
1138 if (strlen($idx) == 1) $idx = "0".$idx;
1139 $OUT .= " <OPTION value=\"".$idx."\"";
1140 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1141 $OUT .= ">".$idx."</OPTION>\n";
1146 for ($idx = 0; $idx < 24; $idx++)
1148 if (strlen($idx) == 1) $idx = "0".$idx;
1149 $OUT .= " <OPTION value=\"".$idx."\"";
1150 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1151 $OUT .= ">".$idx."</OPTION>\n";
1156 $OUT .= " <OPTION value=\"Y\"";
1157 if ($DEFAULT == 'Y') $OUT .= " selected=\"selected\"";
1158 $OUT .= ">".YES."</OPTION>
1159 <OPTION value=\"N\"";
1160 if ($DEFAULT == 'N') $OUT .= " selected=\"selected\"";
1161 $OUT .= ">".NO."</OPTION>\n";
1164 $OUT .= " </SELECT>\n";
1168 function TRANSLATE_YESNO($yn)
1172 case 'Y': $yn = YES; break;
1173 case 'N': $yn = NO; break;
1174 default : $yn = "??? (".$yn.")"; break;
1179 // Deprecated : $length
1182 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="")
1186 // Build server string
1187 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1190 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']).":".$_CONFIG['master_salt'];
1192 // Build string from misc data
1193 $data = $code.":".$uid.":".$DATA;
1195 // Add more additional data
1196 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1197 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1198 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1199 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1200 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1201 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1203 // Calculate number for generating the code
1204 $a = $code + _ADD - 1;
1206 // Generate hash with master salt from modula of number with the prime number and other data
1207 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1209 // Create number from hash
1210 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1212 // At least 10 numbers shall be secure enought!
1213 $len = $_CONFIG['code_length'];
1214 if ($len == 0) $len = 10;
1216 // Cut off requested counts of number
1217 $return = substr(str_replace('.', "", $rcode), 0, $len);
1219 // Done building code
1222 // Does only allow numbers
1223 function bigintval($num, $castValue = true)
1225 // Filter all numbers out
1226 $ret = preg_replace("/[^0123456789]/", "", $num);
1229 if ($castValue) $ret = (int) $ret;
1234 // Insert the code in $img_code into jpeg or PNG image
1235 function GENERATE_IMAGE($img_code, $header=true)
1238 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0))
1240 // Stop execution of function here because of over-sized code length
1245 // Return in an HTML code code
1246 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1249 switch ($_CONFIG['img_type'])
1253 $img = PATH."/theme/".GET_CURR_THEME()."/images/code_bg.jpg";
1254 if ((file_exists($img)) && (is_readable($img)))
1256 // Okay, load image and hide all errors
1257 $image = @imagecreatefromjpeg($img);
1261 // Exit function here
1268 $img = PATH."/theme/".GET_CURR_THEME()."/images/code_bg.png";
1269 if ((file_exists($img)) && (is_readable($img)))
1271 // Okay, load image and hide all errors
1272 $image = @imagecreatefrompng($img);
1276 // Exit function here
1282 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1283 $text_color = imagecolorallocate($image, 0, 0, 0);
1285 // Insert code into image
1286 imagestring($image, 5, 14, 2, $img_code, $text_color);
1288 // Return to browser
1289 header ("Content-Type: image/".$_CONFIG['img_type']);
1291 // Output image with matching image factory
1292 switch ($_CONFIG['img_type'])
1294 case "jpg": imagejpeg($image); break;
1295 case "png": imagepng($image); break;
1298 // Remove image from memory
1299 imagedestroy($image);
1301 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false)
1303 // Calculate 15-seconds timestamp (15-seconds-steps shall be fine ;) )
1304 $timestamp = round($timestamp / 15) * 15;
1305 // Do we have a leap year?
1307 $TEST = date('Y', time()) / 4;
1308 $M1 = date("m", time());
1309 $M2 = date("m", (time() + $timestamp));
1310 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1311 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1312 // First of all years...
1313 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1315 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1317 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1319 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1321 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1323 $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));
1324 // And at last seconds...
1325 $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));
1327 // Now we convert them in seconds...
1331 // Just put all data in an array for later use
1345 $OUT = "<DIV align=\"".$align."\">\n";
1346 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1348 if (ereg('Y', $display) || (empty($display)))
1350 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1352 if (ereg("M", $display) || (empty($display)))
1354 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1356 if (ereg("W", $display) || (empty($display)))
1358 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1360 if (ereg("D", $display) || (empty($display)))
1362 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1364 if (ereg("h", $display) || (empty($display)))
1366 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1368 if (ereg("m", $display) || (empty($display)))
1370 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1372 if (ereg("s", $display) || (empty($display)))
1374 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">".SECS."</STRONG></TD>\n";
1378 if (ereg('Y', $display) || (empty($display)))
1380 // Generate year selection
1381 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1382 for ($idx = 0; $idx <= 10; $idx++)
1384 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1385 if ($idx == $Y) $OUT .= " selected default";
1386 $OUT .= ">".$idx."</OPTION>\n";
1388 $OUT .= " </SELECT></TD>\n";
1392 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1394 if (ereg("M", $display) || (empty($display)))
1396 // Generate month selection
1397 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1398 for ($idx = 0; $idx <= 11; $idx++)
1400 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1401 if ($idx == $M) $OUT .= " selected default";
1402 $OUT .= ">".$idx."</OPTION>\n";
1404 $OUT .= " </SELECT></TD>\n";
1408 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1410 if (ereg("W", $display) || (empty($display)))
1412 // Generate week selection
1413 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1414 for ($idx = 0; $idx <= 4; $idx++)
1416 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1417 if ($idx == $W) $OUT .= " selected default";
1418 $OUT .= ">".$idx."</OPTION>\n";
1420 $OUT .= " </SELECT></TD>\n";
1424 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1426 if (ereg("D", $display) || (empty($display)))
1428 // Generate day selection
1429 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1430 for ($idx = 0; $idx <= 31; $idx++)
1432 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1433 if ($idx == $D) $OUT .= " selected default";
1434 $OUT .= ">".$idx."</OPTION>\n";
1436 $OUT .= " </SELECT></TD>\n";
1440 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1442 if (ereg("h", $display) || (empty($display)))
1444 // Generate hour selection
1445 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1446 for ($idx = 0; $idx <= 23; $idx++)
1448 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1449 if ($idx == $h) $OUT .= " selected default";
1450 $OUT .= ">".$idx."</OPTION>\n";
1452 $OUT .= " </SELECT></TD>\n";
1456 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1458 if (ereg("m", $display) || (empty($display)))
1460 // Generate minute selection
1461 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1462 for ($idx = 0; $idx <= 59; $idx++)
1464 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1465 if ($idx == $m) $OUT .= " selected default";
1466 $OUT .= ">".$idx."</OPTION>\n";
1468 $OUT .= " </SELECT></TD>\n";
1472 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1474 if (ereg("s", $display) || (empty($display)))
1476 // Generate second selection
1477 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1478 for ($idx = 0; $idx <= 45; $idx+=15)
1480 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1481 if ($idx == $s) $OUT .= " selected default";
1482 $OUT .= ">".$idx."</OPTION>\n";
1484 $OUT .= " </SELECT></TD>\n";
1488 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1491 $OUT .= "</TABLE>\n";
1493 // Return generated HTML code
1498 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1500 // Do we have a leap year?
1502 $TEST = date('Y', time()) / 4;
1503 $M1 = date("m", time());
1504 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1505 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1506 // First add years...
1507 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1509 $ret += $POST[$prefix."_mo"] * 2628000;
1511 $ret += $POST[$prefix."_we"] * 604800;
1513 $ret += $POST[$prefix."_da"] * 86400;
1515 $ret += $POST[$prefix."_ho"] * 3600;
1517 $ret += $POST[$prefix."_mi"] * 60;
1518 // And at last seconds...
1519 $ret += $POST[$prefix."_se"];
1520 // Return calculated value
1523 // Sends out mail to all administrators
1524 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content="", $UID="0") {
1525 // Trim template name
1526 $template = trim($template);
1528 // Load email template
1529 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1531 if (GET_EXT_VERSION("admins") < "0.4.0") {
1532 // Older version detected!
1533 return SEND_ADMIN_EMAILS($subj, $msg);
1536 // Check which admin shall receive this mail
1537 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1538 array($template), __FILE__, __LINE__);
1539 if (SQL_NUMROWS($result) == 0) {
1540 // Create new entry (to all admins)
1541 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1542 array($template), __FILE__, __LINE__);
1544 // Load admin IDs...
1546 while(list($aid) = SQL_FETCHROW($result)) {
1551 SQL_FREERESULT($result);
1553 // "implode" IDs and query string
1554 $aid = implode(",", $aids);
1556 // Add line to userlog
1557 USERLOG_ADD_LINE($subj, $msg, $UID);
1559 } elseif ($aid == "0") {
1560 // Select all email adresses
1561 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1563 // If Admin-ID is not "to-all" select
1564 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1568 // Load email addresses and send away
1569 while (list($email) = SQL_FETCHROW($result)) {
1570 SEND_EMAIL($email, $subj, $msg);
1574 SQL_FREERESULT($result);
1577 function CREATE_FANCY_TIME($stamp) {
1578 // Get data array with years/months/weeks/days/...
1579 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1581 foreach($data as $k=>$v) {
1583 // Value is greater than 0 "eval" data to return string
1584 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1590 // Remove first "comma,null" string
1591 $ret = substr($ret, 2);
1595 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1596 $SEP = ""; $TOP = "";
1599 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1603 for ($page = 1; $page <= $PAGES; $page++) {
1604 // Is the page currently selected or shall we generate a link to it?
1605 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1606 // Is currently selected, so only highlight it
1607 $NAV .= "<STRONG>-";
1609 // Open anchor tag and add base URL
1610 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1612 // Add userid when we shall show all mails from a single member
1613 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1615 // Close open anchor tag
1619 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1620 // Is currently selected, so only highlight it
1621 $NAV .= "-</STRONG>";
1627 // Add seperator if we have not yet reached total pages
1628 if ($page < $PAGES) $NAV .= " | ";
1631 // Define constants only once
1632 if (!defined('__NAV_OUTPUT')) {
1633 define('__NAV_OUTPUT' , $NAV);
1634 define('__NAV_COLSPAN', $colspan);
1635 define('__NAV_TOP' , $TOP);
1636 define('__NAV_SEP' , $SEP);
1639 // Load navigation template
1640 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1643 // Return generated HTML-Code
1652 function MXCHANGE_OPEN ($script) {
1653 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1654 // Compile the script name
1655 $script = COMPILE_CODE($script);
1656 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1658 // Use default SERVER_URL by default... ;) So?
1660 if (substr($script, 0, 7) == "http://") {
1661 // Use the hostname from script URL as new hostname
1662 $url = substr($script, 7);
1663 $extract = explode("/", $url);
1665 // Done extracting the URL :)
1668 // Extract host name
1669 $host = str_replace("http://", "", $url);
1670 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1672 // Generate relative URL
1673 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1674 if (substr(strtolower($script), 0, 7) == "http://") {
1675 // But only if http:// is in front!
1676 $script = substr($script, (strlen($url) + 7));
1677 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1679 $script = substr($script, (strlen($url) + 8));
1682 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1683 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1686 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1687 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1690 return array("", "", "");
1693 // Generate request header
1694 $request = "GET /".trim($script)." HTTP/1.0\r\n";
1695 $request .= "Host: ".$host."\r\n";
1696 $request .= "Referer: ".URL."/admin.php\r\n";
1697 $request .= "User-Agent: ".TITLE."/".FULL_VERSION."\r\n\r\n";
1700 $response = array();
1703 fputs($fp, $request);
1707 $response[] = trim(fgets($fp, 1024));
1713 // Was the request successfull?
1714 if ((!ereg("200 OK", $response[0])) && (empty($response[0]))) {
1715 // Not found / access forbidden
1716 $response = array("", "", "");
1722 // Taken from www.php.net eregi() user comments
1723 function VALIDATE_EMAIL($email) {
1725 $email = COMPILE_CODE($email);
1727 // Check first part of email address
1728 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1731 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1734 $regex = "^".$first."@".$domain."$";
1736 // Return check result
1737 return eregi($regex, $email);
1739 // Function taken from user comments on www.php.net / function eregi()
1740 function VALIDATE_URL ($URL, $compile=true) {
1741 // Trim URL a little
1742 $URL = trim(urldecode($URL));
1743 //* DEBUG: */ echo $URL."<br />";
1745 // Compile some chars out...
1746 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1747 //* DEBUG: */ echo $URL."<br />";
1749 // Check for the extension filter
1750 if (EXT_IS_ACTIVE("filter")) {
1751 // Use the extension's filter set
1752 return FILTER_VALIDATE_URL($URL, false);
1755 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1756 // https:// in front of the URLs
1757 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1760 function MEMBER_ACTION_LINKS($uid, $status="") {
1761 // Define all main targets
1762 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1764 // Begin of navigation links
1765 $eval = "\$OUT = \"[ ";
1767 foreach ($TARGETS as $tar) {
1768 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1769 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1770 if (($tar == "lock_user") && ($status == "LOCKED")) {
1771 // Locked accounts shall be unlocked
1772 $eval .= "UNLOCK_USER";
1774 // All other status is fine
1775 $eval .= strtoupper($tar);
1777 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1778 if (($tar == "lock_user") && ($status == "LOCKED")) {
1779 // Locked accounts shall be unlocked
1780 $eval .= "UNLOCK_USER";
1782 // All other status is fine
1783 $eval .= strtoupper($tar);
1785 $eval .= ".\"</A></SPAN> | ";
1788 // Finish navigation link
1789 $eval = substr($eval, 0, -7) . "]\";";
1795 // Function for backward-compatiblity
1796 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1797 // Load it from the register extension
1798 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1800 // Generate an email link
1801 function CREATE_EMAIL_LINK($email, $table="admins") {
1802 // Default email link (INSECURE! Spammer can read this by harvester programs)
1803 $EMAIL = "mailto:".$email;
1805 // Check for several extensions
1806 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1807 // Create email link for contacting admin in guest area
1808 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1809 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1810 // Create email link for contacting a member within admin area (or later in other areas, too?)
1811 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1812 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1813 // Create email link to contact sponsor within admin area (or like the link above?)
1814 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1817 // Shall I close the link when there is no admin?
1818 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1820 // Return email link
1823 // Generate a hash for extra-security for all passwords
1824 function generateHash ($plainText, $salt = "") {
1825 global $_CONFIG, $_SERVER;
1827 // Is the required extension "sql_patches" there?
1828 if ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) {
1829 // Extension sql_patches is missing/outdated so we return the plain text
1833 // When the salt is empty build a new one, else use the first x configured characters as the salt
1835 // Build server string
1836 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1839 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']).":".$_CONFIG['master_salt'];
1842 $data = $plainText.":".uniqid(rand(), true).":".time();
1844 // Calculate number for generating the code
1845 $a = time() + _ADD - 1;
1847 // Generate SHA1 sum from modula of number and the prime number
1848 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1849 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br>";
1850 $sha1 = scrambleString($sha1);
1851 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br>";
1852 //* DEBUG: */ $sha1b = descrambleString($sha1);
1853 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br>";
1855 // Generate the password salt string
1856 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1857 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1861 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1865 return $salt . sha1($salt . $plainText);
1868 function scrambleString($str) {
1874 // Final check, in case of failture it will return unscrambled string
1875 if (strlen($str) > 40) {
1876 // The string is to long
1878 } elseif (strlen($str) == 40) {
1880 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1882 // Generate new numbers
1883 $scrambleNums = explode(":", genScrambleString(strlen($str)));
1886 // Scramble string here
1887 //* DEBUG: */ echo "***Original=".$str."***<br />";
1888 for ($idx = 0; $idx < strlen($str); $idx++) {
1889 // Get char on scrambled position
1890 $char = substr($str, $scrambleNums[$idx], 1);
1892 // Add it to final output string
1893 $scrambled .= $char;
1896 // Return scrambled string
1897 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
1901 function descrambleString($str)
1904 // Scramble only 40 chars long strings
1905 if (strlen($str) != 40) return $str;
1907 // Load numbers from config
1908 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
1911 if (count($scrambleNums) != 40) return $str;
1913 // Begin descrambling
1914 $orig = str_repeat(" ", 40);
1915 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
1916 for ($idx = 0; $idx < 40; $idx++)
1918 $char = substr($str, $idx, 1);
1919 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
1922 // Return scrambled string
1923 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
1927 function genScrambleString($len) {
1928 // Prepare randomizer and array for the numbers
1929 mt_srand((double) microtime() * 1000000);
1930 $scrambleNumbers = array();
1932 // First we need to setup randomized numbers from 0 to 31
1933 for ($idx = 0; $idx < $len; $idx++) {
1935 $rand = mt_rand(0, ($len -1));
1937 // Check for it by creating more numbers
1938 while (array_key_exists($rand, $scrambleNumbers)) {
1939 $rand = mt_rand(0, ($len -1));
1943 $scrambleNumbers[$rand] = $rand;
1946 // So let's create the string for storing it in database
1947 $scrambleString = implode(":", $scrambleNumbers);
1948 return $scrambleString;
1950 // Append data like session ID referral ID to the given URL which would
1951 // normally be stored in cookies
1952 function ADD_URL_DATA($URL)
1957 // Determine URL binder
1959 if (strpos($URL, "?") !== false) $BIND = "&";
1961 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
1962 // Cookies are not accepted
1963 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
1964 // Cookie found in URL
1965 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
1966 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
1967 // Not found! So let's set default here
1968 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
1971 // Is there already added data? Then change the binder
1972 if (!empty($ADD)) $BIND = "&";
1975 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
1976 // Add session from URL
1977 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
1979 // Add current session
1980 $ADD .= $BIND."PHPSESSID=".session_id();
1984 // Add all together and return it
1988 function generatePassString($passHash) {
1991 // Return vanilla password hash
1994 // Is a secret key and master salt already initialized?
1995 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
1996 // Only calculate when the secret key is generated
1997 $newHash = ""; $start = 9;
1998 for ($idx = 0; $idx < 10; $idx++) {
1999 $part1 = hexdec(substr($passHash, $start, 4));
2000 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2001 $mod = dechex($idx);
2002 if ($part1 > $part2) {
2003 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2004 } elseif ($part2 > $part1) {
2005 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2007 $mod = substr(round($mod), 0, 4);
2008 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2009 //* DEBUG: */ echo "*".$start."=".$mod."*<br>";
2014 //* DEBUG: */ die($passHash."<br>".$newHash." (".strlen($newHash).")");
2015 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2018 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2019 $ret = md5($passHash);
2020 //* DEBUG: */ echo "++".$ret."++<br />\n";
2026 // Fix "deleted" cookies
2027 function FIX_DELETED_COOKIES ($cookies) {
2028 // Is this an array with entries?
2029 if ((is_array($cookies)) && (count($cookies) > 0)) {
2030 // Then check all cookies if they are marked as deleted!
2031 foreach ($cookies as $cookieName) {
2032 // Is the cookie set to "deleted"?
2033 if (get_session($cookieName) == "deleted") {
2034 set_session($cookieName, "");
2039 // Output error messages in a fasioned way and die...
2040 function mxchange_die ($msg) {
2043 // Load the message template
2044 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2047 include(PATH."inc/footer.php");
2053 // Display parsing time and number of SQL queries in footer
2054 function DISPLAY_PARSING_TIME_FOOTER() {
2055 global $startTime, $_CONFIG;
2056 $endTime = microtime(true);
2058 // Is the timer started?
2059 if (!isset($GLOBALS['startTime'])) {
2064 // "Explode" both times
2065 $start = explode(" ", $GLOBALS['startTime']);
2066 $end = explode(" ", $endTime);
2067 $runTime = $end[0] - $start[0];
2068 if ($runTime < 0) $runTime = 0;
2069 $runTime = TRANSLATE_COMMA($runTime);
2073 'runtime' => $runTime,
2074 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2075 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2078 // Load the template
2079 LOAD_TEMPLATE("show_timings", false, $content);
2082 // Unset/set session variables
2083 function set_session ($var, $value) {
2085 // Abort in CSS mode here
2086 if ($CSS == 1) return true;
2088 // Trim value and session variable
2089 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2091 // Is the session variable set?
2092 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2093 // Remove the session
2094 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2095 unset($_SESSION[$var]);
2096 return session_unregister($var);
2097 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2099 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2100 $_SESSION[$var] = $value;
2101 return session_register($var);
2104 // Return always true if the session variable is already set.
2105 // Keept me busy for a longer while...
2106 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2109 // Check wether a boolean constant is set
2110 // Taken from user comments in PHP documentation for function constant()
2111 function isBooleanConstantAndTrue($constname) { // : Boolean
2113 if (defined($constname)) $res = (constant($constname) === true);
2117 // Check wether a session variable is set
2118 function isSessionVariableSet($var) {
2119 return (isset($_SESSION[$var]));
2122 // Returns wether the value of the session variable or NULL if not set
2123 function get_session($var) {
2124 if (!isset($_SESSION)) session_start();
2126 // Default is not found! ;-)
2129 // Is the variable there?
2130 if (isSessionVariableSet($var)) {
2131 // Then get it secured!
2132 $value = SQL_ESCAPE($_SESSION[$var]);
2140 //////////////////////////////////////////////
2142 // AUTOMATICALLY RE-GNERATED FUNCTIONS ONLY //
2144 //////////////////////////////////////////////
2146 if (!function_exists('html_entity_decode'))
2148 // Taken from documentation on www.php.net
2149 function html_entity_decode($string)
2151 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2152 $trans_tbl = array_flip($trans_tbl);
2153 return strtr($string, $trans_tbl);