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 // Prepare the content and eval() it...
143 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
146 if (empty($newContent)) {
147 // Something went wrong!
148 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
150 $OUTPUT = $newContent;
153 // Output code here, DO NOT REMOVE! ;-)
155 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
156 // Rewrite links when rewrite extension is active
157 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
158 $OUTPUT = REWRITE_LINKS($OUTPUT);
161 // Compile and run finished rendered HTML code
162 while (strpos($OUTPUT, '{!') > 0) {
163 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
167 // Output code here, DO NOT REMOVE! ;-)
172 // Output the raw HTML code
173 function OUTPUT_RAW ($HTML) {
174 // Output stripped HTML code to avoid broken JavaScript code, etc.
175 echo stripslashes($HTML);
177 // Flush the output if only _OB_CACHING is not "on"
178 if (_OB_CACHING != "on") {
184 // Add a fatal error message to the queue array
185 function ADD_FATAL ($message, $extra="") {
188 // Regular text message to add to $FATAL
191 // $message is text with a mask plus extras to insert into the text
192 $FATAL[] = sprintf($message, $extra);
196 // Load a template file and return it's content (only it's name; do not use ' or ")
197 function LOAD_TEMPLATE($template, $return=false, $content="") {
198 // Add more variables which you want to use in your template files
199 global $DATA, $_CONFIG, $username;
201 // Make all template names lowercase
202 $template = strtolower($template);
204 // Count the template load
205 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
206 $_CONFIG['num_templates']++;
209 $ACTION = SQL_ESCAPE($GLOBALS['action']);
210 $WHAT = SQL_ESCAPE($GLOBALS['what']);
212 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
213 $REFID = $GLOBALS['refid'];
216 if ($template == "member_support_form") {
217 // Support request of a member
218 $result = SQL_QUERY_ESC("SELECT sex, surname, family FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
219 array($GLOBALS['userid']), __FILE__, __LINE__);
220 list($sex, $surname, $family) = SQL_FETCHROW($result);
221 SQL_FREERESULT($result);
222 $salut = TRANSLATE_SEX($sex);
225 // Generate date/time string
226 $date_time = MAKE_DATETIME(time(), "1");
229 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
232 // Check for admin/guest/member templates
233 if (strpos($template, "admin_") > -1) {
234 // Admin template found
236 } elseif (strpos($template, "guest_") > -1) {
237 // Guest template found
239 } elseif (strpos($template, "member_") > -1) {
240 // Member template found
242 } elseif (strpos($template, "install_") > -1) {
243 // Installation template found
245 } elseif (strpos($template, "ext_") > -1) {
246 // Extension template found
248 } elseif (strpos($template, "la_") > -1) {
249 // "Logical-area" template found
252 // Test for extension
253 $test = substr($template, 0, strpos($template, "_"));
254 if (EXT_IS_ACTIVE($test)) {
255 // Set extra path to extension's name
260 ////////////////////////
261 // Generate file name //
262 ////////////////////////
263 $file = $BASE.$MODE.$template.".tpl";
265 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
266 // Select what depended header/footer template file for admin/guest/member area
267 $file2 = sprintf("%s%s%s_%s.tpl",
271 SQL_ESCAPE($GLOBALS['what'])
275 if (file_exists($file2)) $file = $file2;
277 // Remove variable from memory
281 // Does the special template exists?
282 if ((!file_exists($file)) || (!is_readable($file))) {
283 // Reset to default template
284 $file = $BASE.$template.".tpl";
287 // Now does the final template exists?
288 if ((file_exists($file)) && (is_readable($file))) {
289 // The local file does exists so we load it. :)
290 $tmpl_file = implode("", file($file));
292 // Replace ' to our own chars to preventing them being quoted
293 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
295 // Do we have to compile the code?
297 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
299 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
302 // Simply return loaded code
306 // Add surrounding HTML comments to help finding bugs faster
307 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
308 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
309 // Only admins shall see this warning or when installation mode is active
310 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
311 (".basename($file).")<br />
314 <PRE>".print_r($content, true)."</PRE>
316 <PRE>".print_r($DATA, true)."</PRE>
320 // Do we have some content to output or return?
322 // Not empty so let's put it out! ;)
324 // Return the HTML code
330 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
331 // Warning, empty output!
332 return "E:".$template."<br />\n";
336 // Send mail out to an email address
337 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML='N', $FROM="") {
338 // Compile subject line (for POINTS constant etc.)
339 $eval = "\$SUBJECT = \"".COMPILE_CODE(addslashes($SUBJECT))."\";";
341 $SUBJECT = html_entity_decode($SUBJECT);
344 if ((!eregi("@", $TO)) && ($TO > 0)) {
345 // Value detected, load email from database
346 if (EXT_IS_ACTIVE("msg")) {
347 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
350 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
351 list($TO) = SQL_FETCHROW($result_email);
352 SQL_FREERESULT($result_email);
354 } elseif ($TO == 0) {
359 // Not in PHPMailer-Mode
360 if (!CHECK_PHPMAILER_USAGE()) {
362 // Load email header template
363 $FROM = LOAD_EMAIL_TEMPLATE("header");
366 $FROM .= LOAD_EMAIL_TEMPLATE("header");
368 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
370 // Load email header template
371 $FROM = LOAD_EMAIL_TEMPLATE("header");
374 $FROM .= LOAD_EMAIL_TEMPLATE("header");
378 // Fix HTML parameter (default is no!)
379 if (empty($HTML)) $HTML = "N";
380 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
381 // In debug mode we want to display the mail instead of sending it away so we can debug this part
383 ".htmlentities(trim($FROM))."
385 Subject : ".$SUBJECT."
388 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail", true))) {
389 // Send mail as HTML away
390 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
391 } elseif (!empty($TO)) {
393 $TO = COMPILE_CODE($TO);
396 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
397 } elseif ($HTML == "N") {
399 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
403 // Check if legacy or PHPMailer command
405 function CHECK_PHPMAILER_USAGE() {
406 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
410 * Send out a raw email with PHPMailer class or legacy mail() command
412 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
413 // Shall we use PHPMailer class or legacy mode?
414 if (CHECK_PHPMAILER_USAGE()) {
415 // Use PHPMailer class with SMTP enabled
416 require_once(PATH."inc/phpmailer/class.phpmailer.php");
417 require_once(PATH."inc/phpmailer/class.smtp.php");
420 $mail = new PHPMailer();
421 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
424 $mail->SMTPAuth = true;
425 $mail->Host = SMTP_HOSTNAME;
427 $mail->Username = SMTP_USER;
428 $mail->Password = SMTP_PASSWORD;
430 $mail->From = WEBMASTER;
434 $mail->FromName = MAIN_TITLE;
435 $mail->Subject = $subject;
436 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
438 $mail->AltBody = "Your mail program required HTML support to read this mail!";
439 $mail->WordWrap = 70;
444 $mail->AddAddress($to, "");
445 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
446 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
447 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
450 // Use legacy mail() command
451 @mail($to, $subject, $msg, $from);
456 // Generate a password in a specified length or use default password length
457 function GEN_PASS($LEN = 0) {
459 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
461 // Initialize array with all allowed chars
462 $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,-,+,_,/");
464 // Initialize randomizer
465 mt_srand((double) microtime() * 1000000);
467 // Start creating password
469 for ($i = 0; $i < $LEN; $i++) {
470 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
473 // When the size is below 40 we can also add additional security by scrambling it
474 if (strlen($PASS) <= 40) {
475 // Also scramble the password
476 $PASS = scrambleString($PASS);
479 // Return the password
483 function MAKE_DATETIME ($time, $mode="0")
487 return NEVER_HAPPENED;
489 // Filter out numbers
490 $time = bigintval($time);
493 switch (GET_LANGUAGE())
495 case "de": // German date / time format
497 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
498 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
499 case "2": $ret = date("d.m.Y|H:i", $time); break;
500 case "3": $ret = date("d.m.Y", $time); break;
504 default: // Default is the US date / time format!
506 case "0": $ret = date("r", $time); break;
507 case "1": $ret = date("Y-m-d - g:i A", $time); break;
508 case "2": $ret = date("y-m-d|H:i", $time); break;
509 case "3": $ret = date("y-m-d", $time); break;
515 // Translates the american decimal dot into a german comma
516 function TRANSLATE_COMMA ($dotted, $cut=true) {
519 // Default is 3 you can change this in admin area "Misc -> Misc Options"
520 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
521 $maxComma = $_CONFIG['max_comma'];
525 // Test for commata if in cut-mode
526 $com = explode(".", $dotted);
527 if (count($com) > 1) {
528 // Commata found, so only zeros?
529 if ($com[1] == str_repeat("0", strlen($com[1]))) {
530 // Only zeros, so don't display them
534 // Don't display commatas even if there are none... ;-)
540 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
543 switch (GET_LANGUAGE()) {
545 $dotted = number_format($dotted, $maxComma, ",", ".");
549 $dotted = number_format($dotted, $maxComma, ".", ",");
553 // Return translated value
558 function DEREFERER ($URL) {
559 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
564 function TRANSLATE_SEX ($sex) {
567 case "M": $ret = SEX_M; break;
568 case "F": $ret = SEX_F; break;
569 case "C": $ret = SEX_C; break;
570 default : $ret = $sex; break;
575 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) {
590 // Prepare frametester URL
591 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
593 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
595 return $frametesterUrl;
598 function SELECTION_COUNT($array) {
600 if (is_array($array)) {
601 foreach ($array as $key => $sel) {
602 if (!empty($sel)) $ret++;
608 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) {
616 $ret = ACCOUNT_UNCONFIRMED;
620 $ret = ACCOUNT_CONFIRMED;
624 $ret = ACCOUNT_LOCKED;
628 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
634 function GET_LANGUAGE() {
635 if (!empty($_GET['mx_lang'])) {
636 // Accept only first 2 chars
637 $lang = substr($_GET['mx_lang'], 0, 2);
643 // Set default return value to default language from config
646 // Check GET variable and cookie
648 // Check if main language file does exist
649 if (file_exists(PATH."inc/language/".$lang.".php")) {
650 // Okay found, so let's update cookies
653 } elseif (!isSessionVariableSet('mx_lang')) {
654 // Return stored value from cookie
655 $ret = get_session('mx_lang');
657 // Fixes a warning before the session has the mx_lang constant
658 if (empty($ret)) $ret = DEFAULT_LANG;
663 function SET_LANGUAGE($lang) {
666 // Accept only first 2 chars!
667 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
670 set_session("mx_lang", $lang);
673 function LOAD_EMAIL_TEMPLATE($template, $content="", $UID="0") {
674 global $DATA, $_CONFIG, $REPLACER;
676 // Make sure all template names are lowercase!
677 $template = strtolower($template);
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(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;
708 // DEPRECATED switch!
711 case "bonus-mail": // Load data for the bonus mail
714 $points = TRANSLATE_COMMA($DATA[4]);
716 $TARGET_URL = $DATA[8];
717 $CATEGORY = GET_CATEGORY($DATA[9]);
721 foreach ($REPLACER as $key=>$value)
723 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
729 $BLOCKS = $_CONFIG['max_send'];
732 $PAYMENT = GET_PAYMENT($DATA[3]);
733 $TARGET_URL = $DATA[5];
734 $CATEGORY = GET_CATEGORY($DATA[6]);
738 case "order-deleted":
740 $TARGET_URL = $DATA[0];
750 case "confirm-member":
751 $points = $_CONFIG['points_register'];
754 case "confirm-referral":
762 $SEND_UID = $DATA[1];
763 $CATEGORY = GET_CATEGORY($DATA[9]);
764 $TIME = GET_PAY_POINTS($DATA[5], "time");
765 $TARGET_URL = $DATA[7];
766 $points = TRANSLATE_COMMA(GET_PAY_POINTS($DATA[5], "payment"));
767 // Warning! This ID has changed from 10 to 11!
771 foreach ($REPLACER as $key=>$value)
773 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
779 $SEND_UID = $DATA[1];
780 $CATEGORY = GET_CATEGORY($DATA[9]);
781 $TARGET_URL = $DATA[7];
786 $points = TRANSLATE_COMMA($DATA[10]);
790 if (isset($_POST['points'])) {
791 $points = bigintval($_POST['points']);
793 $points = __POINTS_VALUE;
797 case "guest_request_confirm":
804 if (EXT_IS_ACTIVE("nickname")) {
806 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
807 array(bigintval($UID)), __FILE__, __LINE__);
808 list($surname, $family, $sex, $email, $nick) = SQL_FETCHROW($result);
809 SQL_FREERESULT($result);
812 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
813 array(bigintval($UID)), __FILE__, __LINE__);
814 list($surname, $family, $sex, $email) = SQL_FETCHROW($result);
815 SQL_FREERESULT($result);
819 // Neutral sex and email address is default
824 // Translate M to male or F to female
825 $salut = TRANSLATE_SEX($sex);
827 // Store email for some functions in global data array
828 $DATA['email'] = $email;
831 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
833 // Check for admin/guest/member templates
834 if (strpos($template, "admin_") > -1) {
835 // Admin template found
836 $file = $BASE."admin/".$template.".tpl";
837 } elseif (strpos($template, "guest_") > -1) {
838 // Guest template found
839 $file = $BASE."guest/".$template.".tpl";
840 } elseif (strpos($template, "member_") > -1) {
841 // Member template found
842 $file = $BASE."member/".$template.".tpl";
844 // Test for extension
845 $test = substr($template, 0, strpos($template, "_"));
846 if (EXT_IS_ACTIVE($test)) {
847 // Set extra path to extension's name
848 $file = $BASE.$test."/".$template.".tpl";
850 // No special filename
851 $file = $BASE.$template.".tpl";
855 // Does the special template exists?
856 if ((!@file_exists($file)) || (!is_readable($file))) {
857 // Reset to default template
858 $file = $BASE.$template.".tpl";
861 // Now does the final template exists?
862 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);
876 } 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);
888 // No template name supplied!
889 $content = NO_TEMPLATE_SUPPLIED;
892 // Return compiled content
893 return COMPILE_CODE($content);
896 function MAKE_TIME($H, $M, $S, $stamp) {
897 // Extract day, month and year from given timestamp
898 $DAY = date("d", $stamp);
899 $MONTH = date("m", $stamp);
900 $YEAR = date('Y', $stamp);
902 // Create timestamp for wished time which depends on extracted date
903 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
906 function LOAD_URL($URL, $addUrlData=true) {
907 global $CSS, $_CONFIG, $link, $db, $footer;
909 // Check if http(s):// is there
910 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
911 // Make all URLs full-qualified
915 // Compile out URI codes
916 $URL = COMPILE_CODE($URL);
919 $OUTPUT = ob_get_contents();
924 // Add some data to URL if cookies are not accepted
925 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
927 // Probe for bot from search engine
928 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
929 // Search engine bot detected so let's rewrite many chars for the link
930 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
932 // Output new location link as anchor
933 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
934 } elseif (!headers_sent()) {
935 // Load URL when headers are not sent
938 debug_print_backtrace();
939 die("</pre>URL={$URL}");
941 @header ("Location: ".str_replace("&", "&", $URL));
943 // Output error message
944 include(PATH."inc/header.php");
945 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
946 include(PATH."inc/footer.php");
951 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
952 global $SEC_CHARS, $URL_CHARS;
955 // Select smaller set of chars to replace when we e.g. want to compile URLs
956 if (!$full) $ARRAY = $URL_CHARS;
960 // BEFORE 0.2.1 : Language and data constants
961 // WITH 0.2.1+ : Only language constants
962 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
964 // BEFORE 0.2.1 : Not used
965 // WITH 0.2.1+ : Data constants
966 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
969 // Compile QUOT and other non-HTML codes
970 foreach ($ARRAY['to'] as $k => $to) {
971 // Do the reversed thing as in inc/libs/security_functions.php
972 $code = str_replace($to, $ARRAY['from'][$k], $code);
975 // But shall I keep simple quotes for later use?
976 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
978 // Find $content[bla][blub] entries
979 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
981 // Are some matches found?
982 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
983 // Replace all matches
984 $matchesFound = array();
985 foreach ($matches[0] as $key=>$match) {
986 // Avoid replacing matches multiple times
987 if (!isset($matchesFound[$match])) {
989 $code = str_replace($match, "\".".$match.".\"", $code);
990 $matchesFound[$match] = 1;
993 // Take all string elements
994 if (("".bigintval($matches[4][$key])."" != $matches[4][$key]) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
995 // Replace it in the code
996 $code = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $code);
997 $matchesFound[$key."_".$matches[4][$key]] = 1;
1002 // Return compiled code
1006 /************************************************************************
1008 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1009 * $a_sort sortiert: *
1011 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1012 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1013 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1014 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1015 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1017 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1018 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1019 * Sie, dass es doch nicht so schwer ist! :-) *
1021 ************************************************************************/
1022 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1025 while ($primary_key < count($a_sort))
1027 foreach ($dummy[$a_sort[$primary_key]] as $key=>$value)
1029 foreach ($dummy[$a_sort[$primary_key]] as $key2=>$value2)
1034 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1035 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1037 elseif ($key != $key2)
1039 // Sort numbers (E.g.: 9 < 10)
1040 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1041 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1045 // We have found two different values, so let's sort whole array
1046 foreach ($dummy as $sort_key=>$sort_val)
1048 $t = $dummy[$sort_key][$key];
1049 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1050 $dummy[$sort_key][$key2] = $t;
1061 // Write back sorted array
1065 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1067 global $MONTH_DESCR; $OUT = "";
1070 // This is a yes/no selection only!
1071 if ($id > 0) $prefix .= "[".$id."]";
1072 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1076 // Begin with regular selection box here
1077 if (!empty($prefix)) $prefix .= "_";
1079 if ($id > 0) $type2 .= "[".$id."]";
1080 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1085 for ($idx = 1; $idx < 32; $idx++)
1087 $OUT .= " <OPTION value=\"".$idx."\"";
1088 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1089 $OUT .= ">".$idx."</OPTION>\n";
1093 case "month": // Month
1094 foreach ($MONTH_DESCR as $month=>$descr)
1096 $OUT .= " <OPTION value=\"".$month."\"";
1097 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1098 $OUT .= ">".$descr."</OPTION>\n";
1102 case "year": // Year
1104 $YEAR = date('Y', time());
1106 // Check if the default value is larger than minimum and bigger than actual year
1107 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1109 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1111 $OUT .= " <OPTION value=\"".$idx."\"";
1112 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1113 $OUT .= ">".$idx."</OPTION>\n";
1116 elseif ($DEFAULT == -1)
1118 // Current year minus 1
1119 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1121 $OUT .= " <OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1126 // Get current year and subtract 16 (for erotic content)
1127 $OUT .= " <OPTION value=\"1929\"><1930</OPTION>\n";
1128 $YEAR = date('Y', time()) - 16;
1129 for ($idx = 1930; $idx <= $YEAR; $idx++)
1131 $OUT .= " <OPTION value=\"".$idx."\"";
1132 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1133 $OUT .= ">".$idx."</OPTION>\n";
1140 for ($idx = 0; $idx < 60; $idx+=5)
1142 if (strlen($idx) == 1) $idx = "0".$idx;
1143 $OUT .= " <OPTION value=\"".$idx."\"";
1144 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1145 $OUT .= ">".$idx."</OPTION>\n";
1150 for ($idx = 0; $idx < 24; $idx++)
1152 if (strlen($idx) == 1) $idx = "0".$idx;
1153 $OUT .= " <OPTION value=\"".$idx."\"";
1154 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1155 $OUT .= ">".$idx."</OPTION>\n";
1160 $OUT .= " <OPTION value=\"Y\"";
1161 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1162 $OUT .= ">".YES."</OPTION>
1163 <OPTION value=\"N\"";
1164 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1165 $OUT .= ">".NO."</OPTION>\n";
1168 $OUT .= " </SELECT>\n";
1172 function TRANSLATE_YESNO($yn)
1176 case 'Y': $yn = YES; break;
1177 case 'N': $yn = NO; break;
1178 default : $yn = "??? (".$yn.")"; break;
1183 // Deprecated : $length
1186 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1189 // Fix missing _MAX constant
1190 if (!defined('_MAX')) define('_MAX', 15235);
1192 // Build server string
1193 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1196 $keys = SITE_KEY.":".DATE_KEY;
1197 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1198 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1199 $keys .= ":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']);
1200 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1202 // Build string from misc data
1203 $data = $code.":".$uid.":".$DATA;
1205 // Add more additional data
1206 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1207 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1208 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1209 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1210 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1211 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1213 // Calculate number for generating the code
1214 $a = $code + _ADD - 1;
1216 if (isset($_CONFIG['master_hash'])) {
1217 // Generate hash with master salt from modula of number with the prime number and other data
1218 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1220 // Create number from hash
1221 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1223 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1224 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1226 // Create number from hash
1227 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1230 // At least 10 numbers shall be secure enought!
1231 $len = $_CONFIG['code_length'];
1232 if ($len == 0) $len = 10;
1234 // Cut off requested counts of number
1235 $return = substr(str_replace('.', "", $rcode), 0, $len);
1237 // Done building code
1240 // Does only allow numbers
1241 function bigintval($num, $castValue = true) {
1242 // Filter all numbers out
1243 $ret = preg_replace("/[^0123456789]/", "", $num);
1248 // Insert the code in $img_code into jpeg or PNG image
1249 function GENERATE_IMAGE($img_code, $header=true) {
1251 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0))
1253 // Stop execution of function here because of over-sized code length
1258 // Return in an HTML code code
1259 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1262 switch ($_CONFIG['img_type'])
1266 $img = sprintf("%s/theme/%s/images/code_bg.jpg", PATH, GET_CURR_THEME());
1267 if ((file_exists($img)) && (is_readable($img))) {
1268 // Okay, load image and hide all errors
1269 $image = @imagecreatefromjpeg($img);
1271 // Exit function here
1278 $img = sprintf("%s/theme/%s/images/code_bg.png", PATH, GET_CURR_THEME());
1279 if ((file_exists($img)) && (is_readable($img))) {
1280 // Okay, load image and hide all errors
1281 $image = @imagecreatefrompng($img);
1283 // Exit function here
1289 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1290 $text_color = imagecolorallocate($image, 0, 0, 0);
1292 // Insert code into image
1293 imagestring($image, 5, 14, 2, $img_code, $text_color);
1295 // Return to browser
1296 header ("Content-Type: image/".$_CONFIG['img_type']);
1298 // Output image with matching image factory
1299 switch ($_CONFIG['img_type']) {
1300 case "jpg": imagejpeg($image); break;
1301 case "png": imagepng($image); break;
1304 // Remove image from memory
1305 imagedestroy($image);
1307 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false)
1309 // Calculate 15-seconds timestamp (15-seconds-steps shall be fine ;) )
1310 $timestamp = round($timestamp / 15) * 15;
1311 // Do we have a leap year?
1313 $TEST = date('Y', time()) / 4;
1314 $M1 = date("m", time());
1315 $M2 = date("m", (time() + $timestamp));
1316 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1317 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1318 // First of all years...
1319 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1321 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1323 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1325 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1327 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1329 $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));
1330 // And at last seconds...
1331 $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));
1333 // Now we convert them in seconds...
1337 // Just put all data in an array for later use
1351 $OUT = "<DIV align=\"".$align."\">\n";
1352 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1354 if (ereg('Y', $display) || (empty($display)))
1356 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1358 if (ereg("M", $display) || (empty($display)))
1360 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1362 if (ereg("W", $display) || (empty($display)))
1364 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1366 if (ereg("D", $display) || (empty($display)))
1368 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1370 if (ereg("h", $display) || (empty($display)))
1372 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1374 if (ereg("m", $display) || (empty($display)))
1376 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1378 if (ereg("s", $display) || (empty($display)))
1380 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1384 if (ereg('Y', $display) || (empty($display)))
1386 // Generate year selection
1387 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1388 for ($idx = 0; $idx <= 10; $idx++)
1390 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1391 if ($idx == $Y) $OUT .= " selected default";
1392 $OUT .= ">".$idx."</OPTION>\n";
1394 $OUT .= " </SELECT></TD>\n";
1398 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1400 if (ereg("M", $display) || (empty($display)))
1402 // Generate month selection
1403 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1404 for ($idx = 0; $idx <= 11; $idx++)
1406 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1407 if ($idx == $M) $OUT .= " selected default";
1408 $OUT .= ">".$idx."</OPTION>\n";
1410 $OUT .= " </SELECT></TD>\n";
1414 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1416 if (ereg("W", $display) || (empty($display)))
1418 // Generate week selection
1419 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1420 for ($idx = 0; $idx <= 4; $idx++)
1422 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1423 if ($idx == $W) $OUT .= " selected default";
1424 $OUT .= ">".$idx."</OPTION>\n";
1426 $OUT .= " </SELECT></TD>\n";
1430 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1432 if (ereg("D", $display) || (empty($display)))
1434 // Generate day selection
1435 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1436 for ($idx = 0; $idx <= 31; $idx++)
1438 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1439 if ($idx == $D) $OUT .= " selected default";
1440 $OUT .= ">".$idx."</OPTION>\n";
1442 $OUT .= " </SELECT></TD>\n";
1446 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1448 if (ereg("h", $display) || (empty($display)))
1450 // Generate hour selection
1451 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1452 for ($idx = 0; $idx <= 23; $idx++)
1454 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1455 if ($idx == $h) $OUT .= " selected default";
1456 $OUT .= ">".$idx."</OPTION>\n";
1458 $OUT .= " </SELECT></TD>\n";
1462 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1464 if (ereg("m", $display) || (empty($display)))
1466 // Generate minute selection
1467 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1468 for ($idx = 0; $idx <= 59; $idx++)
1470 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1471 if ($idx == $m) $OUT .= " selected default";
1472 $OUT .= ">".$idx."</OPTION>\n";
1474 $OUT .= " </SELECT></TD>\n";
1478 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1480 if (ereg("s", $display) || (empty($display)))
1482 // Generate second selection
1483 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1484 for ($idx = 0; $idx <= 45; $idx+=15)
1486 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1487 if ($idx == $s) $OUT .= " selected default";
1488 $OUT .= ">".$idx."</OPTION>\n";
1490 $OUT .= " </SELECT></TD>\n";
1494 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1497 $OUT .= "</TABLE>\n";
1499 // Return generated HTML code
1504 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1506 // Do we have a leap year?
1508 $TEST = date('Y', time()) / 4;
1509 $M1 = date("m", time());
1510 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1511 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1512 // First add years...
1513 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1515 $ret += $POST[$prefix."_mo"] * 2628000;
1517 $ret += $POST[$prefix."_we"] * 604800;
1519 $ret += $POST[$prefix."_da"] * 86400;
1521 $ret += $POST[$prefix."_ho"] * 3600;
1523 $ret += $POST[$prefix."_mi"] * 60;
1524 // And at last seconds...
1525 $ret += $POST[$prefix."_se"];
1526 // Return calculated value
1529 // Sends out mail to all administrators
1530 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1531 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1532 // Trim template name
1533 $template = trim($template);
1535 // Load email template
1536 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1538 if (GET_EXT_VERSION("admins") < "0.4.0") {
1539 // Older version detected!
1540 return SEND_ADMIN_EMAILS($subj, $msg);
1543 // Check which admin shall receive this mail
1544 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1545 array($template), __FILE__, __LINE__);
1546 if (SQL_NUMROWS($result) == 0) {
1547 // Create new entry (to all admins)
1548 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1549 array($template), __FILE__, __LINE__);
1551 // Load admin IDs...
1553 while(list($aid) = SQL_FETCHROW($result)) {
1558 SQL_FREERESULT($result);
1560 // "implode" IDs and query string
1561 $aid = implode(",", $aids);
1563 // Add line to userlog
1564 USERLOG_ADD_LINE($subj, $msg, $UID);
1566 } elseif ($aid == "0") {
1567 // Select all email adresses
1568 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1570 // If Admin-ID is not "to-all" select
1571 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1575 // Load email addresses and send away
1576 while (list($email) = SQL_FETCHROW($result)) {
1577 SEND_EMAIL($email, $subj, $msg);
1581 SQL_FREERESULT($result);
1584 function CREATE_FANCY_TIME($stamp) {
1585 // Get data array with years/months/weeks/days/...
1586 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1588 foreach($data as $k=>$v) {
1590 // Value is greater than 0 "eval" data to return string
1591 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1597 // Remove first "comma,null" string
1598 $ret = substr($ret, 2);
1602 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1603 $SEP = ""; $TOP = "";
1606 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1610 for ($page = 1; $page <= $PAGES; $page++) {
1611 // Is the page currently selected or shall we generate a link to it?
1612 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1613 // Is currently selected, so only highlight it
1614 $NAV .= "<STRONG>-";
1616 // Open anchor tag and add base URL
1617 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1619 // Add userid when we shall show all mails from a single member
1620 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1622 // Close open anchor tag
1626 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1627 // Is currently selected, so only highlight it
1628 $NAV .= "-</STRONG>";
1634 // Add seperator if we have not yet reached total pages
1635 if ($page < $PAGES) $NAV .= " | ";
1638 // Define constants only once
1639 if (!defined('__NAV_OUTPUT')) {
1640 define('__NAV_OUTPUT' , $NAV);
1641 define('__NAV_COLSPAN', $colspan);
1642 define('__NAV_TOP' , $TOP);
1643 define('__NAV_SEP' , $SEP);
1646 // Load navigation template
1647 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1650 // Return generated HTML-Code
1658 // Extract host from script name
1659 function EXTRACT_HOST (&$script) {
1660 // Use default SERVER_URL by default... ;) So?
1663 // Is this URL valid?
1664 if (substr($script, 0, 7) == "http://") {
1665 // Use the hostname from script URL as new hostname
1666 $url = substr($script, 7);
1667 $extract = explode("/", $url);
1669 // Done extracting the URL :)
1672 // Extract host name
1673 $host = str_replace("http://", "", $url);
1674 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1676 // Generate relative URL
1677 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1678 if (substr(strtolower($script), 0, 7) == "http://") {
1679 // But only if http:// is in front!
1680 $script = substr($script, (strlen($url) + 7));
1681 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1683 $script = substr($script, (strlen($url) + 8));
1686 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1687 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1693 // Send a GET request
1694 function GET_URL ($script) {
1695 // Compile the script name
1696 $script = COMPILE_CODE($script);
1698 // Extract host name from script
1699 $host = EXTRACT_HOST($script);
1701 // Generate GET request header
1702 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1703 $request .= "Host: " . $host . "\r\n";
1704 $request .= "Referer: " . URL . "/admin.php\r\n";
1705 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1706 $request .= "Content-Type: text/plain\r\n";
1707 $request .= "Cache-Control: no-cache\r\n";
1708 $request .= "Connection: Close\r\n\r\n";
1710 // Send the raw request
1711 $response = SEND_RAW_REQUEST($host, $request);
1713 // Return the result to the caller function
1717 // Send a POST request
1718 function POST_URL ($script, $postData) {
1719 // Is postData an array?
1720 if (!is_array($postData)) {
1722 return array("", "", "");
1725 // Compile the script name
1726 $script = COMPILE_CODE($script);
1728 // Extract host name from script
1729 $host = EXTRACT_HOST($script);
1731 // Construct request
1732 $data = http_build_query($postData, '', '&');
1734 // Generate POST request header
1735 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1736 $request .= "Host: " . $host . "\r\n";
1737 $request .= "Referer: " . URL . "/admin.php\r\n";
1738 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1739 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1740 $request .= "Content-length: " . strlen($data) . "\r\n";
1741 $request .= "Cache-Control: no-cache\r\n";
1742 $request .= "Connection: Close\r\n\r\n";
1745 // Send the raw request
1746 $response = SEND_RAW_REQUEST($host, $request);
1748 // Return the result to the caller function
1752 // Sends a raw request to another host
1753 function SEND_RAW_REQUEST ($host, $request) {
1757 $response = array("", "", "");
1759 // Default is not to use proxy
1762 // Are proxy settins set?
1763 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1769 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1771 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1773 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1777 if (!is_resource($fp)) {
1784 // Generate CONNECT request header
1785 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1786 $proxyTunnel .= "Host: ".$host."\r\n";
1788 // Use login data to proxy? (username at least!)
1789 if (!empty($_CONFIG['proxy_username'])) {
1791 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1792 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1795 // Add last new-line
1796 $proxyTunnel .= "\r\n";
1797 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1800 fputs($fp, $proxyTunnel);
1804 // No response received
1808 // Read the first line
1809 $resp = trim(fgets($fp, 10240));
1810 $respArray = explode(" ", $resp);
1811 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1812 // Invalid response!
1818 fputs($fp, $request);
1822 $response[] = trim(fgets($fp, 1024));
1828 // Skip first empty lines
1830 foreach ($resp as $idx => $line) {
1832 $line = trim($line);
1834 // Is this line empty?
1837 array_shift($response);
1839 // Abort on first non-empty line
1844 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1846 // Proxy agent found?
1847 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1848 // Proxy header detected, so remove two lines
1849 array_shift($response);
1850 array_shift($response);
1853 // Was the request successfull?
1854 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1855 // Not found / access forbidden
1856 $response = array("", "", "");
1862 // Taken from www.php.net eregi() user comments
1863 function VALIDATE_EMAIL($email) {
1865 $email = COMPILE_CODE($email);
1867 // Check first part of email address
1868 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1871 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1874 $regex = "^".$first."@".$domain."$";
1876 // Return check result
1877 return eregi($regex, $email);
1879 // Function taken from user comments on www.php.net / function eregi()
1880 function VALIDATE_URL ($URL, $compile=true) {
1881 // Trim URL a little
1882 $URL = trim(urldecode($URL));
1883 //* DEBUG: */ echo $URL."<br />";
1885 // Compile some chars out...
1886 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1887 //* DEBUG: */ echo $URL."<br />";
1889 // Check for the extension filter
1890 if (EXT_IS_ACTIVE("filter")) {
1891 // Use the extension's filter set
1892 return FILTER_VALIDATE_URL($URL, false);
1895 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1896 // https:// in front of the URLs
1897 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1900 function MEMBER_ACTION_LINKS($uid, $status="") {
1901 // Define all main targets
1902 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1904 // Begin of navigation links
1905 $eval = "\$OUT = \"[ ";
1907 foreach ($TARGETS as $tar) {
1908 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1909 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1910 if (($tar == "lock_user") && ($status == "LOCKED")) {
1911 // Locked accounts shall be unlocked
1912 $eval .= "UNLOCK_USER";
1914 // All other status is fine
1915 $eval .= strtoupper($tar);
1917 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1918 if (($tar == "lock_user") && ($status == "LOCKED")) {
1919 // Locked accounts shall be unlocked
1920 $eval .= "UNLOCK_USER";
1922 // All other status is fine
1923 $eval .= strtoupper($tar);
1925 $eval .= ".\"</A></SPAN> | ";
1928 // Finish navigation link
1929 $eval = substr($eval, 0, -7)."]\";";
1935 // Function for backward-compatiblity
1936 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1937 // Load it from the register extension
1938 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1940 // Generate an email link
1941 function CREATE_EMAIL_LINK($email, $table="admins") {
1942 // Default email link (INSECURE! Spammer can read this by harvester programs)
1943 $EMAIL = "mailto:".$email;
1945 // Check for several extensions
1946 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1947 // Create email link for contacting admin in guest area
1948 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1949 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1950 // Create email link for contacting a member within admin area (or later in other areas, too?)
1951 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1952 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1953 // Create email link to contact sponsor within admin area (or like the link above?)
1954 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1957 // Shall I close the link when there is no admin?
1958 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1960 // Return email link
1963 // Generate a hash for extra-security for all passwords
1964 function generateHash ($plainText, $salt = "") {
1965 global $_CONFIG, $_SERVER;
1967 // Is the required extension "sql_patches" there and a salt is not given?
1968 if (((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) && (empty($salt))) {
1969 // Extension sql_patches is missing/outdated so we return the plain text
1973 // Do we miss an arry element here?
1974 if (!isset($_CONFIG['file_hash'])) {
1976 print(__FUNCTION__.":<pre>");
1977 debug_print_backtrace();
1981 // When the salt is empty build a new one, else use the first x configured characters as the salt
1983 // Build server string
1984 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1987 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']).":".$_CONFIG['master_salt'];
1990 $data = $plainText.":".uniqid(rand(), true).":".time();
1992 // Calculate number for generating the code
1993 $a = time() + _ADD - 1;
1995 // Generate SHA1 sum from modula of number and the prime number
1996 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1997 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br>";
1998 $sha1 = scrambleString($sha1);
1999 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br>";
2000 //* DEBUG: */ $sha1b = descrambleString($sha1);
2001 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br>";
2003 // Generate the password salt string
2004 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
2005 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2008 $salt = substr($salt, 0, $_CONFIG['salt_length']);
2009 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2013 return $salt.sha1($salt.$plainText);
2016 function scrambleString($str) {
2022 // Final check, in case of failture it will return unscrambled string
2023 if (strlen($str) > 40) {
2024 // The string is to long
2026 } elseif (strlen($str) == 40) {
2028 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2030 // Generate new numbers
2031 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2034 // Scramble string here
2035 //* DEBUG: */ echo "***Original=".$str."***<br />";
2036 for ($idx = 0; $idx < strlen($str); $idx++) {
2037 // Get char on scrambled position
2038 $char = substr($str, $scrambleNums[$idx], 1);
2040 // Add it to final output string
2041 $scrambled .= $char;
2044 // Return scrambled string
2045 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2049 function descrambleString($str)
2052 // Scramble only 40 chars long strings
2053 if (strlen($str) != 40) return $str;
2055 // Load numbers from config
2056 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2059 if (count($scrambleNums) != 40) return $str;
2061 // Begin descrambling
2062 $orig = str_repeat(" ", 40);
2063 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2064 for ($idx = 0; $idx < 40; $idx++)
2066 $char = substr($str, $idx, 1);
2067 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2070 // Return scrambled string
2071 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2075 function genScrambleString($len) {
2076 // Prepare randomizer and array for the numbers
2077 mt_srand((double) microtime() * 1000000);
2078 $scrambleNumbers = array();
2080 // First we need to setup randomized numbers from 0 to 31
2081 for ($idx = 0; $idx < $len; $idx++) {
2083 $rand = mt_rand(0, ($len -1));
2085 // Check for it by creating more numbers
2086 while (array_key_exists($rand, $scrambleNumbers)) {
2087 $rand = mt_rand(0, ($len -1));
2091 $scrambleNumbers[$rand] = $rand;
2094 // So let's create the string for storing it in database
2095 $scrambleString = implode(":", $scrambleNumbers);
2096 return $scrambleString;
2098 // Append data like session ID referral ID to the given URL which would
2099 // normally be stored in cookies
2100 function ADD_URL_DATA($URL)
2105 // Determine URL binder
2107 if (strpos($URL, "?") !== false) $BIND = "&";
2109 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2110 // Cookies are not accepted
2111 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2112 // Cookie found in URL
2113 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2114 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2115 // Not found! So let's set default here
2116 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2119 // Is there already added data? Then change the binder
2120 if (!empty($ADD)) $BIND = "&";
2123 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2124 // Add session from URL
2125 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2127 // Add current session
2128 $ADD .= $BIND."PHPSESSID=".session_id();
2132 // Add all together and return it
2135 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2136 function generatePassString($passHash) {
2139 // Return vanilla password hash
2142 // Is a secret key and master salt already initialized?
2143 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2144 // Only calculate when the secret key is generated
2145 $newHash = ""; $start = 9;
2146 for ($idx = 0; $idx < 10; $idx++) {
2147 $part1 = hexdec(substr($passHash, $start, 4));
2148 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2149 $mod = dechex($idx);
2150 if ($part1 > $part2) {
2151 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2152 } elseif ($part2 > $part1) {
2153 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2155 $mod = substr(round($mod), 0, 4);
2156 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2157 //* DEBUG: */ echo "*".$start."=".$mod."*<br>";
2162 //* DEBUG: */ print($passHash."<br>".$newHash." (".strlen($newHash).")");
2163 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2164 //* DEBUG: */ print($ret."<br />\n");
2167 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2168 $ret = md5($passHash);
2169 //* DEBUG: */ echo "++".$ret."++<br />\n";
2176 // Fix "deleted" cookies
2177 function FIX_DELETED_COOKIES ($cookies) {
2178 // Is this an array with entries?
2179 if ((is_array($cookies)) && (count($cookies) > 0)) {
2180 // Then check all cookies if they are marked as deleted!
2181 foreach ($cookies as $cookieName) {
2182 // Is the cookie set to "deleted"?
2183 if (get_session($cookieName) == "deleted") {
2184 set_session($cookieName, "");
2190 // Output error messages in a fasioned way and die...
2191 function mxchange_die ($msg) {
2194 // Load the message template
2195 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2198 include(PATH."inc/footer.php");
2204 // Display parsing time and number of SQL queries in footer
2205 function DISPLAY_PARSING_TIME_FOOTER() {
2206 global $startTime, $_CONFIG;
2207 $endTime = microtime(true);
2209 // Is the timer started?
2210 if (!isset($GLOBALS['startTime'])) {
2215 // "Explode" both times
2216 $start = explode(" ", $GLOBALS['startTime']);
2217 $end = explode(" ", $endTime);
2218 $runTime = $end[0] - $start[0];
2219 if ($runTime < 0) $runTime = 0;
2220 $runTime = TRANSLATE_COMMA($runTime);
2224 'runtime' => $runTime,
2225 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2226 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2229 // Load the template
2230 LOAD_TEMPLATE("show_timings", false, $content);
2233 // Unset/set session variables
2234 function set_session ($var, $value) {
2237 // Abort in CSS mode here
2238 if ($CSS == 1) return true;
2240 // Trim value and session variable
2241 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2243 // Is the session variable set?
2244 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2245 // Remove the session
2246 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2247 unset($_SESSION[$var]);
2248 return session_unregister($var);
2249 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2251 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2252 $_SESSION[$var] = $value;
2253 return session_register($var);
2254 } elseif (!empty($value)) {
2256 $_SESSION[$var] = $value;
2258 // Something bad happens!
2259 return false; // Hope this doesn't make so much trouble???
2262 // Return always true if the session variable is already set.
2263 // Keept me busy for a longer while...
2264 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2268 // Check wether a boolean constant is set
2269 // Taken from user comments in PHP documentation for function constant()
2270 function isBooleanConstantAndTrue($constname) { // : Boolean
2272 if (defined($constname)) $res = (constant($constname) === true);
2276 // Check wether a session variable is set
2277 function isSessionVariableSet($var) {
2278 return (isset($_SESSION[$var]));
2280 // Returns wether the value of the session variable or NULL if not set
2281 function get_session($var) {
2282 // Default is not found! ;-)
2285 // Is the variable there?
2286 if (isSessionVariableSet($var)) {
2287 // Then get it secured!
2288 $value = SQL_ESCAPE($_SESSION[$var]);
2294 // Send notification to admin
2295 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content="", $uid="0") {
2296 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2298 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2300 // Send outdated way
2301 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2302 SEND_ADMIN_EMAILS($subject, $msg);
2305 // Destroy user session
2306 function destroy_user_session () {
2307 // Remove all user data from session
2308 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2310 // Merges an array together but only if both are arrays
2311 function merge_array ($array1, $array2) {
2312 // Are both an array?
2313 if ((is_array($array1)) && (is_array($array2))) {
2314 // Merge all together
2315 return array_merge($array1, $array2);
2316 } elseif (is_array($array1)) {
2317 // Return left array
2321 // Something wired happened here...
2322 print(__FUNCTION__.":<pre>");
2323 debug_print_backtrace();
2326 // Debug message logger
2327 function DEBUG_LOG ($message) {
2328 // Is debug mode enabled?
2329 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
2330 // Log this message away
2331 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2332 fwrite($fp, date("d.m.Y|H:i:s", time())."|{$message}\n");
2336 // Reads a directory with PHP files in and gets only files back
2337 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2341 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2344 while ($baseFile = readdir($dirPointer)) {
2345 // Load file only if extension is active
2347 $file = $baseDir.$baseFile;
2349 // Is this a valid reset file?
2350 if ((is_file($file)) && (is_readable($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2351 // Remove both for extension name
2352 $extName = substr($baseFile, strlen($prefix), -4);
2355 $extId = GET_EXT_ID($extName);
2357 // Is the extension valid and active?
2358 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2359 // Then add this file
2366 closedir($dirPointer);
2368 // Return array with include files
2371 // Load more reset scripts
2372 function RESET_ADD_INCLUDES () {
2373 global $_CONFIG, $INC_POOL;
2375 // Is the reset set or old sql_patches?
2376 if ((!isBooleanConstantAndTrue('__DAILY_RESET')) || (GET_EXT_VERSION("sql_patches") < "0.4.5")) {
2381 // Get more daily reset scripts
2382 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_"));
2384 // Create current week mark
2385 $currWeek = date("W", time());
2388 if ($_CONFIG['last_week'] != $currWeek) {
2389 // Include weekly reset scripts
2390 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2393 UPDATE_CONFIG("last_week", $currWeek);
2396 // Create current month mark
2397 $currMonth = date("m", time());
2400 if ($_CONFIG['last_month'] != $currMonth) {
2401 // Include monthly reset scripts
2402 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2405 UPDATE_CONFIG("last_month", $currMonth);
2409 //////////////////////////////////////////////////
2411 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2413 //////////////////////////////////////////////////
2415 if (!function_exists('html_entity_decode')) {
2416 // Taken from documentation on www.php.net
2417 function html_entity_decode($string) {
2418 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2419 $trans_tbl = array_flip($trans_tbl);
2420 return strtr($string, $trans_tbl);