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 (!defined('__SECURITY')) {
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 // Extension "rewrite" installed?
137 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
138 $OUTPUT = REWRITE_LINKS($OUTPUT);
141 // Compile and run finished rendered HTML code
142 while (strpos($OUTPUT, '{!') > 0) {
143 // Prepare the content and eval() it...
145 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
148 // Was that eval okay?
149 if (empty($newContent)) {
150 // Something went wrong!
151 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
153 $OUTPUT = $newContent;
156 // Output code here, DO NOT REMOVE! ;-)
158 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
159 // Rewrite links when rewrite extension is active
160 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
161 $OUTPUT = REWRITE_LINKS($OUTPUT);
164 // Compile and run finished rendered HTML code
165 while (strpos($OUTPUT, '{!') > 0) {
166 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
170 // Output code here, DO NOT REMOVE! ;-)
175 // Output the raw HTML code
176 function OUTPUT_RAW ($HTML) {
177 // Output stripped HTML code to avoid broken JavaScript code, etc.
178 echo stripslashes(stripslashes($HTML));
180 // Flush the output if only _OB_CACHING is not "on"
181 if (_OB_CACHING != "on") {
187 // Add a fatal error message to the queue array
188 function ADD_FATAL ($message, $extra="") {
191 // Regular text message to add to $FATAL
194 // $message is text with a mask plus extras to insert into the text
195 $FATAL[] = sprintf($message, $extra);
199 // Load a template file and return it's content (only it's name; do not use ' or ")
200 function LOAD_TEMPLATE($template, $return=false, $content=array()) {
201 // Add more variables which you want to use in your template files
202 global $DATA, $_CONFIG, $username;
204 // Make all template names lowercase
205 $template = strtolower($template);
207 // Count the template load
208 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
209 $_CONFIG['num_templates']++;
213 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
215 // @DEPRECATED Try to remove this if() block
216 if ($template == "member_support_form") {
217 // Support request of a member
218 $result = SQL_QUERY_ESC("SELECT gender, surname, family, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
219 array($GLOBALS['userid']), __FILE__, __LINE__);
221 // @TODO Merge this data into $content
222 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
225 $gender = TRANSLATE_GENDER($gender);
227 // Insert data if content is an array
228 if (is_array($content)) {
229 // Please switch to $content[bla] in all your templates! Direct
230 // variables are deprecated as of 09/13/2008.
231 $content['gender'] = $gender;
232 $content['surname'] = $surname;
233 $content['family'] = $family;
234 $content['email'] = $email;
238 SQL_FREERESULT($result);
241 // Generate date/time string
242 $date_time = MAKE_DATETIME(time(), "1");
245 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
248 // Check for admin/guest/member templates
249 if (strpos($template, "admin_") > -1) {
250 // Admin template found
252 } elseif (strpos($template, "guest_") > -1) {
253 // Guest template found
255 } elseif (strpos($template, "member_") > -1) {
256 // Member template found
258 } elseif (strpos($template, "install_") > -1) {
259 // Installation template found
261 } elseif (strpos($template, "ext_") > -1) {
262 // Extension template found
264 } elseif (strpos($template, "la_") > -1) {
265 // "Logical-area" template found
268 // Test for extension
269 $test = substr($template, 0, strpos($template, "_"));
270 if (EXT_IS_ACTIVE($test)) {
271 // Set extra path to extension's name
276 ////////////////////////
277 // Generate file name //
278 ////////////////////////
279 $file = $BASE.$MODE.$template.".tpl";
281 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
282 // Select what depended header/footer template file for admin/guest/member area
283 $file2 = sprintf("%s%s%s_%s.tpl",
287 SQL_ESCAPE($GLOBALS['what'])
291 if (FILE_READABLE($file2)) $file = $file2;
293 // Remove variable from memory
297 // Does the special template exists?
298 if (!FILE_READABLE($file)) {
299 // Reset to default template
300 $file = $BASE.$template.".tpl";
303 // Now does the final template exists?
304 if (FILE_READABLE($file)) {
305 // The local file does exists so we load it. :)
306 $tmpl_file = implode("", file($file));
308 // Replace ' to our own chars to preventing them being quoted
309 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
311 // Do we have to compile the code?
313 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
315 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
318 // Simply return loaded code
322 // Add surrounding HTML comments to help finding bugs faster
323 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
324 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
325 // Only admins shall see this warning or when installation mode is active
326 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
327 (".basename($file).")<br />
330 <pre>".print_r($content, true)."</pre>
332 <pre>".print_r($DATA, true)."</pre>
336 // Do we have some content to output or return?
338 // Not empty so let's put it out! ;)
340 // Return the HTML code
346 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
347 // Warning, empty output!
348 return "E:".$template."<br />\n";
352 // Send mail out to an email address
353 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
354 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
356 // Compile subject line (for POINTS constant etc.)
357 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
361 if ((!eregi("@", $TO)) && ($TO > 0)) {
362 // Value detected, is the message extension installed?
363 if (EXT_IS_ACTIVE("msg")) {
364 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
367 // Load email address
368 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
369 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
371 // Does the user exist?
372 if (SQL_NUMROWS($result_email)) {
373 // Load email address
374 list($TO) = SQL_FETCHROW($result_email);
381 SQL_FREERESULT($result_email);
383 } elseif ("$TO" == "0") {
387 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
389 // Check for PHPMailer or debug-mode
390 if (!CHECK_PHPMAILER_USAGE()) {
391 // Not in PHPMailer-Mode
393 // Load email header template
394 $FROM = LOAD_EMAIL_TEMPLATE("header");
397 $FROM .= LOAD_EMAIL_TEMPLATE("header");
399 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
401 // Load email header template
402 $FROM = LOAD_EMAIL_TEMPLATE("header");
405 $FROM .= LOAD_EMAIL_TEMPLATE("header");
410 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
413 // Fix HTML parameter (default is no!)
414 if (empty($HTML)) $HTML = "N";
415 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
416 // In debug mode we want to display the mail instead of sending it away so we can debug this part
418 ".htmlentities(trim($FROM))."
420 Subject : ".$SUBJECT."
425 if (defined('DEBUG_MAIL')) DEBUG_LOG(__FUNCTION__.":to={$TO},subject={$SUBJECT},msg={$MSG}");
426 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
427 // Send mail as HTML away
428 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
429 } elseif (!empty($TO)) {
431 SEND_RAW_EMAIL($TO, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
432 } elseif ($HTML == "N") {
434 SEND_RAW_EMAIL(WEBMASTER, COMPILE_CODE($SUBJECT), COMPILE_CODE($MSG), $FROM);
438 // Check if legacy or PHPMailer command
440 function CHECK_PHPMAILER_USAGE() {
441 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
445 * Send out a raw email with PHPMailer class or legacy mail() command
447 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
448 // Shall we use PHPMailer class or legacy mode?
449 if (CHECK_PHPMAILER_USAGE()) {
450 // Use PHPMailer class with SMTP enabled
451 require_once(PATH."inc/phpmailer/class.phpmailer.php");
452 require_once(PATH."inc/phpmailer/class.smtp.php");
455 $mail = new PHPMailer();
456 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
459 $mail->SMTPAuth = true;
460 $mail->Host = SMTP_HOSTNAME;
462 $mail->Username = SMTP_USER;
463 $mail->Password = SMTP_PASSWORD;
465 $mail->From = WEBMASTER;
469 $mail->FromName = MAIN_TITLE;
470 $mail->Subject = $subject;
471 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
473 $mail->AltBody = "Your mail program required HTML support to read this mail!";
474 $mail->WordWrap = 70;
477 $mail->Body = html_entity_decode($msg);
479 $mail->AddAddress($to, "");
480 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
481 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
482 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
485 // Use legacy mail() command
486 @mail($to, $subject, html_entity_decode($msg), $from);
491 // Generate a password in a specified length or use default password length
492 function GEN_PASS($LEN = 0) {
494 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
496 // Initialize array with all allowed chars
497 $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,-,+,_,/");
499 // Initialize randomizer
500 mt_srand((double) microtime() * 1000000);
502 // Start creating password
504 for ($i = 0; $i < $LEN; $i++) {
505 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
508 // When the size is below 40 we can also add additional security by scrambling it
509 if (strlen($PASS) <= 40) {
510 // Also scramble the password
511 $PASS = scrambleString($PASS);
514 // Return the password
518 function MAKE_DATETIME ($time, $mode="0")
522 return NEVER_HAPPENED;
524 // Filter out numbers
525 $time = bigintval($time);
528 switch (GET_LANGUAGE())
530 case "de": // German date / time format
532 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
533 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
534 case "2": $ret = date("d.m.Y|H:i", $time); break;
535 case "3": $ret = date("d.m.Y", $time); break;
539 default: // Default is the US date / time format!
541 case "0": $ret = date("r", $time); break;
542 case "1": $ret = date("Y-m-d - g:i A", $time); break;
543 case "2": $ret = date("y-m-d|H:i", $time); break;
544 case "3": $ret = date("y-m-d", $time); break;
550 // Translates the american decimal dot into a german comma
551 function TRANSLATE_COMMA ($dotted, $cut=true) {
554 // Default is 3 you can change this in admin area "Misc -> Misc Options"
555 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
556 $maxComma = $_CONFIG['max_comma'];
560 // Test for commata if in cut-mode
561 $com = explode(".", $dotted);
562 if (count($com) > 1) {
563 // Commata found, so only zeros?
564 if ($com[1] == str_repeat("0", strlen($com[1]))) {
565 // Only zeros, so display only one
569 // Don't display commatas even if there are none... ;-)
575 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
578 switch (GET_LANGUAGE()) {
580 $dotted = number_format($dotted, $maxComma, ",", ".");
584 $dotted = number_format($dotted, $maxComma, ".", ",");
588 // Return translated value
593 function DEREFERER ($URL) {
594 // Don't de-refer our own links!
595 if (substr($URL, 0, strlen(URL)) != URL) {
596 // De-refer this link
597 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
605 function TRANSLATE_GENDER ($gender) {
608 case "M": $ret = GENDER_M; break;
609 case "F": $ret = GENDER_F; break;
610 case "C": $ret = GENDER_C; break;
611 default : $ret = $gender; break;
616 function FRAMETESTER($URL) {
617 // Prepare frametester URL
618 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
620 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
622 return $frametesterUrl;
625 function SELECTION_COUNT($array) {
627 if (is_array($array)) {
628 foreach ($array as $key => $sel) {
629 if (!empty($sel)) $ret++;
635 function IMG_CODE ($code, $type, $DATA, $uid) {
636 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
639 function TRANSLATE_STATUS($status) {
643 $ret = ACCOUNT_UNCONFIRMED;
647 $ret = ACCOUNT_CONFIRMED;
651 $ret = ACCOUNT_LOCKED;
656 $ret = ACCOUNT_DELETED;
660 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
666 function GET_LANGUAGE() {
667 if (!empty($_GET['mx_lang'])) {
668 // Accept only first 2 chars
669 $lang = substr($_GET['mx_lang'], 0, 2);
675 // Set default return value to default language from config
678 // Check GET variable and cookie
680 // Check if main language file does exist
681 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
682 // Okay found, so let's update cookies
685 } elseif (!isSessionVariableSet('mx_lang')) {
686 // Return stored value from cookie
687 $ret = get_session('mx_lang');
689 // Fixes a warning before the session has the mx_lang constant
690 if (empty($ret)) $ret = DEFAULT_LANG;
695 function SET_LANGUAGE($lang) {
698 // Accept only first 2 chars!
699 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
702 set_session("mx_lang", $lang);
705 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
706 global $DATA, $_CONFIG, $REPLACER;
708 // Make sure all template names are lowercase!
709 $template = strtolower($template);
711 // Default "nickname" if extension is not installed
714 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
715 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
717 // Prepare IP number and User Agent
718 $REMOTE_ADDR = GET_REMOTE_ADDR();
719 $HTTP_USER_AGENT = GET_USER_AGENT();
724 // Is the admin logged in?
727 $ADMIN = GET_ADMIN_EMAIL(get_session('admin_login'));
730 // Neutral email address is default
733 // Expiration in a nice output format
734 if ($_CONFIG['auto_purge'] == 0) {
735 // Will never expire!
736 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
737 } elseif (function_exists('CREATE_FANCY_TIME')) {
738 // Create nice date string
739 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
742 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
745 // Is content an array?
746 if (is_array($content)) {
747 // Add expiration to array, $EXPIRATION is now deprecated!
748 $content['expiration'] = $EXPIRATION;
752 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template}<br />\n";
754 if (EXT_IS_ACTIVE("nickname")) {
755 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
757 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
758 array(bigintval($UID)), __FILE__, __LINE__);
760 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
762 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
763 array(bigintval($UID)), __FILE__, __LINE__);
766 // Is content an array?
767 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content[]=".gettype($content)."<br />\n";
768 if (is_array($content)) {
769 // Fetch and migrate data
770 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
771 $content = array_merge($content, SQL_FETCHARRAY($result));
772 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
776 SQL_FREERESULT($result);
779 // Translate M to male or F to female if present
780 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
782 // Overwrite email from data if present
783 if (isset($content['email'])) $email = $content['email'];
785 // Store email for some functions in global data array
786 $DATA['email'] = $email;
789 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
791 // Check for admin/guest/member templates
792 if (strpos($template, "admin_") > -1) {
793 // Admin template found
794 $file = $BASE."admin/".$template.".tpl";
795 } elseif (strpos($template, "guest_") > -1) {
796 // Guest template found
797 $file = $BASE."guest/".$template.".tpl";
798 } elseif (strpos($template, "member_") > -1) {
799 // Member template found
800 $file = $BASE."member/".$template.".tpl";
802 // Test for extension
803 $test = substr($template, 0, strpos($template, "_"));
804 if (EXT_IS_ACTIVE($test)) {
805 // Set extra path to extension's name
806 $file = $BASE.$test."/".$template.".tpl";
808 // No special filename
809 $file = $BASE.$template.".tpl";
813 // Does the special template exists?
814 if (!FILE_READABLE($file)) {
815 // Reset to default template
816 $file = $BASE.$template.".tpl";
819 // Now does the final template exists?
821 if (FILE_READABLE($file)) {
822 // The local file does exists so we load it. :)
823 $tmpl_file = implode("", file($file));
824 $tmpl_file = addslashes($tmpl_file);
827 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
829 } elseif (!empty($template)) {
830 // Template file not found!
831 $newContent = TEMPLATE_404.": ".$template."<br />
833 <pre>".print_r($content, true)."</pre>
835 <pre>".print_r($DATA, true)."</pre>
838 // Debug mode not active? Then remove the HTML tags
839 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
841 // No template name supplied!
842 $newContent = NO_TEMPLATE_SUPPLIED;
845 // Is there some content?
846 if (empty($newContent)) {
848 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
849 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
852 // Return compiled content
853 return COMPILE_CODE($newContent);
856 function MAKE_TIME($H, $M, $S, $stamp) {
857 // Extract day, month and year from given timestamp
858 $DAY = date("d", $stamp);
859 $MONTH = date("m", $stamp);
860 $YEAR = date('Y', $stamp);
862 // Create timestamp for wished time which depends on extracted date
863 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
866 function LOAD_URL($URL, $addUrlData=true) {
867 global $CSS, $_CONFIG, $footer;
869 // Check if http(s):// is there
870 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
871 // Make all URLs full-qualified
875 // Compile out URI codes
876 $URL = COMPILE_CODE($URL);
879 $OUTPUT = ob_get_contents();
881 // Clear it only if there is content
882 if (!empty($OUTPUT)) {
886 // Add some data to URL if cookies are not accepted
887 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
889 // Probe for bot from search engine
890 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT())) || (eregi("spider", GET_USER_AGENT()))) {
891 // Search engine bot detected so let's rewrite many chars for the link
892 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
894 // Output new location link as anchor
895 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
896 } elseif (!headers_sent()) {
897 // Load URL when headers are not sent
900 debug_print_backtrace();
901 die("</pre>URL={$URL}");
903 @header ("Location: ".str_replace("&", "&", $URL));
905 // Output error message
906 include(PATH."inc/header.php");
907 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
908 include(PATH."inc/footer.php");
913 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
914 global $SEC_CHARS, $URL_CHARS;
915 // Is the code a string?
916 if (!is_string($code)) {
917 // Silently return it
923 // Select smaller set of chars to replace when we e.g. want to compile URLs
924 if (!$full) $ARRAY = $URL_CHARS;
928 // BEFORE 0.2.1 : Language and data constants
929 // WITH 0.2.1+ : Only language constants
930 $code = str_replace('{--','".', str_replace('--}','."', $code));
932 // BEFORE 0.2.1 : Not used
933 // WITH 0.2.1+ : Data constants
934 $code = str_replace('{!','".', str_replace("!}", '."', $code));
937 // Compile QUOT and other non-HTML codes
938 foreach ($ARRAY['to'] as $k => $to) {
939 // Do the reversed thing as in inc/libs/security_functions.php
940 $code = str_replace($to, $ARRAY['from'][$k], $code);
943 // But shall I keep simple quotes for later use?
944 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
946 // Find $content[bla][blub] entries
947 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
949 // Are some matches found?
950 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
951 // Replace all matches
952 $matchesFound = array();
953 foreach ($matches[0] as $key => $match) {
954 // Fuzzy look has failed by default
957 // Fuzzy look on match if already found
958 foreach ($matchesFound as $found => $set) {
960 $test = substr($found, 0, strlen($match));
962 // Does this entry exist?
963 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
964 if ($test == $match) {
966 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
973 if ($fuzzyFound) continue;
975 // Take all string elements
976 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
977 // Replace it in the code
978 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
979 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
980 $code = str_replace($match, "\".".$newMatch.".\"", $code);
981 $matchesFound[$key."_".$matches[4][$key]] = 1;
982 $matchesFound[$match] = 1;
983 } elseif (!isset($matchesFound[$match])) {
985 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
986 $code = str_replace($match, "\".".$match.".\"", $code);
987 $matchesFound[$match] = 1;
992 // Return compiled code
996 /************************************************************************
998 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
999 * $a_sort sortiert: *
1001 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1002 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1003 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1004 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1005 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1007 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1008 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1009 * Sie, dass es doch nicht so schwer ist! :-) *
1011 ************************************************************************/
1012 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1015 while ($primary_key < count($a_sort)) {
1016 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1017 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1020 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1021 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1022 } elseif ($key != $key2) {
1023 // Sort numbers (E.g.: 9 < 10)
1024 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1025 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1029 // We have found two different values, so let's sort whole array
1030 foreach ($dummy as $sort_key => $sort_val) {
1031 $t = $dummy[$sort_key][$key];
1032 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1033 $dummy[$sort_key][$key2] = $t;
1044 // Write back sorted array
1048 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1050 global $MONTH_DESCR; $OUT = "";
1053 // This is a yes/no selection only!
1054 if ($id > 0) $prefix .= "[".$id."]";
1055 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1059 // Begin with regular selection box here
1060 if (!empty($prefix)) $prefix .= "_";
1062 if ($id > 0) $type2 .= "[".$id."]";
1063 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1068 for ($idx = 1; $idx < 32; $idx++)
1070 $OUT .= "<OPTION value=\"".$idx."\"";
1071 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1072 $OUT .= ">".$idx."</OPTION>\n";
1076 case "month": // Month
1077 foreach ($MONTH_DESCR as $month => $descr)
1079 $OUT .= "<OPTION value=\"".$month."\"";
1080 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1081 $OUT .= ">".$descr."</OPTION>\n";
1085 case "year": // Year
1087 $YEAR = date('Y', time());
1089 // Check if the default value is larger than minimum and bigger than actual year
1090 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1092 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1094 $OUT .= "<OPTION value=\"".$idx."\"";
1095 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1096 $OUT .= ">".$idx."</OPTION>\n";
1099 elseif ($DEFAULT == -1)
1101 // Current year minus 1
1102 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1104 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1109 // Get current year and subtract 16 (for erotic content)
1110 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1111 $YEAR = date('Y', time()) - 16;
1112 for ($idx = 1930; $idx <= $YEAR; $idx++)
1114 $OUT .= "<OPTION value=\"".$idx."\"";
1115 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1116 $OUT .= ">".$idx."</OPTION>\n";
1123 for ($idx = 0; $idx < 60; $idx+=5) {
1124 if (strlen($idx) == 1) $idx = "0".$idx;
1125 $OUT .= "<OPTION value=\"".$idx."\"";
1126 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1127 $OUT .= ">".$idx."</OPTION>\n";
1132 for ($idx = 0; $idx < 24; $idx++) {
1133 if (strlen($idx) == 1) $idx = "0".$idx;
1134 $OUT .= "<OPTION value=\"".$idx."\"";
1135 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1136 $OUT .= ">".$idx."</OPTION>\n";
1141 $OUT .= "<OPTION value=\"Y\"";
1142 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1143 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1144 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1145 $OUT .= ">".NO."</OPTION>\n";
1148 $OUT .= " </SELECT>\n";
1152 function TRANSLATE_YESNO($yn)
1156 case 'Y': $yn = YES; break;
1157 case 'N': $yn = NO; break;
1158 default : $yn = "??? (".$yn.")"; break;
1163 // Deprecated : $length
1166 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1169 // Fix missing _MAX constant
1170 if (!defined('_MAX')) define('_MAX', 15235);
1172 // Build server string
1173 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1176 $keys = SITE_KEY.":".DATE_KEY;
1177 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1178 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1179 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1180 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1182 // Build string from misc data
1183 $data = $code.":".$uid.":".$DATA;
1185 // Add more additional data
1186 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1187 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1188 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1189 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1190 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1191 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1193 // Calculate number for generating the code
1194 $a = $code + _ADD - 1;
1196 if (isset($_CONFIG['master_hash'])) {
1197 // Generate hash with master salt from modula of number with the prime number and other data
1198 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1200 // Create number from hash
1201 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1203 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1204 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1206 // Create number from hash
1207 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1210 // At least 10 numbers shall be secure enought!
1211 $len = $_CONFIG['code_length'];
1212 if ($len == 0) $len = $length;
1213 if ($len == 0) $len = 10;
1215 // Cut off requested counts of number
1216 $return = substr(str_replace('.', "", $rcode), 0, $len);
1218 // Done building code
1221 // Does only allow numbers
1222 function bigintval($num, $castValue = true) {
1223 // Filter all numbers out
1224 $ret = preg_replace("/[^0123456789]/", "", $num);
1227 if ($castValue) $ret = (double)$ret;
1229 // Has the whole value changed?
1230 if ("".$ret."" != "".$num."") {
1232 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1238 // Insert the code in $img_code into jpeg or PNG image
1239 function GENERATE_IMAGE($img_code, $header=true) {
1242 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1243 // Stop execution of function here because of over-sized code length
1245 } elseif (!$header) {
1246 // Return in an HTML code code
1247 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1251 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1252 if (FILE_READABLE($img)) {
1253 // Switch image type
1254 switch ($_CONFIG['img_type'])
1257 // Okay, load image and hide all errors
1258 $image = @imagecreatefromjpeg($img);
1262 // Okay, load image and hide all errors
1263 $image = @imagecreatefrompng($img);
1267 // Exit function here
1271 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1272 $text_color = imagecolorallocate($image, 0, 0, 0);
1274 // Insert code into image
1275 imagestring($image, 5, 14, 2, $img_code, $text_color);
1277 // Return to browser
1278 header ("Content-Type: image/".$_CONFIG['img_type']);
1280 // Output image with matching image factory
1281 switch ($_CONFIG['img_type']) {
1282 case "jpg": imagejpeg($image); break;
1283 case "png": imagepng($image); break;
1286 // Remove image from memory
1287 imagedestroy($image);
1289 // Create selection box or array of splitted timestamp
1290 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1293 // Calculate 2-seconds timestamp
1294 $stamp = round($timestamp / 2) * 2;
1296 // Do we have a leap year?
1298 $TEST = date('Y', time()) / 4;
1299 $M1 = date("m", time());
1300 $M2 = date("m", (time() + $stamp));
1302 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1303 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = $_CONFIG['one_day'];
1305 // First of all years...
1306 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1308 $M = abs(floor($stamp / 2628000 - $Y * 12));
1310 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / $_CONFIG['one_day']) / 7) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day']) / 7)));
1312 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / $_CONFIG['one_day']) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day'])) - $W * 7));
1314 $h = abs(floor($stamp / 3600 - $Y * (365 + $SWITCH / $_CONFIG['one_day']) * 24 - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day']) * 24) - $W * 7 * 24 - $D * 24));
1316 $m = abs(floor($stamp / 60 - $Y * (365 + $SWITCH / $_CONFIG['one_day']) * 24 * 60 - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day']) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1317 // And at last seconds...
1318 $s = abs(floor($stamp - $Y * (365 + $SWITCH / $_CONFIG['one_day']) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day']) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1320 // Is seconds zero and time is < 60 seconds?
1321 if (($s == 0) && ($stamp < 60)) {
1323 $s = round($timestamp);
1327 // Now we convert them in seconds...
1329 if ($return_array) {
1330 // Just put all data in an array for later use
1342 $OUT = "<DIV align=\"".$align."\">\n";
1343 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1346 if (ereg('Y', $display) || (empty($display))) {
1347 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1350 if (ereg("M", $display) || (empty($display))) {
1351 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1354 if (ereg("W", $display) || (empty($display))) {
1355 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1358 if (ereg("D", $display) || (empty($display))) {
1359 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1362 if (ereg("h", $display) || (empty($display))) {
1363 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1366 if (ereg("m", $display) || (empty($display))) {
1367 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1370 if (ereg("s", $display) || (empty($display))) {
1371 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1377 if (ereg('Y', $display) || (empty($display))) {
1378 // Generate year selection
1379 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1380 for ($idx = 0; $idx <= 10; $idx++) {
1381 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1382 if ($idx == $Y) $OUT .= " selected default";
1383 $OUT .= ">".$idx."</OPTION>\n";
1385 $OUT .= " </SELECT></TD>\n";
1387 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1390 if (ereg("M", $display) || (empty($display))) {
1391 // Generate month selection
1392 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1393 for ($idx = 0; $idx <= 11; $idx++)
1395 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1396 if ($idx == $M) $OUT .= " selected default";
1397 $OUT .= ">".$idx."</OPTION>\n";
1399 $OUT .= " </SELECT></TD>\n";
1401 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1404 if (ereg("W", $display) || (empty($display))) {
1405 // Generate week selection
1406 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1407 for ($idx = 0; $idx <= 4; $idx++) {
1408 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1409 if ($idx == $W) $OUT .= " selected default";
1410 $OUT .= ">".$idx."</OPTION>\n";
1412 $OUT .= " </SELECT></TD>\n";
1414 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1417 if (ereg("D", $display) || (empty($display))) {
1418 // Generate day selection
1419 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1420 for ($idx = 0; $idx <= 31; $idx++) {
1421 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1422 if ($idx == $D) $OUT .= " selected default";
1423 $OUT .= ">".$idx."</OPTION>\n";
1425 $OUT .= " </SELECT></TD>\n";
1427 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1430 if (ereg("h", $display) || (empty($display))) {
1431 // Generate hour selection
1432 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1433 for ($idx = 0; $idx <= 23; $idx++) {
1434 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1435 if ($idx == $h) $OUT .= " selected default";
1436 $OUT .= ">".$idx."</OPTION>\n";
1438 $OUT .= " </SELECT></TD>\n";
1440 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1443 if (ereg("m", $display) || (empty($display))) {
1444 // Generate minute selection
1445 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1446 for ($idx = 0; $idx <= 59; $idx++) {
1447 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1448 if ($idx == $m) $OUT .= " selected default";
1449 $OUT .= ">".$idx."</OPTION>\n";
1451 $OUT .= " </SELECT></TD>\n";
1453 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1456 if (ereg("s", $display) || (empty($display))) {
1457 // Generate second selection
1458 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1459 for ($idx = 0; $idx <= 45; $idx += 15) {
1460 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1461 if ($idx == $s) $OUT .= " selected default";
1462 $OUT .= ">".$idx."</OPTION>\n";
1464 $OUT .= " </SELECT></TD>\n";
1466 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1469 $OUT .= "</TABLE>\n";
1471 // Return generated HTML code
1476 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1480 // Do we have a leap year?
1482 $TEST = date('Y', time()) / 4;
1483 $M1 = date("m", time());
1484 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1485 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = $_CONFIG['one_day'];
1486 // First add years...
1487 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1489 $ret += $POST[$prefix."_mo"] * 2628000;
1491 $ret += $POST[$prefix."_we"] * 604800;
1493 $ret += $POST[$prefix."_da"] * 86400;
1495 $ret += $POST[$prefix."_ho"] * 3600;
1497 $ret += $POST[$prefix."_mi"] * 60;
1498 // And at last seconds...
1499 $ret += $POST[$prefix."_se"];
1500 // Return calculated value
1503 // Sends out mail to all administrators
1504 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1505 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1506 // Trim template name
1507 $template = trim($template);
1509 // Load email template
1510 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1512 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1513 // Older version detected!
1514 return SEND_ADMIN_EMAILS($subj, $msg);
1517 // Check which admin shall receive this mail
1518 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1519 array($template), __FILE__, __LINE__);
1520 if (SQL_NUMROWS($result) == 0) {
1521 // Create new entry (to all admins)
1522 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1523 array($template), __FILE__, __LINE__);
1525 // Load admin IDs...
1527 while(list($aid) = SQL_FETCHROW($result)) {
1532 SQL_FREERESULT($result);
1534 // "implode" IDs and query string
1535 $aid = implode(",", $aids);
1537 // Add line to userlog
1538 USERLOG_ADD_LINE($subj, $msg, $UID);
1540 } elseif ($aid == "0") {
1541 // Select all email adresses
1542 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1544 // If Admin-ID is not "to-all" select
1545 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1549 // Load email addresses and send away
1550 while (list($email) = SQL_FETCHROW($result)) {
1551 SEND_EMAIL($email, $subj, $msg);
1555 SQL_FREERESULT($result);
1558 function CREATE_FANCY_TIME($stamp) {
1559 // Get data array with years/months/weeks/days/...
1560 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1562 foreach($data as $k => $v) {
1564 // Value is greater than 0 "eval" data to return string
1565 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1571 // Do we have something there?
1572 if (strlen($ret) > 0) {
1573 // Remove leading commata and space
1574 $ret = substr($ret, 2);
1577 $ret = "0 "._SECONDS;
1580 // Return fancy time string
1584 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1585 $SEP = ""; $TOP = "";
1588 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1592 for ($page = 1; $page <= $PAGES; $page++) {
1593 // Is the page currently selected or shall we generate a link to it?
1594 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1595 // Is currently selected, so only highlight it
1596 $NAV .= "<STRONG>-";
1598 // Open anchor tag and add base URL
1599 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1601 // Add userid when we shall show all mails from a single member
1602 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1604 // Close open anchor tag
1608 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1609 // Is currently selected, so only highlight it
1610 $NAV .= "-</STRONG>";
1616 // Add seperator if we have not yet reached total pages
1617 if ($page < $PAGES) $NAV .= " | ";
1620 // Define constants only once
1621 if (!defined('__NAV_OUTPUT')) {
1622 define('__NAV_OUTPUT' , $NAV);
1623 define('__NAV_COLSPAN', $colspan);
1624 define('__NAV_TOP' , $TOP);
1625 define('__NAV_SEP' , $SEP);
1628 // Load navigation template
1629 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1632 // Return generated HTML-Code
1640 // Extract host from script name
1641 function EXTRACT_HOST (&$script) {
1642 // Use default SERVER_URL by default... ;) So?
1645 // Is this URL valid?
1646 if (substr($script, 0, 7) == "http://") {
1647 // Use the hostname from script URL as new hostname
1648 $url = substr($script, 7);
1649 $extract = explode("/", $url);
1651 // Done extracting the URL :)
1654 // Extract host name
1655 $host = str_replace("http://", "", $url);
1656 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1658 // Generate relative URL
1659 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1660 if (substr(strtolower($script), 0, 7) == "http://") {
1661 // But only if http:// is in front!
1662 $script = substr($script, (strlen($url) + 7));
1663 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1665 $script = substr($script, (strlen($url) + 8));
1668 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1669 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1675 // Send a GET request
1676 function GET_URL ($script) {
1677 // Compile the script name
1678 $script = COMPILE_CODE($script);
1680 // Extract host name from script
1681 $host = EXTRACT_HOST($script);
1683 // Generate GET request header
1684 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1685 $request .= "Host: " . $host . "\r\n";
1686 $request .= "Referer: " . URL . "/admin.php\r\n";
1687 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1688 $request .= "Content-Type: text/plain\r\n";
1689 $request .= "Cache-Control: no-cache\r\n";
1690 $request .= "Connection: Close\r\n\r\n";
1692 // Send the raw request
1693 $response = SEND_RAW_REQUEST($host, $request);
1695 // Return the result to the caller function
1699 // Send a POST request
1700 function POST_URL ($script, $postData) {
1701 // Is postData an array?
1702 if (!is_array($postData)) {
1704 return array("", "", "");
1707 // Compile the script name
1708 $script = COMPILE_CODE($script);
1710 // Extract host name from script
1711 $host = EXTRACT_HOST($script);
1713 // Construct request
1714 $data = http_build_query($postData, '','&');
1716 // Generate POST request header
1717 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1718 $request .= "Host: " . $host . "\r\n";
1719 $request .= "Referer: " . URL . "/admin.php\r\n";
1720 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1721 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1722 $request .= "Content-length: " . strlen($data) . "\r\n";
1723 $request .= "Cache-Control: no-cache\r\n";
1724 $request .= "Connection: Close\r\n\r\n";
1727 // Send the raw request
1728 $response = SEND_RAW_REQUEST($host, $request);
1730 // Return the result to the caller function
1734 // Sends a raw request to another host
1735 function SEND_RAW_REQUEST ($host, $request) {
1739 $response = array("", "", "");
1741 // Default is not to use proxy
1744 // Are proxy settins set?
1745 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1751 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1753 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1755 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1759 if (!is_resource($fp)) {
1766 // Generate CONNECT request header
1767 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1768 $proxyTunnel .= "Host: ".$host."\r\n";
1770 // Use login data to proxy? (username at least!)
1771 if (!empty($_CONFIG['proxy_username'])) {
1773 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1774 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1777 // Add last new-line
1778 $proxyTunnel .= "\r\n";
1779 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1782 fputs($fp, $proxyTunnel);
1786 // No response received
1790 // Read the first line
1791 $resp = trim(fgets($fp, 10240));
1792 $respArray = explode(" ", $resp);
1793 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1794 // Invalid response!
1800 fputs($fp, $request);
1804 $response[] = trim(fgets($fp, 1024));
1810 // Skip first empty lines
1812 foreach ($resp as $idx => $line) {
1814 $line = trim($line);
1816 // Is this line empty?
1819 array_shift($response);
1821 // Abort on first non-empty line
1826 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1828 // Proxy agent found?
1829 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1830 // Proxy header detected, so remove two lines
1831 array_shift($response);
1832 array_shift($response);
1835 // Was the request successfull?
1836 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1837 // Not found / access forbidden
1838 $response = array("", "", "");
1844 // Taken from www.php.net eregi() user comments
1845 function VALIDATE_EMAIL($email) {
1847 $email = COMPILE_CODE($email);
1849 // Check first part of email address
1850 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1853 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1856 $regex = "^".$first."@".$domain."$";
1858 // Return check result
1859 return eregi($regex, $email);
1861 // Function taken from user comments on www.php.net / function eregi()
1862 function VALIDATE_URL ($URL, $compile=true) {
1863 // Trim URL a little
1864 $URL = trim(urldecode($URL));
1865 //* DEBUG: */ echo $URL."<br />";
1867 // Compile some chars out...
1868 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1869 //* DEBUG: */ echo $URL."<br />";
1871 // Check for the extension filter
1872 if (EXT_IS_ACTIVE("filter")) {
1873 // Use the extension's filter set
1874 return FILTER_VALIDATE_URL($URL, false);
1877 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1878 // https:// in front of the URLs
1879 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1882 function MEMBER_ACTION_LINKS($uid, $status="") {
1883 // Define all main targets
1884 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1886 // Begin of navigation links
1887 $eval = "\$OUT = \"[ ";
1889 foreach ($TARGETS as $tar) {
1890 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1891 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1892 if (($tar == "lock_user") && ($status == "LOCKED")) {
1893 // Locked accounts shall be unlocked
1894 $eval .= "UNLOCK_USER";
1896 // All other status is fine
1897 $eval .= strtoupper($tar);
1899 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1900 if (($tar == "lock_user") && ($status == "LOCKED")) {
1901 // Locked accounts shall be unlocked
1902 $eval .= "UNLOCK_USER";
1904 // All other status is fine
1905 $eval .= strtoupper($tar);
1907 $eval .= ".\"</A></SPAN> | ";
1910 // Finish navigation link
1911 $eval = substr($eval, 0, -7)."]\";";
1917 // Function for backward-compatiblity
1918 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1919 // Load it from the register extension
1920 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1922 // Generate an email link
1923 function CREATE_EMAIL_LINK($email, $table="admins") {
1924 // Default email link (INSECURE! Spammer can read this by harvester programs)
1925 $EMAIL = "mailto:".$email;
1927 // Check for several extensions
1928 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1929 // Create email link for contacting admin in guest area
1930 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1931 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1932 // Create email link for contacting a member within admin area (or later in other areas, too?)
1933 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1934 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1935 // Create email link to contact sponsor within admin area (or like the link above?)
1936 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1939 // Shall I close the link when there is no admin?
1940 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1942 // Return email link
1945 // Generate a hash for extra-security for all passwords
1946 function generateHash ($plainText, $salt = "") {
1947 global $_CONFIG, $_SERVER;
1949 // Is the required extension "sql_patches" there and a salt is not given?
1950 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
1951 // Extension sql_patches is missing/outdated so we return the plain text
1955 // Do we miss an arry element here?
1956 if (!isset($_CONFIG['file_hash'])) {
1958 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1959 debug_print_backtrace();
1963 // When the salt is empty build a new one, else use the first x configured characters as the salt
1965 // Build server string
1966 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1969 $keys = SITE_KEY.":".DATE_KEY.":".$_CONFIG['secret_key'].":".$_CONFIG['file_hash'].":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime'])).":".$_CONFIG['master_salt'];
1972 $data = $plainText.":".uniqid(rand(), true).":".time();
1974 // Calculate number for generating the code
1975 $a = time() + _ADD - 1;
1977 // Generate SHA1 sum from modula of number and the prime number
1978 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1979 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
1980 $sha1 = scrambleString($sha1);
1981 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
1982 //* DEBUG: */ $sha1b = descrambleString($sha1);
1983 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
1985 // Generate the password salt string
1986 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1987 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1990 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1991 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
1995 return $salt.sha1($salt.$plainText);
1998 function scrambleString($str) {
2004 // Final check, in case of failture it will return unscrambled string
2005 if (strlen($str) > 40) {
2006 // The string is to long
2008 } elseif (strlen($str) == 40) {
2010 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2012 // Generate new numbers
2013 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2016 // Scramble string here
2017 //* DEBUG: */ echo "***Original=".$str."***<br />";
2018 for ($idx = 0; $idx < strlen($str); $idx++) {
2019 // Get char on scrambled position
2020 $char = substr($str, $scrambleNums[$idx], 1);
2022 // Add it to final output string
2023 $scrambled .= $char;
2026 // Return scrambled string
2027 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2031 function descrambleString($str) {
2033 // Scramble only 40 chars long strings
2034 if (strlen($str) != 40) return $str;
2036 // Load numbers from config
2037 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2040 if (count($scrambleNums) != 40) return $str;
2042 // Begin descrambling
2043 $orig = str_repeat(" ", 40);
2044 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2045 for ($idx = 0; $idx < 40; $idx++) {
2046 $char = substr($str, $idx, 1);
2047 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2050 // Return scrambled string
2051 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2055 function genScrambleString($len) {
2056 // Prepare randomizer and array for the numbers
2057 mt_srand((double) microtime() * 1000000);
2058 $scrambleNumbers = array();
2060 // First we need to setup randomized numbers from 0 to 31
2061 for ($idx = 0; $idx < $len; $idx++) {
2063 $rand = mt_rand(0, ($len -1));
2065 // Check for it by creating more numbers
2066 while (array_key_exists($rand, $scrambleNumbers)) {
2067 $rand = mt_rand(0, ($len -1));
2071 $scrambleNumbers[$rand] = $rand;
2074 // So let's create the string for storing it in database
2075 $scrambleString = implode(":", $scrambleNumbers);
2076 return $scrambleString;
2078 // Append data like session ID referral ID to the given URL which would
2079 // normally be stored in cookies
2080 function ADD_URL_DATA($URL) {
2084 // Determine URL binder
2086 if (strpos($URL, "?") !== false) $BIND = "&";
2088 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2089 // Cookies are not accepted
2090 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2091 // Cookie found in URL
2092 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2093 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2094 // Not found! So let's set default here
2095 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2098 // Is there already added data? Then change the binder
2099 if (!empty($ADD)) $BIND = "&";
2102 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2103 // Add session from URL
2104 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2106 // Add current session
2107 $ADD .= $BIND."PHPSESSID=".session_id();
2111 // Add all together and return it
2114 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2115 function generatePassString($passHash) {
2118 // Return vanilla password hash
2121 // Is a secret key and master salt already initialized?
2122 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2123 // Only calculate when the secret key is generated
2124 $newHash = ""; $start = 9;
2125 for ($idx = 0; $idx < 10; $idx++) {
2126 $part1 = hexdec(substr($passHash, $start, 4));
2127 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2128 $mod = dechex($idx);
2129 if ($part1 > $part2) {
2130 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2131 } elseif ($part2 > $part1) {
2132 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2134 $mod = substr(round($mod), 0, 4);
2135 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2136 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2141 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2142 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2143 //* DEBUG: */ print($ret."<br />\n");
2146 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2147 $ret = md5($passHash);
2148 //* DEBUG: */ echo "++".$ret."++<br />\n";
2155 // Fix "deleted" cookies
2156 function FIX_DELETED_COOKIES ($cookies) {
2157 // Is this an array with entries?
2158 if ((is_array($cookies)) && (count($cookies) > 0)) {
2159 // Then check all cookies if they are marked as deleted!
2160 foreach ($cookies as $cookieName) {
2161 // Is the cookie set to "deleted"?
2162 if (get_session($cookieName) == "deleted") {
2163 set_session($cookieName, "");
2169 // Output error messages in a fasioned way and die...
2170 function mxchange_die ($msg) {
2173 // Load the message template
2174 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2177 include(PATH."inc/footer.php");
2183 // Display parsing time and number of SQL queries in footer
2184 function DISPLAY_PARSING_TIME_FOOTER() {
2185 global $startTime, $_CONFIG;
2186 $endTime = microtime(true);
2188 // Is the timer started?
2189 if (!isset($GLOBALS['startTime'])) {
2194 // "Explode" both times
2195 $start = explode(" ", $GLOBALS['startTime']);
2196 $end = explode(" ", $endTime);
2197 $runTime = $end[0] - $start[0];
2198 if ($runTime < 0) $runTime = 0;
2199 $runTime = TRANSLATE_COMMA($runTime);
2203 'runtime' => $runTime,
2204 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2205 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2208 // Load the template
2209 LOAD_TEMPLATE("show_timings", false, $content);
2212 // Unset/set session variables
2213 function set_session ($var, $value) {
2216 // Abort in CSS mode here
2217 if ($CSS == 1) return true;
2219 // Trim value and session variable
2220 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2222 // Is the session variable set?
2223 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2224 // Remove the session
2225 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2226 unset($_SESSION[$var]);
2227 return session_unregister($var);
2228 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2230 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2231 $_SESSION[$var] = $value;
2232 return session_register($var);
2233 } elseif (!empty($value)) {
2235 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2236 $_SESSION[$var] = $value;
2240 // Ignored (but valid)
2241 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2245 // Check wether a boolean constant is set
2246 // Taken from user comments in PHP documentation for function constant()
2247 function isBooleanConstantAndTrue($constName) { // : Boolean
2250 // Failed by default
2254 if (isset($constCache[$constName])) {
2256 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2257 $res = $constCache[$constName];
2260 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2261 if (defined($constName)) $res = (constant($constName) === true);
2264 $constCache[$constName] = $res;
2266 //* DEBUG: */ var_dump($res);
2272 // Check wether a session variable is set
2273 function isSessionVariableSet($var) {
2274 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2275 return (isset($_SESSION[$var]));
2277 // Returns wether the value of the session variable or NULL if not set
2278 function get_session($var) {
2281 // Default is not found! ;-)
2284 // Is the variable there or cached values?
2285 if (isset($cacheArray['session'][$var])) {
2286 // Get cached value (skips a lot SQL_ESCAPE() calles!
2287 $value = $cacheArray['session'][$var];
2288 } elseif (isSessionVariableSet($var)) {
2289 // Then get it secured!
2290 $value = SQL_ESCAPE($_SESSION[$var]);
2293 $cacheArray['session'][$var] = $value;
2299 // Send notification to admin
2300 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2301 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2303 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2305 // Send outdated way
2306 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2307 SEND_ADMIN_EMAILS($subject, $msg);
2310 // Destroy user session
2311 function destroy_user_session () {
2312 // Remove all user data from session
2313 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2315 // Merges an array together but only if both are arrays
2316 function merge_array ($array1, $array2) {
2317 // Are both an array?
2318 if ((is_array($array1)) && (is_array($array2))) {
2319 // Merge all together
2320 return array_merge($array1, $array2);
2321 } elseif (is_array($array1)) {
2322 // Return left array
2326 // Something wired happened here...
2327 print(__FUNCTION__.":<pre>");
2328 debug_print_backtrace();
2331 // Debug message logger
2332 function DEBUG_LOG ($message, $force=false) {
2333 // Is debug mode enabled?
2334 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2335 // Log this message away
2336 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2337 fwrite($fp, date("d.m.Y|H:i:s", time())."|".strip_tags($message)."\n");
2341 // Reads a directory with PHP files in and gets only files back
2342 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2346 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2349 while ($baseFile = readdir($dirPointer)) {
2350 // Load file only if extension is active
2352 $file = $baseDir.$baseFile;
2354 // Is this a valid reset file?
2355 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2356 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2357 // Remove both for extension name
2358 $extName = substr($baseFile, strlen($prefix), -4);
2361 $extId = GET_EXT_ID($extName);
2363 // Is the extension valid and active?
2364 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2365 // Then add this file
2367 } elseif ($extId == 0) {
2368 // Add non-extension files as well
2375 closedir($dirPointer);
2377 // Return array with include files
2380 // Load more reset scripts
2381 function RESET_ADD_INCLUDES () {
2384 // Is the reset set or old sql_patches?
2385 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2390 // Get more daily reset scripts
2391 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2393 // Create current week mark
2394 $currWeek = date("W", time());
2397 if ($_CONFIG['last_week'] != $currWeek) {
2398 // Include weekly reset scripts
2399 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2402 UPDATE_CONFIG("last_week", $currWeek);
2405 // Create current month mark
2406 $currMonth = date("m", time());
2409 if ($_CONFIG['last_month'] != $currMonth) {
2410 // Include monthly reset scripts
2411 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2414 UPDATE_CONFIG("last_month", $currMonth);
2420 // Handle extra values
2421 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2422 // Default is the value itself
2425 // Do we have a special filter function?
2426 if (!empty($filterFunction)) {
2427 // Does the filter function exist?
2428 if (function_exists($filterFunction)) {
2429 // Do we have extra parameters here?
2430 if (!empty($extraValue)) {
2431 // Put both parameters in one new array by default
2432 $args = array($value, $extraValue);
2434 // If we have an array simply use it and pre-extend it with our value
2435 if (is_array($extraValue)) {
2436 // Make the new args array
2437 $args = array_merge(array($value), $extraValue);
2440 // Call the multi-parameter call-back
2441 $ret = call_user_func_array($filterFunction, $args);
2443 // One parameter call
2444 $ret = call_user_func($filterFunction, $value);
2452 // Check if given FQFN is a readable file
2453 function FILE_READABLE($fqfn) {
2455 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2457 // Converts timestamp selections into a timestamp
2458 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2459 // Init test variable
2462 // Get last three chars
2463 $TEST = substr($id, -3);
2465 // Improved way of checking! :-)
2466 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2467 // Found a multi-selection for timings?
2468 $TEST = substr($id, 0, -3);
2469 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)) {
2470 // Generate timestamp
2471 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2472 $DATA[] = "$TEST='".$POST[$TEST]."'";
2474 // Remove data from array
2475 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2476 unset($POST[$TEST."_".$rem]);
2480 unset($id); $skip = true; $TEST2 = $TEST;
2483 // Process this entry
2484 $skip = false; $TEST2 = "";
2487 // Reverts the german decimal comma into Computer decimal dot
2488 function REVERT_COMMA ($str) {
2489 // Default float is not a float... ;-)
2492 // Which language is selected?
2493 switch (GET_LANGUAGE()) {
2494 case "de": // German language
2495 // Remove german thousand dots first
2496 $str = str_replace(".", "", $str);
2498 // Replace german commata with decimal dot and cast it
2499 $float = (float)str_replace(",", ".", $str);
2502 default: // US and so on
2503 // Remove thousand dots first and cast
2504 $float = (float)str_replace(",", "", $str);
2511 // Handle menu-depending failed logins and return the rendered content
2512 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2513 // Default output is empty ;-)
2516 // Is the session data set?
2517 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2518 // Ignore zero values
2519 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2520 // Non-guest has login failtures found, get both data and prepare it for template
2521 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2523 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2524 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2528 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2531 // Reset session data
2532 set_session('mxchange_'.$accessLevel.'_failtures', "");
2533 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2536 // Return rendered content
2540 function REBUILD_CACHE ($cache, $inc="") {
2541 global $cacheInstance, $_CONFIG, $CSS;
2543 // Shall I remove the cache file?
2544 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2546 if ($cacheInstance->cache_file($cache, true)) {
2548 $cacheInstance->cache_destroy();
2551 // Include file given?
2554 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2556 // Is the include there?
2557 if (FILE_READABLE($fqfn)) {
2558 // And rebuild it from scratch
2561 // Include not found!
2562 DEBUG_LOG(__FUNCTION__.":Include {$inc} not found. cache={$cache}");
2567 // Purge admin menu cache
2568 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2569 global $_CONFIG, $cacheInstance;
2571 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2572 if (!EXT_IS_ACTIVE("cache")) {
2573 // Cache extension not active
2575 } elseif (!is_object($cacheInstance)) {
2576 // No cache instance!
2577 DEBUG_LOG(__FUNCTION__.": No cache instance found.");
2579 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2580 // Caching disabled (currently experiemental!)
2584 // Experiemental feature!
2585 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2587 // Translates the "pool type" into human-readable
2588 function TRANSLATE_POOL_TYPE ($type) {
2589 // Default type is unknown
2590 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2592 // Generate constant
2593 $constName = sprintf("POOL_TYPE_%s", $type);
2596 if (defined($constName)) {
2598 $translated = constant($constName);
2601 // Return "translation"
2604 // "Getter" for remote IP number
2605 function GET_REMOTE_ADDR () {
2606 // Get remote ip from environment
2607 $remoteAddr = getenv('REMOTE_ADDR');
2609 // Is removeip installed?
2610 if (EXT_IS_ACTIVE("removeip")) {
2611 // Then anonymize it
2612 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2618 // "Getter" for remote hostname
2619 function GET_REMOTE_HOST () {
2620 // Get remote ip from environment
2621 $remoteHost = getenv('REMOTE_HOST');
2623 // Is removeip installed?
2624 if (EXT_IS_ACTIVE("removeip")) {
2625 // Then anonymize it
2626 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2632 // "Getter" for user agent
2633 function GET_USER_AGENT () {
2634 // Get remote ip from environment
2635 $userAgent = getenv('HTTP_USER_AGENT');
2637 // Is removeip installed?
2638 if (EXT_IS_ACTIVE("removeip")) {
2639 // Then anonymize it
2640 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2646 // "Getter" for referer
2647 function GET_REFERER () {
2648 // Get remote ip from environment
2649 $referer = getenv('HTTP_REFERER');
2651 // Is removeip installed?
2652 if (EXT_IS_ACTIVE("removeip")) {
2653 // Then anonymize it
2654 $referer = GET_ANONYMOUS_REFERER($referer);
2661 //////////////////////////////////////////////////
2663 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2665 //////////////////////////////////////////////////
2667 if (!function_exists('html_entity_decode')) {
2668 // Taken from documentation on www.php.net
2669 function html_entity_decode($string) {
2670 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2671 $trans_tbl = array_flip($trans_tbl);
2672 return strtr($string, $trans_tbl);