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) {
57 // Count tables so we can generate CSS classes for every table... :-)
59 // Class is empty so count one up and create a class
60 $table_cnt++; $CLASS = "class".$table_cnt;
62 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
64 // Shall I add the classes to TABLE and TD or only to TD?
65 if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
68 if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
71 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
73 // Vertical align is given
74 if (!empty($VALIGN)) $OUT .= " valign=\"".$VALIGN."\"";
75 $OUT .= ">\n<TR>\n<TD";
76 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
77 $OUT .= " class=\"".$CLASS."\">";
81 // Close a table (you may want to add some footer stuff here)
82 function CLOSE_TABLE($ADD="") {
83 OUTPUT_HTML(" </TD>\n</TR>");
84 if (!empty($ADD)) OUTPUT_HTML($ADD);
85 OUTPUT_HTML("</TABLE>");
88 // Output HTML code directly or "render" it. You addionally switch the new-line character off
89 function OUTPUT_HTML($HTML, $NEW_LINE = true) {
90 // Some global variables
91 global $OUTPUT, $footer, $CSS;
93 // Do we have HTML-Code here?
95 // Yes, so we handle it as you have configured
99 // That's why you don't need any \n at the end of your HTML code... :-)
100 if (_OB_CACHING == "on") {
101 // Output into PHP's internal buffer
104 // That's why you don't need any \n at the end of your HTML code... :-)
105 if ($NEW_LINE) echo "\n";
107 // Render mode for old or lame servers...
110 // That's why you don't need any \n at the end of your HTML code... :-)
111 if ($NEW_LINE) $OUTPUT .= "\n";
116 // If we are switching from render to direct output rendered code
117 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
119 // The same as above... ^
121 if ($NEW_LINE) echo "\n";
125 // Huh, something goes wrong or maybe you have edited config.php ???
126 die ("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
129 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
130 // Output cached HTML code
131 $OUTPUT = ob_get_contents();
133 // Clear output buffer for later output
136 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
137 $OUTPUT = REWRITE_LINKS($OUTPUT);
140 // Compile and run finished rendered HTML code
141 while (strpos($OUTPUT, '{!') > 0) {
142 // Prepare the content and eval() it...
144 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
147 if (empty($newContent)) {
148 // Something went wrong!
149 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
151 $OUTPUT = $newContent;
154 // Output code here, DO NOT REMOVE! ;-)
156 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
157 // Rewrite links when rewrite extension is active
158 if ((EXT_IS_ACTIVE("rewrite", true)) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
159 $OUTPUT = REWRITE_LINKS($OUTPUT);
162 // Compile and run finished rendered HTML code
163 while (strpos($OUTPUT, '{!') > 0) {
164 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
168 // Output code here, DO NOT REMOVE! ;-)
173 // Output the raw HTML code
174 function OUTPUT_RAW ($HTML) {
175 // Output stripped HTML code to avoid broken JavaScript code, etc.
176 echo stripslashes($HTML);
178 // Flush the output if only _OB_CACHING is not "on"
179 if (_OB_CACHING != "on") {
185 // Add a fatal error message to the queue array
186 function ADD_FATAL ($message, $extra="") {
189 // Regular text message to add to $FATAL
192 // $message is text with a mask plus extras to insert into the text
193 $FATAL[] = sprintf($message, $extra);
197 // Load a template file and return it's content (only it's name; do not use ' or ")
198 function LOAD_TEMPLATE($template, $return=false, $content="") {
199 // Add more variables which you want to use in your template files
200 global $DATA, $_CONFIG, $username;
202 // Make all template names lowercase
203 $template = strtolower($template);
205 // Count the template load
206 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
207 $_CONFIG['num_templates']++;
210 $ACTION = SQL_ESCAPE($GLOBALS['action']);
211 $WHAT = SQL_ESCAPE($GLOBALS['what']);
213 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
214 $REFID = $GLOBALS['refid'];
217 if ($template == "member_support_form") {
218 // Support request of a member
219 $result = SQL_QUERY_ESC("SELECT sex, surname, family FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
220 array($GLOBALS['userid']), __FILE__, __LINE__);
221 list($sex, $surname, $family) = SQL_FETCHROW($result);
222 SQL_FREERESULT($result);
223 $salut = TRANSLATE_SEX($sex);
226 // Generate date/time string
227 $date_time = MAKE_DATETIME(time(), "1");
230 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
233 // Check for admin/guest/member templates
234 if (strpos($template, "admin_") > -1) {
235 // Admin template found
237 } elseif (strpos($template, "guest_") > -1) {
238 // Guest template found
240 } elseif (strpos($template, "member_") > -1) {
241 // Member template found
243 } elseif (strpos($template, "install_") > -1) {
244 // Installation template found
246 } elseif (strpos($template, "ext_") > -1) {
247 // Extension template found
249 } elseif (strpos($template, "la_") > -1) {
250 // "Logical-area" template found
253 // Test for extension
254 $test = substr($template, 0, strpos($template, "_"));
255 if (EXT_IS_ACTIVE($test)) {
256 // Set extra path to extension's name
261 ////////////////////////
262 // Generate file name //
263 ////////////////////////
264 $file = $BASE.$MODE.$template.".tpl";
266 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
267 // Select what depended header/footer template file for admin/guest/member area
268 $file2 = sprintf("%s%s%s_%s.tpl",
272 SQL_ESCAPE($GLOBALS['what'])
276 if (FILE_READABLE($file2)) $file = $file2;
278 // Remove variable from memory
282 // Does the special template exists?
283 if (!FILE_READABLE($file)) {
284 // Reset to default template
285 $file = $BASE.$template.".tpl";
288 // Now does the final template exists?
289 if (FILE_READABLE($file)) {
290 // The local file does exists so we load it. :)
291 $tmpl_file = implode("", file($file));
293 // Replace ' to our own chars to preventing them being quoted
294 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
296 // Do we have to compile the code?
298 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
300 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
303 // Simply return loaded code
307 // Add surrounding HTML comments to help finding bugs faster
308 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
309 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
310 // Only admins shall see this warning or when installation mode is active
311 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
312 (".basename($file).")<br />
315 <PRE>".print_r($content, true)."</PRE>
317 <PRE>".print_r($DATA, true)."</PRE>
321 // Do we have some content to output or return?
323 // Not empty so let's put it out! ;)
325 // Return the HTML code
331 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
332 // Warning, empty output!
333 return "E:".$template."<br />\n";
337 // Send mail out to an email address
338 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML='N', $FROM="") {
339 // Compile subject line (for POINTS constant etc.)
340 $eval = "\$SUBJECT = \"".COMPILE_CODE(addslashes($SUBJECT))."\";";
342 $SUBJECT = html_entity_decode($SUBJECT);
345 if ((!eregi("@", $TO)) && ($TO > 0)) {
346 // Value detected, load email from database
347 if (EXT_IS_ACTIVE("msg")) {
348 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
351 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
352 list($TO) = SQL_FETCHROW($result_email);
353 SQL_FREERESULT($result_email);
355 } elseif ($TO == 0) {
360 // Not in PHPMailer-Mode
361 if (!CHECK_PHPMAILER_USAGE()) {
363 // Load email header template
364 $FROM = LOAD_EMAIL_TEMPLATE("header");
367 $FROM .= LOAD_EMAIL_TEMPLATE("header");
369 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
371 // Load email header template
372 $FROM = LOAD_EMAIL_TEMPLATE("header");
375 $FROM .= LOAD_EMAIL_TEMPLATE("header");
379 // Fix HTML parameter (default is no!)
380 if (empty($HTML)) $HTML = "N";
381 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
382 // In debug mode we want to display the mail instead of sending it away so we can debug this part
384 ".htmlentities(trim($FROM))."
386 Subject : ".$SUBJECT."
389 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail", true))) {
390 // Send mail as HTML away
391 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
392 } elseif (!empty($TO)) {
394 $TO = COMPILE_CODE($TO);
397 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
398 } elseif ($HTML == "N") {
400 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
404 // Check if legacy or PHPMailer command
406 function CHECK_PHPMAILER_USAGE() {
407 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
411 * Send out a raw email with PHPMailer class or legacy mail() command
413 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
414 // Shall we use PHPMailer class or legacy mode?
415 if (CHECK_PHPMAILER_USAGE()) {
416 // Use PHPMailer class with SMTP enabled
417 require_once(PATH."inc/phpmailer/class.phpmailer.php");
418 require_once(PATH."inc/phpmailer/class.smtp.php");
421 $mail = new PHPMailer();
422 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
425 $mail->SMTPAuth = true;
426 $mail->Host = SMTP_HOSTNAME;
428 $mail->Username = SMTP_USER;
429 $mail->Password = SMTP_PASSWORD;
431 $mail->From = WEBMASTER;
435 $mail->FromName = MAIN_TITLE;
436 $mail->Subject = $subject;
437 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
439 $mail->AltBody = "Your mail program required HTML support to read this mail!";
440 $mail->WordWrap = 70;
445 $mail->AddAddress($to, "");
446 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
447 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
448 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
451 // Use legacy mail() command
452 @mail($to, $subject, $msg, $from);
457 // Generate a password in a specified length or use default password length
458 function GEN_PASS($LEN = 0) {
460 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
462 // Initialize array with all allowed chars
463 $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,-,+,_,/");
465 // Initialize randomizer
466 mt_srand((double) microtime() * 1000000);
468 // Start creating password
470 for ($i = 0; $i < $LEN; $i++) {
471 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
474 // When the size is below 40 we can also add additional security by scrambling it
475 if (strlen($PASS) <= 40) {
476 // Also scramble the password
477 $PASS = scrambleString($PASS);
480 // Return the password
484 function MAKE_DATETIME ($time, $mode="0")
488 return NEVER_HAPPENED;
490 // Filter out numbers
491 $time = bigintval($time);
494 switch (GET_LANGUAGE())
496 case "de": // German date / time format
498 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
499 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
500 case "2": $ret = date("d.m.Y|H:i", $time); break;
501 case "3": $ret = date("d.m.Y", $time); break;
505 default: // Default is the US date / time format!
507 case "0": $ret = date("r", $time); break;
508 case "1": $ret = date("Y-m-d - g:i A", $time); break;
509 case "2": $ret = date("y-m-d|H:i", $time); break;
510 case "3": $ret = date("y-m-d", $time); break;
516 // Translates the american decimal dot into a german comma
517 function TRANSLATE_COMMA ($dotted, $cut=true) {
520 // Default is 3 you can change this in admin area "Misc -> Misc Options"
521 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
522 $maxComma = $_CONFIG['max_comma'];
526 // Test for commata if in cut-mode
527 $com = explode(".", $dotted);
528 if (count($com) > 1) {
529 // Commata found, so only zeros?
530 if ($com[1] == str_repeat("0", strlen($com[1]))) {
531 // Only zeros, so don't display them
535 // Don't display commatas even if there are none... ;-)
541 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
544 switch (GET_LANGUAGE()) {
546 $dotted = number_format($dotted, $maxComma, ",", ".");
550 $dotted = number_format($dotted, $maxComma, ".", ",");
554 // Return translated value
559 function DEREFERER ($URL) {
560 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
565 function TRANSLATE_SEX ($sex) {
568 case "M": $ret = SEX_M; break;
569 case "F": $ret = SEX_F; break;
570 case "C": $ret = SEX_C; break;
571 default : $ret = $sex; break;
576 function GET_POOL_TYPE($PT) {
579 case "TEMP" : $ret = POOL_TEMP; break;
580 case "SEND" : $ret = POOL_SEND; break;
581 case "NEW" : $ret = POOL_NEW; break;
582 case "ADMIN" : $ret = POOL_ADMIN; break;
583 case "ACTIVE" : $ret = POOL_ACTIVE; break;
584 case "DELETED": $ret = POOL_DELETED; break;
585 default : $ret = POOL_UNKNOWN." (".$PT.")"; break;
590 function FRAMETESTER($URL) {
591 // Prepare frametester URL
592 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
594 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
596 return $frametesterUrl;
599 function SELECTION_COUNT($array) {
601 if (is_array($array)) {
602 foreach ($array as $key => $sel) {
603 if (!empty($sel)) $ret++;
609 function IMG_CODE ($code, $type, $DATA, $uid) {
610 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
613 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_READABLE(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 // Make sure all template names are lowercase!
678 $template = strtolower($template);
680 // Keept for backward-compatiblity (please replace these variables against our new {--CONST--} syntax!)
681 $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
682 $surname = ""; $family = ""; $nick = ""; $sex = "N";
684 // Prepare IP number and User Agent
685 $REMOTE_ADDR = getenv('REMOTE_ADDR');
686 $HTTP_USER_AGENT = getenv('HTTP_USER_AGENT');
689 if (isSessionVariableSet('admin_login')) {
691 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
692 array(get_session('admin_login')), __FILE__, __LINE__);
693 list($ADMIN) = SQL_FETCHROW($result);
694 SQL_FREERESULT($result);
697 // Expiration in a nice output format
698 if ($_CONFIG['auto_purge'] == 0) {
699 // Will never expire!
700 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
701 } elseif (function_exists('CREATE_FANCY_TIME')) {
702 // Create nice date string
703 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
706 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
709 // DEPRECATED switch!
712 case "bonus-mail": // Load data for the bonus mail
715 $points = TRANSLATE_COMMA($DATA[4]);
717 $TARGET_URL = $DATA[8];
718 $CATEGORY = GET_CATEGORY($DATA[9]);
722 foreach ($REPLACER as $key => $value)
724 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
730 $BLOCKS = $_CONFIG['max_send'];
733 $PAYMENT = GET_PAYMENT($DATA[3]);
734 $TARGET_URL = $DATA[5];
735 $CATEGORY = GET_CATEGORY($DATA[6]);
739 case "order-deleted":
741 $TARGET_URL = $DATA[0];
751 case "confirm-member":
752 $points = $_CONFIG['points_register'];
755 case "confirm-referral":
763 $SEND_UID = $DATA[1];
764 $CATEGORY = GET_CATEGORY($DATA[9]);
765 $TIME = GET_PAY_POINTS($DATA[5], "time");
766 $TARGET_URL = $DATA[7];
767 $points = TRANSLATE_COMMA(GET_PAY_POINTS($DATA[5], "payment"));
768 // Warning! This ID has changed from 10 to 11!
772 foreach ($REPLACER as $key => $value)
774 if (isset($DATA[$key])) $content = str_replace($value, $DATA[$key], $content);
780 $SEND_UID = $DATA[1];
781 $CATEGORY = GET_CATEGORY($DATA[9]);
782 $TARGET_URL = $DATA[7];
787 $points = TRANSLATE_COMMA($DATA[10]);
791 if (isset($_POST['points'])) {
792 $points = bigintval($_POST['points']);
794 $points = __POINTS_VALUE;
798 case "guest_request_confirm":
805 if (EXT_IS_ACTIVE("nickname")) {
807 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
808 array(bigintval($UID)), __FILE__, __LINE__);
809 list($surname, $family, $sex, $email, $nick) = SQL_FETCHROW($result);
810 SQL_FREERESULT($result);
813 $result = SQL_QUERY_ESC("SELECT surname, family, sex, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
814 array(bigintval($UID)), __FILE__, __LINE__);
815 list($surname, $family, $sex, $email) = SQL_FETCHROW($result);
816 SQL_FREERESULT($result);
820 // Neutral sex and email address is default
825 // Translate M to male or F to female
826 $salut = TRANSLATE_SEX($sex);
828 // Store email for some functions in global data array
829 $DATA['email'] = $email;
832 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
834 // Check for admin/guest/member templates
835 if (strpos($template, "admin_") > -1) {
836 // Admin template found
837 $file = $BASE."admin/".$template.".tpl";
838 } elseif (strpos($template, "guest_") > -1) {
839 // Guest template found
840 $file = $BASE."guest/".$template.".tpl";
841 } elseif (strpos($template, "member_") > -1) {
842 // Member template found
843 $file = $BASE."member/".$template.".tpl";
845 // Test for extension
846 $test = substr($template, 0, strpos($template, "_"));
847 if (EXT_IS_ACTIVE($test)) {
848 // Set extra path to extension's name
849 $file = $BASE.$test."/".$template.".tpl";
851 // No special filename
852 $file = $BASE.$template.".tpl";
856 // Does the special template exists?
857 if (!FILE_READABLE($file)) {
858 // Reset to default template
859 $file = $BASE.$template.".tpl";
862 // Now does the final template exists?
864 if (FILE_READABLE($file)) {
865 // The local file does exists so we load it. :)
866 $tmpl_file = @implode("", @file($file));
867 $tmpl_file = addslashes($tmpl_file);
870 $tmpl_file = "\$newContent=\"".COMPILE_CODE($tmpl_file)."\";";
873 // Replace HTML conform chars
874 $newContent = html_entity_decode($newContent);
875 } elseif (!empty($template)) {
876 // Template file not found!
877 $newContent = TEMPLATE_404.": ".$template."<br />
879 <PRE>".print_r($newContent, true)."</PRE>
881 <PRE>".print_r($DATA, true)."</PRE>
884 // Debug mode not active? Then remove the HTML tags
885 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
887 // No template name supplied!
888 $newContent = NO_TEMPLATE_SUPPLIED;
891 // Is there some content?
892 if (empty($newContent)) {
894 $newContent = "Compiler error for template {$template}!";
897 // Return compiled content
898 return COMPILE_CODE($newContent);
901 function MAKE_TIME($H, $M, $S, $stamp) {
902 // Extract day, month and year from given timestamp
903 $DAY = date("d", $stamp);
904 $MONTH = date("m", $stamp);
905 $YEAR = date('Y', $stamp);
907 // Create timestamp for wished time which depends on extracted date
908 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
911 function LOAD_URL($URL, $addUrlData=true) {
912 global $CSS, $_CONFIG, $footer;
914 // Check if http(s):// is there
915 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
916 // Make all URLs full-qualified
920 // Compile out URI codes
921 $URL = COMPILE_CODE($URL);
924 $OUTPUT = ob_get_contents();
929 // Add some data to URL if cookies are not accepted
930 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
932 // Probe for bot from search engine
933 if ((eregi("spider", getenv('HTTP_USER_AGENT'))) || (eregi("bot", getenv('HTTP_USER_AGENT'))) || (eregi("spider", getenv('HTTP_USER_AGENT')))) {
934 // Search engine bot detected so let's rewrite many chars for the link
935 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
937 // Output new location link as anchor
938 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
939 } elseif (!headers_sent()) {
940 // Load URL when headers are not sent
943 debug_print_backtrace();
944 die("</pre>URL={$URL}");
946 @header ("Location: ".str_replace("&", "&", $URL));
948 // Output error message
949 include(PATH."inc/header.php");
950 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
951 include(PATH."inc/footer.php");
956 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
957 global $SEC_CHARS, $URL_CHARS;
960 // Select smaller set of chars to replace when we e.g. want to compile URLs
961 if (!$full) $ARRAY = $URL_CHARS;
965 // BEFORE 0.2.1 : Language and data constants
966 // WITH 0.2.1+ : Only language constants
967 $code = str_replace('{--', '".', str_replace('--}', '."', $code));
969 // BEFORE 0.2.1 : Not used
970 // WITH 0.2.1+ : Data constants
971 $code = str_replace('{!', '".', str_replace("!}", '."', $code));
974 // Compile QUOT and other non-HTML codes
975 foreach ($ARRAY['to'] as $k => $to) {
976 // Do the reversed thing as in inc/libs/security_functions.php
977 $code = str_replace($to, $ARRAY['from'][$k], $code);
980 // But shall I keep simple quotes for later use?
981 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
983 // Find $content[bla][blub] entries
984 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
986 // Are some matches found?
987 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
988 // Replace all matches
989 $matchesFound = array();
990 foreach ($matches[0] as $key => $match) {
991 // Avoid replacing matches multiple times
992 if (!isset($matchesFound[$match])) {
994 $code = str_replace($match, "\".".$match.".\"", $code);
995 $matchesFound[$match] = 1;
998 // Take all string elements
999 if (("".bigintval($matches[4][$key])."" != $matches[4][$key]) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1000 // Replace it in the code
1001 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1002 $code = str_replace($match, $newMatch, $code);
1003 $matchesFound[$key."_".$matches[4][$key]] = 1;
1008 // Return compiled code
1012 /************************************************************************
1014 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1015 * $a_sort sortiert: *
1017 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1018 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1019 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1020 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1021 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1023 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1024 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1025 * Sie, dass es doch nicht so schwer ist! :-) *
1027 ************************************************************************/
1028 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1031 while ($primary_key < count($a_sort))
1033 foreach ($dummy[$a_sort[$primary_key]] as $key => $value)
1035 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2)
1040 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1041 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1043 elseif ($key != $key2)
1045 // Sort numbers (E.g.: 9 < 10)
1046 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1047 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1051 // We have found two different values, so let's sort whole array
1052 foreach ($dummy as $sort_key => $sort_val)
1054 $t = $dummy[$sort_key][$key];
1055 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1056 $dummy[$sort_key][$key2] = $t;
1067 // Write back sorted array
1071 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1073 global $MONTH_DESCR; $OUT = "";
1076 // This is a yes/no selection only!
1077 if ($id > 0) $prefix .= "[".$id."]";
1078 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1082 // Begin with regular selection box here
1083 if (!empty($prefix)) $prefix .= "_";
1085 if ($id > 0) $type2 .= "[".$id."]";
1086 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1091 for ($idx = 1; $idx < 32; $idx++)
1093 $OUT .= " <OPTION value=\"".$idx."\"";
1094 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1095 $OUT .= ">".$idx."</OPTION>\n";
1099 case "month": // Month
1100 foreach ($MONTH_DESCR as $month => $descr)
1102 $OUT .= " <OPTION value=\"".$month."\"";
1103 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1104 $OUT .= ">".$descr."</OPTION>\n";
1108 case "year": // Year
1110 $YEAR = date('Y', time());
1112 // Check if the default value is larger than minimum and bigger than actual year
1113 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1115 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1117 $OUT .= " <OPTION value=\"".$idx."\"";
1118 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1119 $OUT .= ">".$idx."</OPTION>\n";
1122 elseif ($DEFAULT == -1)
1124 // Current year minus 1
1125 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1127 $OUT .= " <OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1132 // Get current year and subtract 16 (for erotic content)
1133 $OUT .= " <OPTION value=\"1929\"><1930</OPTION>\n";
1134 $YEAR = date('Y', time()) - 16;
1135 for ($idx = 1930; $idx <= $YEAR; $idx++)
1137 $OUT .= " <OPTION value=\"".$idx."\"";
1138 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1139 $OUT .= ">".$idx."</OPTION>\n";
1146 for ($idx = 0; $idx < 60; $idx+=5)
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 for ($idx = 0; $idx < 24; $idx++)
1158 if (strlen($idx) == 1) $idx = "0".$idx;
1159 $OUT .= " <OPTION value=\"".$idx."\"";
1160 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1161 $OUT .= ">".$idx."</OPTION>\n";
1166 $OUT .= " <OPTION value=\"Y\"";
1167 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1168 $OUT .= ">".YES."</OPTION>
1169 <OPTION value=\"N\"";
1170 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1171 $OUT .= ">".NO."</OPTION>\n";
1174 $OUT .= " </SELECT>\n";
1178 function TRANSLATE_YESNO($yn)
1182 case 'Y': $yn = YES; break;
1183 case 'N': $yn = NO; break;
1184 default : $yn = "??? (".$yn.")"; break;
1189 // Deprecated : $length
1192 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1195 // Fix missing _MAX constant
1196 if (!defined('_MAX')) define('_MAX', 15235);
1198 // Build server string
1199 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1202 $keys = SITE_KEY.":".DATE_KEY;
1203 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1204 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1205 $keys .= ":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']);
1206 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1208 // Build string from misc data
1209 $data = $code.":".$uid.":".$DATA;
1211 // Add more additional data
1212 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1213 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1214 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1215 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1216 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1217 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1219 // Calculate number for generating the code
1220 $a = $code + _ADD - 1;
1222 if (isset($_CONFIG['master_hash'])) {
1223 // Generate hash with master salt 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, $_CONFIG['master_salt']);
1226 // Create number from hash
1227 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1229 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1230 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1232 // Create number from hash
1233 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1236 // At least 10 numbers shall be secure enought!
1237 $len = $_CONFIG['code_length'];
1238 if ($len == 0) $len = 10;
1240 // Cut off requested counts of number
1241 $return = substr(str_replace('.', "", $rcode), 0, $len);
1243 // Done building code
1246 // Does only allow numbers
1247 function bigintval($num, $castValue = true) {
1248 // Filter all numbers out
1249 $ret = preg_replace("/[^0123456789]/", "", $num);
1254 // Insert the code in $img_code into jpeg or PNG image
1255 function GENERATE_IMAGE($img_code, $header=true) {
1258 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1259 // Stop execution of function here because of over-sized code length
1261 } elseif (!$header) {
1262 // Return in an HTML code code
1263 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1267 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1268 if (FILE_READABLE($img)) {
1269 // Switch image type
1270 switch ($_CONFIG['img_type'])
1273 // Okay, load image and hide all errors
1274 $image = @imagecreatefromjpeg($img);
1278 // Okay, load image and hide all errors
1279 $image = @imagecreatefrompng($img);
1283 // Exit function here
1287 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1288 $text_color = imagecolorallocate($image, 0, 0, 0);
1290 // Insert code into image
1291 imagestring($image, 5, 14, 2, $img_code, $text_color);
1293 // Return to browser
1294 header ("Content-Type: image/".$_CONFIG['img_type']);
1296 // Output image with matching image factory
1297 switch ($_CONFIG['img_type']) {
1298 case "jpg": imagejpeg($image); break;
1299 case "png": imagepng($image); break;
1302 // Remove image from memory
1303 imagedestroy($image);
1305 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false)
1307 // Calculate 15-seconds timestamp (15-seconds-steps shall be fine ;) )
1308 $timestamp = round($timestamp / 15) * 15;
1309 // Do we have a leap year?
1311 $TEST = date('Y', time()) / 4;
1312 $M1 = date("m", time());
1313 $M2 = date("m", (time() + $timestamp));
1314 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1315 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = ONE_DAY;
1316 // First of all years...
1317 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1319 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1321 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / ONE_DAY) / 7) - ($M / 12 * (365 + $SWITCH / ONE_DAY) / 7)));
1323 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / ONE_DAY) - ($M / 12 * (365 + $SWITCH / ONE_DAY)) - $W * 7));
1325 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / ONE_DAY) * 24 - ($M / 12 * (365 + $SWITCH / ONE_DAY) * 24) - $W * 7 * 24 - $D * 24));
1327 $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));
1328 // And at last seconds...
1329 $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));
1331 // Now we convert them in seconds...
1335 // Just put all data in an array for later use
1349 $OUT = "<DIV align=\"".$align."\">\n";
1350 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1352 if (ereg('Y', $display) || (empty($display)))
1354 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1356 if (ereg("M", $display) || (empty($display)))
1358 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1360 if (ereg("W", $display) || (empty($display)))
1362 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1364 if (ereg("D", $display) || (empty($display)))
1366 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1368 if (ereg("h", $display) || (empty($display)))
1370 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1372 if (ereg("m", $display) || (empty($display)))
1374 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1376 if (ereg("s", $display) || (empty($display)))
1378 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1382 if (ereg('Y', $display) || (empty($display)))
1384 // Generate year selection
1385 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1386 for ($idx = 0; $idx <= 10; $idx++)
1388 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1389 if ($idx == $Y) $OUT .= " selected default";
1390 $OUT .= ">".$idx."</OPTION>\n";
1392 $OUT .= " </SELECT></TD>\n";
1396 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1398 if (ereg("M", $display) || (empty($display)))
1400 // Generate month selection
1401 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1402 for ($idx = 0; $idx <= 11; $idx++)
1404 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1405 if ($idx == $M) $OUT .= " selected default";
1406 $OUT .= ">".$idx."</OPTION>\n";
1408 $OUT .= " </SELECT></TD>\n";
1412 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1414 if (ereg("W", $display) || (empty($display)))
1416 // Generate week selection
1417 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1418 for ($idx = 0; $idx <= 4; $idx++)
1420 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1421 if ($idx == $W) $OUT .= " selected default";
1422 $OUT .= ">".$idx."</OPTION>\n";
1424 $OUT .= " </SELECT></TD>\n";
1428 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1430 if (ereg("D", $display) || (empty($display)))
1432 // Generate day selection
1433 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1434 for ($idx = 0; $idx <= 31; $idx++)
1436 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1437 if ($idx == $D) $OUT .= " selected default";
1438 $OUT .= ">".$idx."</OPTION>\n";
1440 $OUT .= " </SELECT></TD>\n";
1444 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1446 if (ereg("h", $display) || (empty($display)))
1448 // Generate hour selection
1449 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1450 for ($idx = 0; $idx <= 23; $idx++)
1452 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1453 if ($idx == $h) $OUT .= " selected default";
1454 $OUT .= ">".$idx."</OPTION>\n";
1456 $OUT .= " </SELECT></TD>\n";
1460 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1462 if (ereg("m", $display) || (empty($display)))
1464 // Generate minute selection
1465 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1466 for ($idx = 0; $idx <= 59; $idx++)
1468 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1469 if ($idx == $m) $OUT .= " selected default";
1470 $OUT .= ">".$idx."</OPTION>\n";
1472 $OUT .= " </SELECT></TD>\n";
1476 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1478 if (ereg("s", $display) || (empty($display)))
1480 // Generate second selection
1481 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1482 for ($idx = 0; $idx <= 45; $idx+=15)
1484 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1485 if ($idx == $s) $OUT .= " selected default";
1486 $OUT .= ">".$idx."</OPTION>\n";
1488 $OUT .= " </SELECT></TD>\n";
1492 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1495 $OUT .= "</TABLE>\n";
1497 // Return generated HTML code
1502 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1504 // Do we have a leap year?
1506 $TEST = date('Y', time()) / 4;
1507 $M1 = date("m", time());
1508 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1509 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = ONE_DAY;
1510 // First add years...
1511 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1513 $ret += $POST[$prefix."_mo"] * 2628000;
1515 $ret += $POST[$prefix."_we"] * 604800;
1517 $ret += $POST[$prefix."_da"] * 86400;
1519 $ret += $POST[$prefix."_ho"] * 3600;
1521 $ret += $POST[$prefix."_mi"] * 60;
1522 // And at last seconds...
1523 $ret += $POST[$prefix."_se"];
1524 // Return calculated value
1527 // Sends out mail to all administrators
1528 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1529 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1530 // Trim template name
1531 $template = trim($template);
1533 // Load email template
1534 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1536 if (GET_EXT_VERSION("admins") < "0.4.0") {
1537 // Older version detected!
1538 return SEND_ADMIN_EMAILS($subj, $msg);
1541 // Check which admin shall receive this mail
1542 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1543 array($template), __FILE__, __LINE__);
1544 if (SQL_NUMROWS($result) == 0) {
1545 // Create new entry (to all admins)
1546 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1547 array($template), __FILE__, __LINE__);
1549 // Load admin IDs...
1551 while(list($aid) = SQL_FETCHROW($result)) {
1556 SQL_FREERESULT($result);
1558 // "implode" IDs and query string
1559 $aid = implode(",", $aids);
1561 // Add line to userlog
1562 USERLOG_ADD_LINE($subj, $msg, $UID);
1564 } elseif ($aid == "0") {
1565 // Select all email adresses
1566 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1568 // If Admin-ID is not "to-all" select
1569 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1573 // Load email addresses and send away
1574 while (list($email) = SQL_FETCHROW($result)) {
1575 SEND_EMAIL($email, $subj, $msg);
1579 SQL_FREERESULT($result);
1582 function CREATE_FANCY_TIME($stamp) {
1583 // Get data array with years/months/weeks/days/...
1584 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1586 foreach($data as $k => $v) {
1588 // Value is greater than 0 "eval" data to return string
1589 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1595 // Remove first "comma,null" string
1596 $ret = substr($ret, 2);
1600 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1601 $SEP = ""; $TOP = "";
1604 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1608 for ($page = 1; $page <= $PAGES; $page++) {
1609 // Is the page currently selected or shall we generate a link to it?
1610 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1611 // Is currently selected, so only highlight it
1612 $NAV .= "<STRONG>-";
1614 // Open anchor tag and add base URL
1615 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1617 // Add userid when we shall show all mails from a single member
1618 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1620 // Close open anchor tag
1624 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1625 // Is currently selected, so only highlight it
1626 $NAV .= "-</STRONG>";
1632 // Add seperator if we have not yet reached total pages
1633 if ($page < $PAGES) $NAV .= " | ";
1636 // Define constants only once
1637 if (!defined('__NAV_OUTPUT')) {
1638 define('__NAV_OUTPUT' , $NAV);
1639 define('__NAV_COLSPAN', $colspan);
1640 define('__NAV_TOP' , $TOP);
1641 define('__NAV_SEP' , $SEP);
1644 // Load navigation template
1645 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1648 // Return generated HTML-Code
1656 // Extract host from script name
1657 function EXTRACT_HOST (&$script) {
1658 // Use default SERVER_URL by default... ;) So?
1661 // Is this URL valid?
1662 if (substr($script, 0, 7) == "http://") {
1663 // Use the hostname from script URL as new hostname
1664 $url = substr($script, 7);
1665 $extract = explode("/", $url);
1667 // Done extracting the URL :)
1670 // Extract host name
1671 $host = str_replace("http://", "", $url);
1672 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1674 // Generate relative URL
1675 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1676 if (substr(strtolower($script), 0, 7) == "http://") {
1677 // But only if http:// is in front!
1678 $script = substr($script, (strlen($url) + 7));
1679 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1681 $script = substr($script, (strlen($url) + 8));
1684 //* DEBUG */ print("SCRIPT=".$script."<br />\n");
1685 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1691 // Send a GET request
1692 function GET_URL ($script) {
1693 // Compile the script name
1694 $script = COMPILE_CODE($script);
1696 // Extract host name from script
1697 $host = EXTRACT_HOST($script);
1699 // Generate GET request header
1700 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1701 $request .= "Host: " . $host . "\r\n";
1702 $request .= "Referer: " . URL . "/admin.php\r\n";
1703 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1704 $request .= "Content-Type: text/plain\r\n";
1705 $request .= "Cache-Control: no-cache\r\n";
1706 $request .= "Connection: Close\r\n\r\n";
1708 // Send the raw request
1709 $response = SEND_RAW_REQUEST($host, $request);
1711 // Return the result to the caller function
1715 // Send a POST request
1716 function POST_URL ($script, $postData) {
1717 // Is postData an array?
1718 if (!is_array($postData)) {
1720 return array("", "", "");
1723 // Compile the script name
1724 $script = COMPILE_CODE($script);
1726 // Extract host name from script
1727 $host = EXTRACT_HOST($script);
1729 // Construct request
1730 $data = http_build_query($postData, '', '&');
1732 // Generate POST request header
1733 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1734 $request .= "Host: " . $host . "\r\n";
1735 $request .= "Referer: " . URL . "/admin.php\r\n";
1736 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1737 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1738 $request .= "Content-length: " . strlen($data) . "\r\n";
1739 $request .= "Cache-Control: no-cache\r\n";
1740 $request .= "Connection: Close\r\n\r\n";
1743 // Send the raw request
1744 $response = SEND_RAW_REQUEST($host, $request);
1746 // Return the result to the caller function
1750 // Sends a raw request to another host
1751 function SEND_RAW_REQUEST ($host, $request) {
1755 $response = array("", "", "");
1757 // Default is not to use proxy
1760 // Are proxy settins set?
1761 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1767 //* DEBUG */ die("SCRIPT=".$script."<br />\n");
1769 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1771 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1775 if (!is_resource($fp)) {
1782 // Generate CONNECT request header
1783 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1784 $proxyTunnel .= "Host: ".$host."\r\n";
1786 // Use login data to proxy? (username at least!)
1787 if (!empty($_CONFIG['proxy_username'])) {
1789 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1790 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1793 // Add last new-line
1794 $proxyTunnel .= "\r\n";
1795 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1798 fputs($fp, $proxyTunnel);
1802 // No response received
1806 // Read the first line
1807 $resp = trim(fgets($fp, 10240));
1808 $respArray = explode(" ", $resp);
1809 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1810 // Invalid response!
1816 fputs($fp, $request);
1820 $response[] = trim(fgets($fp, 1024));
1826 // Skip first empty lines
1828 foreach ($resp as $idx => $line) {
1830 $line = trim($line);
1832 // Is this line empty?
1835 array_shift($response);
1837 // Abort on first non-empty line
1842 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1844 // Proxy agent found?
1845 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1846 // Proxy header detected, so remove two lines
1847 array_shift($response);
1848 array_shift($response);
1851 // Was the request successfull?
1852 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1853 // Not found / access forbidden
1854 $response = array("", "", "");
1860 // Taken from www.php.net eregi() user comments
1861 function VALIDATE_EMAIL($email) {
1863 $email = COMPILE_CODE($email);
1865 // Check first part of email address
1866 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1869 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1872 $regex = "^".$first."@".$domain."$";
1874 // Return check result
1875 return eregi($regex, $email);
1877 // Function taken from user comments on www.php.net / function eregi()
1878 function VALIDATE_URL ($URL, $compile=true) {
1879 // Trim URL a little
1880 $URL = trim(urldecode($URL));
1881 //* DEBUG: */ echo $URL."<br />";
1883 // Compile some chars out...
1884 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1885 //* DEBUG: */ echo $URL."<br />";
1887 // Check for the extension filter
1888 if (EXT_IS_ACTIVE("filter")) {
1889 // Use the extension's filter set
1890 return FILTER_VALIDATE_URL($URL, false);
1893 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1894 // https:// in front of the URLs
1895 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1898 function MEMBER_ACTION_LINKS($uid, $status="") {
1899 // Define all main targets
1900 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1902 // Begin of navigation links
1903 $eval = "\$OUT = \"[ ";
1905 foreach ($TARGETS as $tar) {
1906 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1907 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1908 if (($tar == "lock_user") && ($status == "LOCKED")) {
1909 // Locked accounts shall be unlocked
1910 $eval .= "UNLOCK_USER";
1912 // All other status is fine
1913 $eval .= strtoupper($tar);
1915 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1916 if (($tar == "lock_user") && ($status == "LOCKED")) {
1917 // Locked accounts shall be unlocked
1918 $eval .= "UNLOCK_USER";
1920 // All other status is fine
1921 $eval .= strtoupper($tar);
1923 $eval .= ".\"</A></SPAN> | ";
1926 // Finish navigation link
1927 $eval = substr($eval, 0, -7)."]\";";
1933 // Function for backward-compatiblity
1934 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1935 // Load it from the register extension
1936 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1938 // Generate an email link
1939 function CREATE_EMAIL_LINK($email, $table="admins") {
1940 // Default email link (INSECURE! Spammer can read this by harvester programs)
1941 $EMAIL = "mailto:".$email;
1943 // Check for several extensions
1944 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1945 // Create email link for contacting admin in guest area
1946 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1947 } elseif ((EXT_IS_ACTIVE("user", true)) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1948 // Create email link for contacting a member within admin area (or later in other areas, too?)
1949 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1950 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1951 // Create email link to contact sponsor within admin area (or like the link above?)
1952 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1955 // Shall I close the link when there is no admin?
1956 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1958 // Return email link
1961 // Generate a hash for extra-security for all passwords
1962 function generateHash ($plainText, $salt = "") {
1963 global $_CONFIG, $_SERVER;
1965 // Is the required extension "sql_patches" there and a salt is not given?
1966 if (((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) && (empty($salt))) {
1967 // Extension sql_patches is missing/outdated so we return the plain text
1971 // Do we miss an arry element here?
1972 if (!isset($_CONFIG['file_hash'])) {
1974 print(__FUNCTION__.":<pre>");
1975 debug_print_backtrace();
1979 // When the salt is empty build a new one, else use the first x configured characters as the salt
1981 // Build server string
1982 $server = $_SERVER['PHP_SELF'].":".getenv('HTTP_USER_AGENT').":".getenv('SERVER_SOFTWARE').":".getenv('REMOTE_ADDR').":".":".filemtime(PATH."inc/databases.php");
1985 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", $_CONFIG['patch_ctime']).":".$_CONFIG['master_salt'];
1988 $data = $plainText.":".uniqid(rand(), true).":".time();
1990 // Calculate number for generating the code
1991 $a = time() + _ADD - 1;
1993 // Generate SHA1 sum from modula of number and the prime number
1994 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1995 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br>";
1996 $sha1 = scrambleString($sha1);
1997 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br>";
1998 //* DEBUG: */ $sha1b = descrambleString($sha1);
1999 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br>";
2001 // Generate the password salt string
2002 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
2003 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2006 $salt = substr($salt, 0, $_CONFIG['salt_length']);
2007 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2011 return $salt.sha1($salt.$plainText);
2014 function scrambleString($str) {
2020 // Final check, in case of failture it will return unscrambled string
2021 if (strlen($str) > 40) {
2022 // The string is to long
2024 } elseif (strlen($str) == 40) {
2026 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2028 // Generate new numbers
2029 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2032 // Scramble string here
2033 //* DEBUG: */ echo "***Original=".$str."***<br />";
2034 for ($idx = 0; $idx < strlen($str); $idx++) {
2035 // Get char on scrambled position
2036 $char = substr($str, $scrambleNums[$idx], 1);
2038 // Add it to final output string
2039 $scrambled .= $char;
2042 // Return scrambled string
2043 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2047 function descrambleString($str) {
2049 // Scramble only 40 chars long strings
2050 if (strlen($str) != 40) return $str;
2052 // Load numbers from config
2053 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2056 if (count($scrambleNums) != 40) return $str;
2058 // Begin descrambling
2059 $orig = str_repeat(" ", 40);
2060 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2061 for ($idx = 0; $idx < 40; $idx++) {
2062 $char = substr($str, $idx, 1);
2063 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2066 // Return scrambled string
2067 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2071 function genScrambleString($len) {
2072 // Prepare randomizer and array for the numbers
2073 mt_srand((double) microtime() * 1000000);
2074 $scrambleNumbers = array();
2076 // First we need to setup randomized numbers from 0 to 31
2077 for ($idx = 0; $idx < $len; $idx++) {
2079 $rand = mt_rand(0, ($len -1));
2081 // Check for it by creating more numbers
2082 while (array_key_exists($rand, $scrambleNumbers)) {
2083 $rand = mt_rand(0, ($len -1));
2087 $scrambleNumbers[$rand] = $rand;
2090 // So let's create the string for storing it in database
2091 $scrambleString = implode(":", $scrambleNumbers);
2092 return $scrambleString;
2094 // Append data like session ID referral ID to the given URL which would
2095 // normally be stored in cookies
2096 function ADD_URL_DATA($URL) {
2100 // Determine URL binder
2102 if (strpos($URL, "?") !== false) $BIND = "&";
2104 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2105 // Cookies are not accepted
2106 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2107 // Cookie found in URL
2108 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2109 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2110 // Not found! So let's set default here
2111 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2114 // Is there already added data? Then change the binder
2115 if (!empty($ADD)) $BIND = "&";
2118 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2119 // Add session from URL
2120 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2122 // Add current session
2123 $ADD .= $BIND."PHPSESSID=".session_id();
2127 // Add all together and return it
2130 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2131 function generatePassString($passHash) {
2134 // Return vanilla password hash
2137 // Is a secret key and master salt already initialized?
2138 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2139 // Only calculate when the secret key is generated
2140 $newHash = ""; $start = 9;
2141 for ($idx = 0; $idx < 10; $idx++) {
2142 $part1 = hexdec(substr($passHash, $start, 4));
2143 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2144 $mod = dechex($idx);
2145 if ($part1 > $part2) {
2146 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2147 } elseif ($part2 > $part1) {
2148 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2150 $mod = substr(round($mod), 0, 4);
2151 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2152 //* DEBUG: */ echo "*".$start."=".$mod."*<br>";
2157 //* DEBUG: */ print($passHash."<br>".$newHash." (".strlen($newHash).")");
2158 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2159 //* DEBUG: */ print($ret."<br />\n");
2162 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2163 $ret = md5($passHash);
2164 //* DEBUG: */ echo "++".$ret."++<br />\n";
2171 // Fix "deleted" cookies
2172 function FIX_DELETED_COOKIES ($cookies) {
2173 // Is this an array with entries?
2174 if ((is_array($cookies)) && (count($cookies) > 0)) {
2175 // Then check all cookies if they are marked as deleted!
2176 foreach ($cookies as $cookieName) {
2177 // Is the cookie set to "deleted"?
2178 if (get_session($cookieName) == "deleted") {
2179 set_session($cookieName, "");
2185 // Output error messages in a fasioned way and die...
2186 function mxchange_die ($msg) {
2189 // Load the message template
2190 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2193 include(PATH."inc/footer.php");
2199 // Display parsing time and number of SQL queries in footer
2200 function DISPLAY_PARSING_TIME_FOOTER() {
2201 global $startTime, $_CONFIG;
2202 $endTime = microtime(true);
2204 // Is the timer started?
2205 if (!isset($GLOBALS['startTime'])) {
2210 // "Explode" both times
2211 $start = explode(" ", $GLOBALS['startTime']);
2212 $end = explode(" ", $endTime);
2213 $runTime = $end[0] - $start[0];
2214 if ($runTime < 0) $runTime = 0;
2215 $runTime = TRANSLATE_COMMA($runTime);
2219 'runtime' => $runTime,
2220 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2221 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2224 // Load the template
2225 LOAD_TEMPLATE("show_timings", false, $content);
2228 // Unset/set session variables
2229 function set_session ($var, $value) {
2232 // Abort in CSS mode here
2233 if ($CSS == 1) return true;
2235 // Trim value and session variable
2236 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2238 // Is the session variable set?
2239 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2240 // Remove the session
2241 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2242 unset($_SESSION[$var]);
2243 return session_unregister($var);
2244 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2246 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2247 $_SESSION[$var] = $value;
2248 return session_register($var);
2249 } elseif (!empty($value)) {
2251 $_SESSION[$var] = $value;
2253 // Something bad happens!
2254 return false; // Hope this doesn't make so much trouble???
2257 // Return always true if the session variable is already set.
2258 // Keept me busy for a longer while...
2259 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2263 // Check wether a boolean constant is set
2264 // Taken from user comments in PHP documentation for function constant()
2265 function isBooleanConstantAndTrue($constname) { // : Boolean
2267 if (defined($constname)) $res = (constant($constname) === true);
2271 // Check wether a session variable is set
2272 function isSessionVariableSet($var) {
2273 return (isset($_SESSION[$var]));
2275 // Returns wether the value of the session variable or NULL if not set
2276 function get_session($var) {
2277 // Default is not found! ;-)
2280 // Is the variable there?
2281 if (isSessionVariableSet($var)) {
2282 // Then get it secured!
2283 $value = SQL_ESCAPE($_SESSION[$var]);
2289 // Send notification to admin
2290 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content="", $uid="0") {
2291 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2293 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2295 // Send outdated way
2296 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2297 SEND_ADMIN_EMAILS($subject, $msg);
2300 // Destroy user session
2301 function destroy_user_session () {
2302 // Remove all user data from session
2303 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2305 // Merges an array together but only if both are arrays
2306 function merge_array ($array1, $array2) {
2307 // Are both an array?
2308 if ((is_array($array1)) && (is_array($array2))) {
2309 // Merge all together
2310 return array_merge($array1, $array2);
2311 } elseif (is_array($array1)) {
2312 // Return left array
2316 // Something wired happened here...
2317 print(__FUNCTION__.":<pre>");
2318 debug_print_backtrace();
2321 // Debug message logger
2322 function DEBUG_LOG ($message) {
2323 // Is debug mode enabled?
2324 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
2325 // Log this message away
2326 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2327 fwrite($fp, date("d.m.Y|H:i:s", time())."|{$message}\n");
2331 // Reads a directory with PHP files in and gets only files back
2332 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2336 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2339 while ($baseFile = readdir($dirPointer)) {
2340 // Load file only if extension is active
2342 $file = $baseDir.$baseFile;
2344 // Is this a valid reset file?
2345 if ((is_file($file)) && (is_readable($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2346 // Remove both for extension name
2347 $extName = substr($baseFile, strlen($prefix), -4);
2350 $extId = GET_EXT_ID($extName);
2352 // Is the extension valid and active?
2353 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2354 // Then add this file
2361 closedir($dirPointer);
2363 // Return array with include files
2366 // Load more reset scripts
2367 function RESET_ADD_INCLUDES () {
2368 global $_CONFIG, $INC_POOL;
2370 // Is the reset set or old sql_patches?
2371 if ((!isBooleanConstantAndTrue('__DAILY_RESET')) || (GET_EXT_VERSION("sql_patches") < "0.4.5")) {
2376 // Get more daily reset scripts
2377 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_"));
2379 // Create current week mark
2380 $currWeek = date("W", time());
2383 if ($_CONFIG['last_week'] != $currWeek) {
2384 // Include weekly reset scripts
2385 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2388 UPDATE_CONFIG("last_week", $currWeek);
2391 // Create current month mark
2392 $currMonth = date("m", time());
2395 if ($_CONFIG['last_month'] != $currMonth) {
2396 // Include monthly reset scripts
2397 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2400 UPDATE_CONFIG("last_month", $currMonth);
2403 // Handle extra values
2404 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2405 // Default is the value itself
2408 // Do we have a special filter function?
2409 if (!empty($filterFunction)) {
2410 // Does the filter function exist?
2411 if (function_exists($filterFunction)) {
2412 // Do we have extra parameters here?
2413 if (!empty($extraValue)) {
2414 // Put both parameters in one new array by default
2415 $args = array($value, $extraValue);
2417 // If we have an array simply use it and pre-extend it with our value
2418 if (is_array($extraValue)) {
2419 // Make the new args array
2420 $args = array_merge(array($value), $extraValue);
2423 // Call the multi-parameter call-back
2424 $ret = call_user_func_array($filterFunction, $args);
2426 // One parameter call
2427 $ret = call_user_func($filterFunction, $value);
2435 // Check if given FQFN is a readable file
2436 function FILE_READABLE($fqfn) {
2438 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2440 // Converts timestamp selections into a timestamp
2441 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2442 // Init test variable
2445 // Get last three chars
2446 $TEST = substr($id, -3);
2448 // Improved way of checking! :-)
2449 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2450 // Found a multi-selection for timings?
2451 $TEST = substr($id, 0, -3);
2452 if ((isset($POST[$TEST."_ye"])) && (isset($POST[$TEST."_mo"])) && (isset($POST[$TEST."_we"])) && (isset($POST[$TEST."_da"])) && (isset($POST[$TEST."_ho"])) && (isset($POST[$TEST."_mi"])) && (isset($POST[$TEST."_se"])) && ($TEST != $TEST2)) {
2453 // Generate timestamp
2454 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2455 $DATA[] = "$TEST='".$POST[$TEST]."'";
2457 // Remove data from array
2458 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2459 unset($POST[$TEST."_".$rem]);
2463 unset($id); $skip = true; $TEST2 = $TEST;
2466 // Process this entry
2467 $skip = false; $TEST2 = "";
2470 // Reverts the german decimal comma into Computer decimal dot
2471 function REVERT_COMMA ($str) {
2472 $float = (float)str_replace(",", ".", $str);
2476 //////////////////////////////////////////////////
2478 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2480 //////////////////////////////////////////////////
2482 if (!function_exists('html_entity_decode')) {
2483 // Taken from documentation on www.php.net
2484 function html_entity_decode($string) {
2485 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2486 $trans_tbl = array_flip($trans_tbl);
2487 return strtr($string, $trans_tbl);