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;
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, $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 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
599 function TRANSLATE_GENDER ($gender) {
602 case "M": $ret = GENDER_M; break;
603 case "F": $ret = GENDER_F; break;
604 case "C": $ret = GENDER_C; break;
605 default : $ret = $gender; break;
610 function FRAMETESTER($URL) {
611 // Prepare frametester URL
612 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
614 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
616 return $frametesterUrl;
619 function SELECTION_COUNT($array) {
621 if (is_array($array)) {
622 foreach ($array as $key => $sel) {
623 if (!empty($sel)) $ret++;
629 function IMG_CODE ($code, $type, $DATA, $uid) {
630 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
633 function TRANSLATE_STATUS($status) {
637 $ret = ACCOUNT_UNCONFIRMED;
641 $ret = ACCOUNT_CONFIRMED;
645 $ret = ACCOUNT_LOCKED;
650 $ret = ACCOUNT_DELETED;
654 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
660 function GET_LANGUAGE() {
661 if (!empty($_GET['mx_lang'])) {
662 // Accept only first 2 chars
663 $lang = substr($_GET['mx_lang'], 0, 2);
669 // Set default return value to default language from config
672 // Check GET variable and cookie
674 // Check if main language file does exist
675 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
676 // Okay found, so let's update cookies
679 } elseif (!isSessionVariableSet('mx_lang')) {
680 // Return stored value from cookie
681 $ret = get_session('mx_lang');
683 // Fixes a warning before the session has the mx_lang constant
684 if (empty($ret)) $ret = DEFAULT_LANG;
689 function SET_LANGUAGE($lang) {
692 // Accept only first 2 chars!
693 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
696 set_session("mx_lang", $lang);
699 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
700 global $DATA, $_CONFIG, $REPLACER;
702 // Make sure all template names are lowercase!
703 $template = strtolower($template);
705 // Default "nickname" if extension is not installed
708 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
709 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
711 // Prepare IP number and User Agent
712 $REMOTE_ADDR = GET_REMOTE_ADDR();
713 $HTTP_USER_AGENT = GET_USER_AGENT();
718 // Is the admin logged in?
721 $ADMIN = GET_ADMIN_EMAIL(get_session('admin_login'));
724 // Neutral email address is default
727 // Expiration in a nice output format
728 if ($_CONFIG['auto_purge'] == 0) {
729 // Will never expire!
730 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
731 } elseif (function_exists('CREATE_FANCY_TIME')) {
732 // Create nice date string
733 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
736 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
739 // Is content an array?
740 if (is_array($content)) {
741 // Add expiration to array, $EXPIRATION is now deprecated!
742 $content['expiration'] = $EXPIRATION;
746 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template}<br />\n";
748 if (EXT_IS_ACTIVE("nickname")) {
749 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
751 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
752 array(bigintval($UID)), __FILE__, __LINE__);
754 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
756 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
757 array(bigintval($UID)), __FILE__, __LINE__);
760 // Is content an array?
761 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content[]=".gettype($content)."<br />\n";
762 if (is_array($content)) {
763 // Fetch and migrate data
764 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
765 $content = array_merge($content, SQL_FETCHARRAY($result));
766 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
770 SQL_FREERESULT($result);
773 // Translate M to male or F to female if present
774 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
776 // Overwrite email from data if present
777 if (isset($content['email'])) $email = $content['email'];
779 // Store email for some functions in global data array
780 $DATA['email'] = $email;
783 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
785 // Check for admin/guest/member templates
786 if (strpos($template, "admin_") > -1) {
787 // Admin template found
788 $file = $BASE."admin/".$template.".tpl";
789 } elseif (strpos($template, "guest_") > -1) {
790 // Guest template found
791 $file = $BASE."guest/".$template.".tpl";
792 } elseif (strpos($template, "member_") > -1) {
793 // Member template found
794 $file = $BASE."member/".$template.".tpl";
796 // Test for extension
797 $test = substr($template, 0, strpos($template, "_"));
798 if (EXT_IS_ACTIVE($test)) {
799 // Set extra path to extension's name
800 $file = $BASE.$test."/".$template.".tpl";
802 // No special filename
803 $file = $BASE.$template.".tpl";
807 // Does the special template exists?
808 if (!FILE_READABLE($file)) {
809 // Reset to default template
810 $file = $BASE.$template.".tpl";
813 // Now does the final template exists?
815 if (FILE_READABLE($file)) {
816 // The local file does exists so we load it. :)
817 $tmpl_file = implode("", file($file));
818 $tmpl_file = addslashes($tmpl_file);
821 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
823 } elseif (!empty($template)) {
824 // Template file not found!
825 $newContent = TEMPLATE_404.": ".$template."<br />
827 <pre>".print_r($content, true)."</pre>
829 <pre>".print_r($DATA, true)."</pre>
832 // Debug mode not active? Then remove the HTML tags
833 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
835 // No template name supplied!
836 $newContent = NO_TEMPLATE_SUPPLIED;
839 // Is there some content?
840 if (empty($newContent)) {
842 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
843 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
846 // Return compiled content
847 return COMPILE_CODE($newContent);
850 function MAKE_TIME($H, $M, $S, $stamp) {
851 // Extract day, month and year from given timestamp
852 $DAY = date("d", $stamp);
853 $MONTH = date("m", $stamp);
854 $YEAR = date('Y', $stamp);
856 // Create timestamp for wished time which depends on extracted date
857 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
860 function LOAD_URL($URL, $addUrlData=true) {
861 global $CSS, $_CONFIG, $footer;
863 // Check if http(s):// is there
864 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
865 // Make all URLs full-qualified
869 // Compile out URI codes
870 $URL = COMPILE_CODE($URL);
873 $OUTPUT = ob_get_contents();
875 // Clear it only if there is content
876 if (!empty($OUTPUT)) {
880 // Add some data to URL if cookies are not accepted
881 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
883 // Probe for bot from search engine
884 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT())) || (eregi("spider", GET_USER_AGENT()))) {
885 // Search engine bot detected so let's rewrite many chars for the link
886 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
888 // Output new location link as anchor
889 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
890 } elseif (!headers_sent()) {
891 // Load URL when headers are not sent
894 debug_print_backtrace();
895 die("</pre>URL={$URL}");
897 @header ("Location: ".str_replace("&", "&", $URL));
899 // Output error message
900 include(PATH."inc/header.php");
901 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
902 include(PATH."inc/footer.php");
907 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
908 global $SEC_CHARS, $URL_CHARS;
909 // Is the code a string?
910 if (!is_string($code)) {
911 // Abort here with backtrace
912 DEBUG_LOG(__FUNCTION__.": code is not string!");
914 debug_print_backtrace();
920 // Select smaller set of chars to replace when we e.g. want to compile URLs
921 if (!$full) $ARRAY = $URL_CHARS;
925 // BEFORE 0.2.1 : Language and data constants
926 // WITH 0.2.1+ : Only language constants
927 $code = str_replace('{--','".', str_replace('--}','."', $code));
929 // BEFORE 0.2.1 : Not used
930 // WITH 0.2.1+ : Data constants
931 $code = str_replace('{!','".', str_replace("!}", '."', $code));
934 // Compile QUOT and other non-HTML codes
935 foreach ($ARRAY['to'] as $k => $to) {
936 // Do the reversed thing as in inc/libs/security_functions.php
937 $code = str_replace($to, $ARRAY['from'][$k], $code);
940 // But shall I keep simple quotes for later use?
941 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
943 // Find $content[bla][blub] entries
944 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
946 // Are some matches found?
947 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
948 // Replace all matches
949 $matchesFound = array();
950 foreach ($matches[0] as $key => $match) {
951 // Fuzzy look has failed by default
954 // Fuzzy look on match if already found
955 foreach ($matchesFound as $found => $set) {
957 $test = substr($found, 0, strlen($match));
959 // Does this entry exist?
960 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
961 if ($test == $match) {
963 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
970 if ($fuzzyFound) continue;
972 // Take all string elements
973 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
974 // Replace it in the code
975 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
976 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
977 $code = str_replace($match, "\".".$newMatch.".\"", $code);
978 $matchesFound[$key."_".$matches[4][$key]] = 1;
979 $matchesFound[$match] = 1;
980 } elseif (!isset($matchesFound[$match])) {
982 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
983 $code = str_replace($match, "\".".$match.".\"", $code);
984 $matchesFound[$match] = 1;
989 // Return compiled code
993 /************************************************************************
995 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
996 * $a_sort sortiert: *
998 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
999 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1000 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1001 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1002 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1004 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1005 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1006 * Sie, dass es doch nicht so schwer ist! :-) *
1008 ************************************************************************/
1009 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1012 while ($primary_key < count($a_sort)) {
1013 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1014 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1017 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1018 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1019 } elseif ($key != $key2) {
1020 // Sort numbers (E.g.: 9 < 10)
1021 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1022 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1026 // We have found two different values, so let's sort whole array
1027 foreach ($dummy as $sort_key => $sort_val) {
1028 $t = $dummy[$sort_key][$key];
1029 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1030 $dummy[$sort_key][$key2] = $t;
1041 // Write back sorted array
1045 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1047 global $MONTH_DESCR; $OUT = "";
1050 // This is a yes/no selection only!
1051 if ($id > 0) $prefix .= "[".$id."]";
1052 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1056 // Begin with regular selection box here
1057 if (!empty($prefix)) $prefix .= "_";
1059 if ($id > 0) $type2 .= "[".$id."]";
1060 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1065 for ($idx = 1; $idx < 32; $idx++)
1067 $OUT .= "<OPTION value=\"".$idx."\"";
1068 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1069 $OUT .= ">".$idx."</OPTION>\n";
1073 case "month": // Month
1074 foreach ($MONTH_DESCR as $month => $descr)
1076 $OUT .= "<OPTION value=\"".$month."\"";
1077 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1078 $OUT .= ">".$descr."</OPTION>\n";
1082 case "year": // Year
1084 $YEAR = date('Y', time());
1086 // Check if the default value is larger than minimum and bigger than actual year
1087 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1089 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1091 $OUT .= "<OPTION value=\"".$idx."\"";
1092 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1093 $OUT .= ">".$idx."</OPTION>\n";
1096 elseif ($DEFAULT == -1)
1098 // Current year minus 1
1099 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1101 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1106 // Get current year and subtract 16 (for erotic content)
1107 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1108 $YEAR = date('Y', time()) - 16;
1109 for ($idx = 1930; $idx <= $YEAR; $idx++)
1111 $OUT .= "<OPTION value=\"".$idx."\"";
1112 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1113 $OUT .= ">".$idx."</OPTION>\n";
1120 for ($idx = 0; $idx < 60; $idx+=5) {
1121 if (strlen($idx) == 1) $idx = "0".$idx;
1122 $OUT .= "<OPTION value=\"".$idx."\"";
1123 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1124 $OUT .= ">".$idx."</OPTION>\n";
1129 for ($idx = 0; $idx < 24; $idx++) {
1130 if (strlen($idx) == 1) $idx = "0".$idx;
1131 $OUT .= "<OPTION value=\"".$idx."\"";
1132 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1133 $OUT .= ">".$idx."</OPTION>\n";
1138 $OUT .= "<OPTION value=\"Y\"";
1139 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1140 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1141 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1142 $OUT .= ">".NO."</OPTION>\n";
1145 $OUT .= " </SELECT>\n";
1149 function TRANSLATE_YESNO($yn)
1153 case 'Y': $yn = YES; break;
1154 case 'N': $yn = NO; break;
1155 default : $yn = "??? (".$yn.")"; break;
1160 // Deprecated : $length
1163 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1166 // Fix missing _MAX constant
1167 if (!defined('_MAX')) define('_MAX', 15235);
1169 // Build server string
1170 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1173 $keys = SITE_KEY.":".DATE_KEY;
1174 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1175 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1176 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1177 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1179 // Build string from misc data
1180 $data = $code.":".$uid.":".$DATA;
1182 // Add more additional data
1183 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1184 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1185 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1186 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1187 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1188 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1190 // Calculate number for generating the code
1191 $a = $code + _ADD - 1;
1193 if (isset($_CONFIG['master_hash'])) {
1194 // Generate hash with master salt from modula of number with the prime number and other data
1195 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1197 // Create number from hash
1198 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1200 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1201 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1203 // Create number from hash
1204 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1207 // At least 10 numbers shall be secure enought!
1208 $len = $_CONFIG['code_length'];
1209 if ($len == 0) $len = $length;
1210 if ($len == 0) $len = 10;
1212 // Cut off requested counts of number
1213 $return = substr(str_replace('.', "", $rcode), 0, $len);
1215 // Done building code
1218 // Does only allow numbers
1219 function bigintval($num, $castValue = true) {
1220 // Filter all numbers out
1221 $ret = preg_replace("/[^0123456789]/", "", $num);
1224 if ($castValue) $ret = (double)$ret;
1226 // Has the whole value changed?
1227 if ("".$ret."" != "".$num."") {
1229 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1235 // Insert the code in $img_code into jpeg or PNG image
1236 function GENERATE_IMAGE($img_code, $header=true) {
1239 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1240 // Stop execution of function here because of over-sized code length
1242 } elseif (!$header) {
1243 // Return in an HTML code code
1244 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1248 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1249 if (FILE_READABLE($img)) {
1250 // Switch image type
1251 switch ($_CONFIG['img_type'])
1254 // Okay, load image and hide all errors
1255 $image = @imagecreatefromjpeg($img);
1259 // Okay, load image and hide all errors
1260 $image = @imagecreatefrompng($img);
1264 // Exit function here
1268 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1269 $text_color = imagecolorallocate($image, 0, 0, 0);
1271 // Insert code into image
1272 imagestring($image, 5, 14, 2, $img_code, $text_color);
1274 // Return to browser
1275 header ("Content-Type: image/".$_CONFIG['img_type']);
1277 // Output image with matching image factory
1278 switch ($_CONFIG['img_type']) {
1279 case "jpg": imagejpeg($image); break;
1280 case "png": imagepng($image); break;
1283 // Remove image from memory
1284 imagedestroy($image);
1286 // Create selection box or array of splitted timestamp
1287 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1290 // Calculate 2-seconds timestamp
1291 $stamp = round($timestamp / 2) * 2;
1293 // Do we have a leap year?
1295 $TEST = date('Y', time()) / 4;
1296 $M1 = date("m", time());
1297 $M2 = date("m", (time() + $stamp));
1299 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1300 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = $_CONFIG['one_day'];
1302 // First of all years...
1303 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1305 $M = abs(floor($stamp / 2628000 - $Y * 12));
1307 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / $_CONFIG['one_day']) / 7) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day']) / 7)));
1309 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / $_CONFIG['one_day']) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day'])) - $W * 7));
1311 $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));
1313 $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));
1314 // And at last seconds...
1315 $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));
1317 // Is seconds zero and time is < 60 seconds?
1318 if (($s == 0) && ($stamp < 60)) {
1320 $s = round($timestamp);
1324 // Now we convert them in seconds...
1326 if ($return_array) {
1327 // Just put all data in an array for later use
1339 $OUT = "<DIV align=\"".$align."\">\n";
1340 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1343 if (ereg('Y', $display) || (empty($display))) {
1344 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1347 if (ereg("M", $display) || (empty($display))) {
1348 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1351 if (ereg("W", $display) || (empty($display))) {
1352 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1355 if (ereg("D", $display) || (empty($display))) {
1356 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1359 if (ereg("h", $display) || (empty($display))) {
1360 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1363 if (ereg("m", $display) || (empty($display))) {
1364 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1367 if (ereg("s", $display) || (empty($display))) {
1368 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1374 if (ereg('Y', $display) || (empty($display))) {
1375 // Generate year selection
1376 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1377 for ($idx = 0; $idx <= 10; $idx++) {
1378 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1379 if ($idx == $Y) $OUT .= " selected default";
1380 $OUT .= ">".$idx."</OPTION>\n";
1382 $OUT .= " </SELECT></TD>\n";
1384 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1387 if (ereg("M", $display) || (empty($display))) {
1388 // Generate month selection
1389 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1390 for ($idx = 0; $idx <= 11; $idx++)
1392 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1393 if ($idx == $M) $OUT .= " selected default";
1394 $OUT .= ">".$idx."</OPTION>\n";
1396 $OUT .= " </SELECT></TD>\n";
1398 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1401 if (ereg("W", $display) || (empty($display))) {
1402 // Generate week selection
1403 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1404 for ($idx = 0; $idx <= 4; $idx++) {
1405 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1406 if ($idx == $W) $OUT .= " selected default";
1407 $OUT .= ">".$idx."</OPTION>\n";
1409 $OUT .= " </SELECT></TD>\n";
1411 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1414 if (ereg("D", $display) || (empty($display))) {
1415 // Generate day selection
1416 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1417 for ($idx = 0; $idx <= 31; $idx++) {
1418 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1419 if ($idx == $D) $OUT .= " selected default";
1420 $OUT .= ">".$idx."</OPTION>\n";
1422 $OUT .= " </SELECT></TD>\n";
1424 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1427 if (ereg("h", $display) || (empty($display))) {
1428 // Generate hour selection
1429 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1430 for ($idx = 0; $idx <= 23; $idx++) {
1431 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1432 if ($idx == $h) $OUT .= " selected default";
1433 $OUT .= ">".$idx."</OPTION>\n";
1435 $OUT .= " </SELECT></TD>\n";
1437 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1440 if (ereg("m", $display) || (empty($display))) {
1441 // Generate minute selection
1442 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1443 for ($idx = 0; $idx <= 59; $idx++) {
1444 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1445 if ($idx == $m) $OUT .= " selected default";
1446 $OUT .= ">".$idx."</OPTION>\n";
1448 $OUT .= " </SELECT></TD>\n";
1450 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1453 if (ereg("s", $display) || (empty($display))) {
1454 // Generate second selection
1455 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1456 for ($idx = 0; $idx <= 45; $idx += 15) {
1457 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1458 if ($idx == $s) $OUT .= " selected default";
1459 $OUT .= ">".$idx."</OPTION>\n";
1461 $OUT .= " </SELECT></TD>\n";
1463 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1466 $OUT .= "</TABLE>\n";
1468 // Return generated HTML code
1473 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1477 // Do we have a leap year?
1479 $TEST = date('Y', time()) / 4;
1480 $M1 = date("m", time());
1481 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1482 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = $_CONFIG['one_day'];
1483 // First add years...
1484 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1486 $ret += $POST[$prefix."_mo"] * 2628000;
1488 $ret += $POST[$prefix."_we"] * 604800;
1490 $ret += $POST[$prefix."_da"] * 86400;
1492 $ret += $POST[$prefix."_ho"] * 3600;
1494 $ret += $POST[$prefix."_mi"] * 60;
1495 // And at last seconds...
1496 $ret += $POST[$prefix."_se"];
1497 // Return calculated value
1500 // Sends out mail to all administrators
1501 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1502 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1503 // Trim template name
1504 $template = trim($template);
1506 // Load email template
1507 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1509 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1510 // Older version detected!
1511 return SEND_ADMIN_EMAILS($subj, $msg);
1514 // Check which admin shall receive this mail
1515 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1516 array($template), __FILE__, __LINE__);
1517 if (SQL_NUMROWS($result) == 0) {
1518 // Create new entry (to all admins)
1519 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1520 array($template), __FILE__, __LINE__);
1522 // Load admin IDs...
1524 while(list($aid) = SQL_FETCHROW($result)) {
1529 SQL_FREERESULT($result);
1531 // "implode" IDs and query string
1532 $aid = implode(",", $aids);
1534 // Add line to userlog
1535 USERLOG_ADD_LINE($subj, $msg, $UID);
1537 } elseif ($aid == "0") {
1538 // Select all email adresses
1539 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1541 // If Admin-ID is not "to-all" select
1542 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1546 // Load email addresses and send away
1547 while (list($email) = SQL_FETCHROW($result)) {
1548 SEND_EMAIL($email, $subj, $msg);
1552 SQL_FREERESULT($result);
1555 function CREATE_FANCY_TIME($stamp) {
1556 // Get data array with years/months/weeks/days/...
1557 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1559 foreach($data as $k => $v) {
1561 // Value is greater than 0 "eval" data to return string
1562 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1568 // Do we have something there?
1569 if (strlen($ret) > 0) {
1570 // Remove leading commata and space
1571 $ret = substr($ret, 2);
1574 $ret = "0 "._SECONDS;
1577 // Return fancy time string
1581 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1582 $SEP = ""; $TOP = "";
1585 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1589 for ($page = 1; $page <= $PAGES; $page++) {
1590 // Is the page currently selected or shall we generate a link to it?
1591 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1592 // Is currently selected, so only highlight it
1593 $NAV .= "<STRONG>-";
1595 // Open anchor tag and add base URL
1596 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1598 // Add userid when we shall show all mails from a single member
1599 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1601 // Close open anchor tag
1605 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1606 // Is currently selected, so only highlight it
1607 $NAV .= "-</STRONG>";
1613 // Add seperator if we have not yet reached total pages
1614 if ($page < $PAGES) $NAV .= " | ";
1617 // Define constants only once
1618 if (!defined('__NAV_OUTPUT')) {
1619 define('__NAV_OUTPUT' , $NAV);
1620 define('__NAV_COLSPAN', $colspan);
1621 define('__NAV_TOP' , $TOP);
1622 define('__NAV_SEP' , $SEP);
1625 // Load navigation template
1626 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1629 // Return generated HTML-Code
1637 // Extract host from script name
1638 function EXTRACT_HOST (&$script) {
1639 // Use default SERVER_URL by default... ;) So?
1642 // Is this URL valid?
1643 if (substr($script, 0, 7) == "http://") {
1644 // Use the hostname from script URL as new hostname
1645 $url = substr($script, 7);
1646 $extract = explode("/", $url);
1648 // Done extracting the URL :)
1651 // Extract host name
1652 $host = str_replace("http://", "", $url);
1653 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1655 // Generate relative URL
1656 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1657 if (substr(strtolower($script), 0, 7) == "http://") {
1658 // But only if http:// is in front!
1659 $script = substr($script, (strlen($url) + 7));
1660 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1662 $script = substr($script, (strlen($url) + 8));
1665 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1666 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1672 // Send a GET request
1673 function GET_URL ($script) {
1674 // Compile the script name
1675 $script = COMPILE_CODE($script);
1677 // Extract host name from script
1678 $host = EXTRACT_HOST($script);
1680 // Generate GET request header
1681 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1682 $request .= "Host: " . $host . "\r\n";
1683 $request .= "Referer: " . URL . "/admin.php\r\n";
1684 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1685 $request .= "Content-Type: text/plain\r\n";
1686 $request .= "Cache-Control: no-cache\r\n";
1687 $request .= "Connection: Close\r\n\r\n";
1689 // Send the raw request
1690 $response = SEND_RAW_REQUEST($host, $request);
1692 // Return the result to the caller function
1696 // Send a POST request
1697 function POST_URL ($script, $postData) {
1698 // Is postData an array?
1699 if (!is_array($postData)) {
1701 return array("", "", "");
1704 // Compile the script name
1705 $script = COMPILE_CODE($script);
1707 // Extract host name from script
1708 $host = EXTRACT_HOST($script);
1710 // Construct request
1711 $data = http_build_query($postData, '','&');
1713 // Generate POST request header
1714 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1715 $request .= "Host: " . $host . "\r\n";
1716 $request .= "Referer: " . URL . "/admin.php\r\n";
1717 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1718 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1719 $request .= "Content-length: " . strlen($data) . "\r\n";
1720 $request .= "Cache-Control: no-cache\r\n";
1721 $request .= "Connection: Close\r\n\r\n";
1724 // Send the raw request
1725 $response = SEND_RAW_REQUEST($host, $request);
1727 // Return the result to the caller function
1731 // Sends a raw request to another host
1732 function SEND_RAW_REQUEST ($host, $request) {
1736 $response = array("", "", "");
1738 // Default is not to use proxy
1741 // Are proxy settins set?
1742 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1748 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1750 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1752 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1756 if (!is_resource($fp)) {
1763 // Generate CONNECT request header
1764 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1765 $proxyTunnel .= "Host: ".$host."\r\n";
1767 // Use login data to proxy? (username at least!)
1768 if (!empty($_CONFIG['proxy_username'])) {
1770 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1771 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1774 // Add last new-line
1775 $proxyTunnel .= "\r\n";
1776 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1779 fputs($fp, $proxyTunnel);
1783 // No response received
1787 // Read the first line
1788 $resp = trim(fgets($fp, 10240));
1789 $respArray = explode(" ", $resp);
1790 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1791 // Invalid response!
1797 fputs($fp, $request);
1801 $response[] = trim(fgets($fp, 1024));
1807 // Skip first empty lines
1809 foreach ($resp as $idx => $line) {
1811 $line = trim($line);
1813 // Is this line empty?
1816 array_shift($response);
1818 // Abort on first non-empty line
1823 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1825 // Proxy agent found?
1826 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1827 // Proxy header detected, so remove two lines
1828 array_shift($response);
1829 array_shift($response);
1832 // Was the request successfull?
1833 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1834 // Not found / access forbidden
1835 $response = array("", "", "");
1841 // Taken from www.php.net eregi() user comments
1842 function VALIDATE_EMAIL($email) {
1844 $email = COMPILE_CODE($email);
1846 // Check first part of email address
1847 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1850 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1853 $regex = "^".$first."@".$domain."$";
1855 // Return check result
1856 return eregi($regex, $email);
1858 // Function taken from user comments on www.php.net / function eregi()
1859 function VALIDATE_URL ($URL, $compile=true) {
1860 // Trim URL a little
1861 $URL = trim(urldecode($URL));
1862 //* DEBUG: */ echo $URL."<br />";
1864 // Compile some chars out...
1865 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1866 //* DEBUG: */ echo $URL."<br />";
1868 // Check for the extension filter
1869 if (EXT_IS_ACTIVE("filter")) {
1870 // Use the extension's filter set
1871 return FILTER_VALIDATE_URL($URL, false);
1874 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1875 // https:// in front of the URLs
1876 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1879 function MEMBER_ACTION_LINKS($uid, $status="") {
1880 // Define all main targets
1881 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1883 // Begin of navigation links
1884 $eval = "\$OUT = \"[ ";
1886 foreach ($TARGETS as $tar) {
1887 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1888 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1889 if (($tar == "lock_user") && ($status == "LOCKED")) {
1890 // Locked accounts shall be unlocked
1891 $eval .= "UNLOCK_USER";
1893 // All other status is fine
1894 $eval .= strtoupper($tar);
1896 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1897 if (($tar == "lock_user") && ($status == "LOCKED")) {
1898 // Locked accounts shall be unlocked
1899 $eval .= "UNLOCK_USER";
1901 // All other status is fine
1902 $eval .= strtoupper($tar);
1904 $eval .= ".\"</A></SPAN> | ";
1907 // Finish navigation link
1908 $eval = substr($eval, 0, -7)."]\";";
1914 // Function for backward-compatiblity
1915 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1916 // Load it from the register extension
1917 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1919 // Generate an email link
1920 function CREATE_EMAIL_LINK($email, $table="admins") {
1921 // Default email link (INSECURE! Spammer can read this by harvester programs)
1922 $EMAIL = "mailto:".$email;
1924 // Check for several extensions
1925 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1926 // Create email link for contacting admin in guest area
1927 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1928 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1929 // Create email link for contacting a member within admin area (or later in other areas, too?)
1930 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1931 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1932 // Create email link to contact sponsor within admin area (or like the link above?)
1933 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1936 // Shall I close the link when there is no admin?
1937 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1939 // Return email link
1942 // Generate a hash for extra-security for all passwords
1943 function generateHash ($plainText, $salt = "") {
1944 global $_CONFIG, $_SERVER;
1946 // Is the required extension "sql_patches" there and a salt is not given?
1947 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
1948 // Extension sql_patches is missing/outdated so we return the plain text
1952 // Do we miss an arry element here?
1953 if (!isset($_CONFIG['file_hash'])) {
1955 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1956 debug_print_backtrace();
1960 // When the salt is empty build a new one, else use the first x configured characters as the salt
1962 // Build server string
1963 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1966 $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'];
1969 $data = $plainText.":".uniqid(rand(), true).":".time();
1971 // Calculate number for generating the code
1972 $a = time() + _ADD - 1;
1974 // Generate SHA1 sum from modula of number and the prime number
1975 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
1976 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
1977 $sha1 = scrambleString($sha1);
1978 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
1979 //* DEBUG: */ $sha1b = descrambleString($sha1);
1980 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
1982 // Generate the password salt string
1983 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
1984 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
1987 $salt = substr($salt, 0, $_CONFIG['salt_length']);
1988 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
1992 return $salt.sha1($salt.$plainText);
1995 function scrambleString($str) {
2001 // Final check, in case of failture it will return unscrambled string
2002 if (strlen($str) > 40) {
2003 // The string is to long
2005 } elseif (strlen($str) == 40) {
2007 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2009 // Generate new numbers
2010 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2013 // Scramble string here
2014 //* DEBUG: */ echo "***Original=".$str."***<br />";
2015 for ($idx = 0; $idx < strlen($str); $idx++) {
2016 // Get char on scrambled position
2017 $char = substr($str, $scrambleNums[$idx], 1);
2019 // Add it to final output string
2020 $scrambled .= $char;
2023 // Return scrambled string
2024 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2028 function descrambleString($str) {
2030 // Scramble only 40 chars long strings
2031 if (strlen($str) != 40) return $str;
2033 // Load numbers from config
2034 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2037 if (count($scrambleNums) != 40) return $str;
2039 // Begin descrambling
2040 $orig = str_repeat(" ", 40);
2041 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2042 for ($idx = 0; $idx < 40; $idx++) {
2043 $char = substr($str, $idx, 1);
2044 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2047 // Return scrambled string
2048 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2052 function genScrambleString($len) {
2053 // Prepare randomizer and array for the numbers
2054 mt_srand((double) microtime() * 1000000);
2055 $scrambleNumbers = array();
2057 // First we need to setup randomized numbers from 0 to 31
2058 for ($idx = 0; $idx < $len; $idx++) {
2060 $rand = mt_rand(0, ($len -1));
2062 // Check for it by creating more numbers
2063 while (array_key_exists($rand, $scrambleNumbers)) {
2064 $rand = mt_rand(0, ($len -1));
2068 $scrambleNumbers[$rand] = $rand;
2071 // So let's create the string for storing it in database
2072 $scrambleString = implode(":", $scrambleNumbers);
2073 return $scrambleString;
2075 // Append data like session ID referral ID to the given URL which would
2076 // normally be stored in cookies
2077 function ADD_URL_DATA($URL) {
2081 // Determine URL binder
2083 if (strpos($URL, "?") !== false) $BIND = "&";
2085 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2086 // Cookies are not accepted
2087 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2088 // Cookie found in URL
2089 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2090 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2091 // Not found! So let's set default here
2092 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2095 // Is there already added data? Then change the binder
2096 if (!empty($ADD)) $BIND = "&";
2099 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2100 // Add session from URL
2101 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2103 // Add current session
2104 $ADD .= $BIND."PHPSESSID=".session_id();
2108 // Add all together and return it
2111 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2112 function generatePassString($passHash) {
2115 // Return vanilla password hash
2118 // Is a secret key and master salt already initialized?
2119 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2120 // Only calculate when the secret key is generated
2121 $newHash = ""; $start = 9;
2122 for ($idx = 0; $idx < 10; $idx++) {
2123 $part1 = hexdec(substr($passHash, $start, 4));
2124 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2125 $mod = dechex($idx);
2126 if ($part1 > $part2) {
2127 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2128 } elseif ($part2 > $part1) {
2129 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2131 $mod = substr(round($mod), 0, 4);
2132 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2133 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2138 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2139 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2140 //* DEBUG: */ print($ret."<br />\n");
2143 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2144 $ret = md5($passHash);
2145 //* DEBUG: */ echo "++".$ret."++<br />\n";
2152 // Fix "deleted" cookies
2153 function FIX_DELETED_COOKIES ($cookies) {
2154 // Is this an array with entries?
2155 if ((is_array($cookies)) && (count($cookies) > 0)) {
2156 // Then check all cookies if they are marked as deleted!
2157 foreach ($cookies as $cookieName) {
2158 // Is the cookie set to "deleted"?
2159 if (get_session($cookieName) == "deleted") {
2160 set_session($cookieName, "");
2166 // Output error messages in a fasioned way and die...
2167 function mxchange_die ($msg) {
2170 // Load the message template
2171 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2174 include(PATH."inc/footer.php");
2180 // Display parsing time and number of SQL queries in footer
2181 function DISPLAY_PARSING_TIME_FOOTER() {
2182 global $startTime, $_CONFIG;
2183 $endTime = microtime(true);
2185 // Is the timer started?
2186 if (!isset($GLOBALS['startTime'])) {
2191 // "Explode" both times
2192 $start = explode(" ", $GLOBALS['startTime']);
2193 $end = explode(" ", $endTime);
2194 $runTime = $end[0] - $start[0];
2195 if ($runTime < 0) $runTime = 0;
2196 $runTime = TRANSLATE_COMMA($runTime);
2200 'runtime' => $runTime,
2201 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2202 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2205 // Load the template
2206 LOAD_TEMPLATE("show_timings", false, $content);
2209 // Unset/set session variables
2210 function set_session ($var, $value) {
2213 // Abort in CSS mode here
2214 if ($CSS == 1) return true;
2216 // Trim value and session variable
2217 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2219 // Is the session variable set?
2220 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2221 // Remove the session
2222 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2223 unset($_SESSION[$var]);
2224 return session_unregister($var);
2225 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2227 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2228 $_SESSION[$var] = $value;
2229 return session_register($var);
2230 } elseif (!empty($value)) {
2232 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2233 $_SESSION[$var] = $value;
2237 // Ignored (but valid)
2238 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2242 // Check wether a boolean constant is set
2243 // Taken from user comments in PHP documentation for function constant()
2244 function isBooleanConstantAndTrue($constName) { // : Boolean
2247 // Failed by default
2251 if (isset($constCache[$constName])) {
2253 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2254 $res = $constCache[$constName];
2257 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2258 if (defined($constName)) $res = (constant($constName) === true);
2261 $constCache[$constName] = $res;
2263 //* DEBUG: */ var_dump($res);
2269 // Check wether a session variable is set
2270 function isSessionVariableSet($var) {
2271 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2272 return (isset($_SESSION[$var]));
2274 // Returns wether the value of the session variable or NULL if not set
2275 function get_session($var) {
2278 // Default is not found! ;-)
2281 // Is the variable there or cached values?
2282 if (isset($cacheArray['session'][$var])) {
2283 // Get cached value (skips a lot SQL_ESCAPE() calles!
2284 $value = $cacheArray['session'][$var];
2285 } elseif (isSessionVariableSet($var)) {
2286 // Then get it secured!
2287 $value = SQL_ESCAPE($_SESSION[$var]);
2290 $cacheArray['session'][$var] = $value;
2296 // Send notification to admin
2297 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2298 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2300 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2302 // Send outdated way
2303 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2304 SEND_ADMIN_EMAILS($subject, $msg);
2307 // Destroy user session
2308 function destroy_user_session () {
2309 // Remove all user data from session
2310 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2312 // Merges an array together but only if both are arrays
2313 function merge_array ($array1, $array2) {
2314 // Are both an array?
2315 if ((is_array($array1)) && (is_array($array2))) {
2316 // Merge all together
2317 return array_merge($array1, $array2);
2318 } elseif (is_array($array1)) {
2319 // Return left array
2323 // Something wired happened here...
2324 print(__FUNCTION__.":<pre>");
2325 debug_print_backtrace();
2328 // Debug message logger
2329 function DEBUG_LOG ($message, $force=false) {
2330 // Is debug mode enabled?
2331 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2332 // Log this message away
2333 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2334 fwrite($fp, date("d.m.Y|H:i:s", time())."|".strip_tags($message)."\n");
2338 // Reads a directory with PHP files in and gets only files back
2339 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2343 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2346 while ($baseFile = readdir($dirPointer)) {
2347 // Load file only if extension is active
2349 $file = $baseDir.$baseFile;
2351 // Is this a valid reset file?
2352 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2353 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2354 // Remove both for extension name
2355 $extName = substr($baseFile, strlen($prefix), -4);
2358 $extId = GET_EXT_ID($extName);
2360 // Is the extension valid and active?
2361 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2362 // Then add this file
2364 } elseif ($extId == 0) {
2365 // Add non-extension files as well
2372 closedir($dirPointer);
2374 // Return array with include files
2377 // Load more reset scripts
2378 function RESET_ADD_INCLUDES () {
2381 // Is the reset set or old sql_patches?
2382 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2387 // Get more daily reset scripts
2388 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2390 // Create current week mark
2391 $currWeek = date("W", time());
2394 if ($_CONFIG['last_week'] != $currWeek) {
2395 // Include weekly reset scripts
2396 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2399 UPDATE_CONFIG("last_week", $currWeek);
2402 // Create current month mark
2403 $currMonth = date("m", time());
2406 if ($_CONFIG['last_month'] != $currMonth) {
2407 // Include monthly reset scripts
2408 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2411 UPDATE_CONFIG("last_month", $currMonth);
2417 // Handle extra values
2418 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2419 // Default is the value itself
2422 // Do we have a special filter function?
2423 if (!empty($filterFunction)) {
2424 // Does the filter function exist?
2425 if (function_exists($filterFunction)) {
2426 // Do we have extra parameters here?
2427 if (!empty($extraValue)) {
2428 // Put both parameters in one new array by default
2429 $args = array($value, $extraValue);
2431 // If we have an array simply use it and pre-extend it with our value
2432 if (is_array($extraValue)) {
2433 // Make the new args array
2434 $args = array_merge(array($value), $extraValue);
2437 // Call the multi-parameter call-back
2438 $ret = call_user_func_array($filterFunction, $args);
2440 // One parameter call
2441 $ret = call_user_func($filterFunction, $value);
2449 // Check if given FQFN is a readable file
2450 function FILE_READABLE($fqfn) {
2452 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2454 // Converts timestamp selections into a timestamp
2455 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2456 // Init test variable
2459 // Get last three chars
2460 $TEST = substr($id, -3);
2462 // Improved way of checking! :-)
2463 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2464 // Found a multi-selection for timings?
2465 $TEST = substr($id, 0, -3);
2466 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)) {
2467 // Generate timestamp
2468 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2469 $DATA[] = "$TEST='".$POST[$TEST]."'";
2471 // Remove data from array
2472 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2473 unset($POST[$TEST."_".$rem]);
2477 unset($id); $skip = true; $TEST2 = $TEST;
2480 // Process this entry
2481 $skip = false; $TEST2 = "";
2484 // Reverts the german decimal comma into Computer decimal dot
2485 function REVERT_COMMA ($str) {
2486 // Default float is not a float... ;-)
2489 // Which language is selected?
2490 switch (GET_LANGUAGE()) {
2491 case "de": // German language
2492 // Remove german thousand dots first
2493 $str = str_replace(".", "", $str);
2495 // Replace german commata with decimal dot and cast it
2496 $float = (float)str_replace(",", ".", $str);
2499 default: // US and so on
2500 // Remove thousand dots first and cast
2501 $float = (float)str_replace(",", "", $str);
2508 // Handle menu-depending failed logins and return the rendered content
2509 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2510 // Default output is empty ;-)
2513 // Is the session data set?
2514 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2515 // Ignore zero values
2516 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2517 // Non-guest has login failtures found, get both data and prepare it for template
2518 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2520 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2521 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2525 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2528 // Reset session data
2529 set_session('mxchange_'.$accessLevel.'_failtures', "");
2530 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2533 // Return rendered content
2537 function REBUILD_CACHE ($cache, $inc="") {
2538 global $cacheInstance, $_CONFIG, $CSS;
2540 // Shall I remove the cache file?
2541 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2543 if ($cacheInstance->cache_file($cache, true)) {
2545 $cacheInstance->cache_destroy();
2548 // Include file given?
2551 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2553 // Is the include there?
2554 if (FILE_READABLE($fqfn)) {
2555 // And rebuild it from scratch
2558 // Include not found!
2559 DEBUG_LOG(__FUNCTION__.":Include {$inc} not found. cache={$cache}");
2564 // Purge admin menu cache
2565 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2566 global $_CONFIG, $cacheInstance;
2568 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2569 if (!EXT_IS_ACTIVE("cache")) {
2570 // Cache extension not active
2572 } elseif (!is_object($cacheInstance)) {
2573 // No cache instance!
2574 DEBUG_LOG(__FUNCTION__.": No cache instance found.");
2576 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2577 // Caching disabled (currently experiemental!)
2581 // Experiemental feature!
2582 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2584 // Translates the "pool type" into human-readable
2585 function TRANSLATE_POOL_TYPE ($type) {
2586 // Default type is unknown
2587 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2589 // Generate constant
2590 $constName = sprintf("POOL_TYPE_%s", $type);
2593 if (defined($constName)) {
2595 $translated = constant($constName);
2598 // Return "translation"
2601 // "Getter" for remote IP number
2602 function GET_REMOTE_ADDR () {
2603 // Get remote ip from environment
2604 $remoteAddr = getenv('REMOTE_ADDR');
2606 // Is removeip installed?
2607 if (EXT_IS_ACTIVE("removeip")) {
2608 // Then anonymize it
2609 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2615 // "Getter" for remote hostname
2616 function GET_REMOTE_HOST () {
2617 // Get remote ip from environment
2618 $remoteHost = getenv('REMOTE_HOST');
2620 // Is removeip installed?
2621 if (EXT_IS_ACTIVE("removeip")) {
2622 // Then anonymize it
2623 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2629 // "Getter" for user agent
2630 function GET_USER_AGENT () {
2631 // Get remote ip from environment
2632 $userAgent = getenv('HTTP_USER_AGENT');
2634 // Is removeip installed?
2635 if (EXT_IS_ACTIVE("removeip")) {
2636 // Then anonymize it
2637 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2643 // "Getter" for referer
2644 function GET_REFERER () {
2645 // Get remote ip from environment
2646 $referer = getenv('HTTP_REFERER');
2648 // Is removeip installed?
2649 if (EXT_IS_ACTIVE("removeip")) {
2650 // Then anonymize it
2651 $referer = GET_ANONYMOUS_REFERER($referer);
2658 //////////////////////////////////////////////////
2660 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2662 //////////////////////////////////////////////////
2664 if (!function_exists('html_entity_decode')) {
2665 // Taken from documentation on www.php.net
2666 function html_entity_decode($string) {
2667 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2668 $trans_tbl = array_flip($trans_tbl);
2669 return strtr($string, $trans_tbl);