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) {
43 $fqfn = sprintf("%sinc/%s.php", PATH, $inc);
45 // Abort by simple test
46 if ((FILE_READABLE($fqfn)) && (!is_writeable($fqfn))) {
50 // Test if we can append data
51 $fp = @fopen($fqfn, 'a');
52 if ($inc == "dummy") {
55 return @unlink($fqfn);
57 // Close all other files
62 // Open a table (you may want to add some header stuff here)
63 function OPEN_TABLE($PERCENT = "", $CLASS = "", $ALIGN="left", $VALIGN="", $td_only=false) {
66 // Count tables so we can generate CSS classes for every table... :-)
68 // Class is empty so count one up and create a class
69 $table_cnt++; $CLASS = "class".$table_cnt;
71 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
73 // Shall I add the classes to TABLE and TD or only to TD?
74 if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
77 if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
80 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
82 // Vertical align is given
83 if (!empty($VALIGN)) $OUT .= " valign=\"".$VALIGN."\"";
84 $OUT .= ">\n<TR>\n<TD";
85 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
86 $OUT .= " class=\"".$CLASS."\">";
90 // Close a table (you may want to add some footer stuff here)
91 function CLOSE_TABLE($ADD="") {
92 OUTPUT_HTML(" </TD>\n</TR>");
93 if (!empty($ADD)) OUTPUT_HTML($ADD);
94 OUTPUT_HTML("</TABLE>");
97 // Output HTML code directly or "render" it. You addionally switch the new-line character off
98 function OUTPUT_HTML($HTML, $NEW_LINE = true) {
99 // Some global variables
100 global $OUTPUT, $footer, $CSS;
102 // Do we have HTML-Code here?
104 // Yes, so we handle it as you have configured
108 // That's why you don't need any \n at the end of your HTML code... :-)
109 if (_OB_CACHING == "on") {
110 // Output into PHP's internal buffer
113 // That's why you don't need any \n at the end of your HTML code... :-)
114 if ($NEW_LINE) echo "\n";
116 // Render mode for old or lame servers...
119 // That's why you don't need any \n at the end of your HTML code... :-)
120 if ($NEW_LINE) $OUTPUT .= "\n";
125 // If we are switching from render to direct output rendered code
126 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
128 // The same as above... ^
130 if ($NEW_LINE) echo "\n";
134 // Huh, something goes wrong or maybe you have edited config.php ???
135 die ("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
138 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
139 // Output cached HTML code
140 $OUTPUT = ob_get_contents();
142 // Clear output buffer for later output
145 // Extension "rewrite" installed?
146 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
147 $OUTPUT = REWRITE_LINKS($OUTPUT);
150 // Compile and run finished rendered HTML code
151 while (strpos($OUTPUT, '{!') > 0) {
152 // Prepare the content and eval() it...
154 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
157 // Was that eval okay?
158 if (empty($newContent)) {
159 // Something went wrong!
160 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
162 $OUTPUT = $newContent;
165 // Output code here, DO NOT REMOVE! ;-)
167 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
168 // Rewrite links when rewrite extension is active
169 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
170 $OUTPUT = REWRITE_LINKS($OUTPUT);
173 // Compile and run finished rendered HTML code
174 while (strpos($OUTPUT, '{!') > 0) {
175 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
179 // Output code here, DO NOT REMOVE! ;-)
184 // Output the raw HTML code
185 function OUTPUT_RAW ($HTML) {
186 // Output stripped HTML code to avoid broken JavaScript code, etc.
187 echo stripslashes(stripslashes($HTML));
189 // Flush the output if only _OB_CACHING is not "on"
190 if (_OB_CACHING != "on") {
196 // Add a fatal error message to the queue array
197 function ADD_FATAL ($message, $extra="") {
201 // Regular text message to add to $FATAL
204 // $message is text with a mask plus extras to insert into the text
205 $message = sprintf($message, $extra);
209 // Log fatal messages away
210 DEBUG_LOG(__FUNCTION__."(".__LINE__."): message={$message}");
213 // Load a template file and return it's content (only it's name; do not use ' or ")
214 function LOAD_TEMPLATE($template, $return=false, $content=array()) {
215 // Add more variables which you want to use in your template files
216 global $DATA, $_CONFIG, $username;
218 // Make all template names lowercase
219 $template = strtolower($template);
221 // Count the template load
222 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
223 $_CONFIG['num_templates']++;
227 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
229 // @DEPRECATED Try to remove this if() block
230 if ($template == "member_support_form") {
231 // Support request of a member
232 $result = SQL_QUERY_ESC("SELECT gender, surname, family, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
233 array($GLOBALS['userid']), __FILE__, __LINE__);
235 // Is content an array?
236 if (is_array($content)) {
238 $content = array_merge($content, SQL_FETCHARRAY($result));
241 $content['gender'] = TRANSLATE_GENDER($content['gender']);
243 // DEPRECATED: Load data in direct variables
244 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
247 $gender = TRANSLATE_GENDER($gender);
251 SQL_FREERESULT($result);
254 // Generate date/time string
255 $date_time = MAKE_DATETIME(time(), "1");
258 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
261 // Check for admin/guest/member templates
262 if (strpos($template, "admin_") > -1) {
263 // Admin template found
265 } elseif (strpos($template, "guest_") > -1) {
266 // Guest template found
268 } elseif (strpos($template, "member_") > -1) {
269 // Member template found
271 } elseif (strpos($template, "install_") > -1) {
272 // Installation template found
274 } elseif (strpos($template, "ext_") > -1) {
275 // Extension template found
277 } elseif (strpos($template, "la_") > -1) {
278 // "Logical-area" template found
281 // Test for extension
282 $test = substr($template, 0, strpos($template, "_"));
283 if (EXT_IS_ACTIVE($test)) {
284 // Set extra path to extension's name
289 ////////////////////////
290 // Generate file name //
291 ////////////////////////
292 $file = $BASE.$MODE.$template.".tpl";
294 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
295 // Select what depended header/footer template file for admin/guest/member area
296 $file2 = sprintf("%s%s%s_%s.tpl",
300 SQL_ESCAPE($GLOBALS['what'])
304 if (FILE_READABLE($file2)) $file = $file2;
306 // Remove variable from memory
310 // Does the special template exists?
311 if (!FILE_READABLE($file)) {
312 // Reset to default template
313 $file = $BASE.$template.".tpl";
316 // Now does the final template exists?
317 if (FILE_READABLE($file)) {
318 // The local file does exists so we load it. :)
319 $tmpl_file = implode("", file($file));
321 // Replace ' to our own chars to preventing them being quoted
322 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
324 // Do we have to compile the code?
326 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
328 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
331 // Simply return loaded code
335 // Add surrounding HTML comments to help finding bugs faster
336 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
337 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
338 // Only admins shall see this warning or when installation mode is active
339 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
340 (".basename($file).")<br />
343 <pre>".print_r($content, true)."</pre>
345 <pre>".print_r($DATA, true)."</pre>
349 // Remove content and data
353 // Do we have some content to output or return?
355 // Not empty so let's put it out! ;)
357 // Return the HTML code
363 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
364 // Warning, empty output!
365 return "E:".$template."<br />\n";
369 // Send mail out to an email address
370 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
371 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
373 // Compile subject line (for POINTS constant etc.)
374 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
378 if ((!eregi("@", $TO)) && ($TO > 0)) {
379 // Value detected, is the message extension installed?
380 if (EXT_IS_ACTIVE("msg")) {
381 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
384 // Load email address
385 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
386 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
388 // Does the user exist?
389 if (SQL_NUMROWS($result_email)) {
390 // Load email address
391 list($TO) = SQL_FETCHROW($result_email);
398 SQL_FREERESULT($result_email);
400 } elseif ("$TO" == "0") {
404 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
406 // Check for PHPMailer or debug-mode
407 if (!CHECK_PHPMAILER_USAGE()) {
408 // Not in PHPMailer-Mode
410 // Load email header template
411 $FROM = LOAD_EMAIL_TEMPLATE("header");
414 $FROM .= LOAD_EMAIL_TEMPLATE("header");
416 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
418 // Load email header template
419 $FROM = LOAD_EMAIL_TEMPLATE("header");
422 $FROM .= LOAD_EMAIL_TEMPLATE("header");
427 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
431 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
434 // Fix HTML parameter (default is no!)
435 if (empty($HTML)) $HTML = "N";
436 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
437 // In debug mode we want to display the mail instead of sending it away so we can debug this part
439 ".htmlentities(trim($FROM))."
441 Subject : ".$SUBJECT."
446 if (defined('DEBUG_MAIL')) DEBUG_LOG(__FUNCTION__.":to={$TO},subject={$SUBJECT},msg={$MSG}");
447 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
448 // Send mail as HTML away
449 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
450 } elseif (!empty($TO)) {
452 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
453 } elseif ($HTML == "N") {
455 SEND_RAW_EMAIL(WEBMASTER, "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
459 // Check if legacy or PHPMailer command
461 function CHECK_PHPMAILER_USAGE() {
462 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
466 * Send out a raw email with PHPMailer class or legacy mail() command
468 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
469 // Shall we use PHPMailer class or legacy mode?
470 if (CHECK_PHPMAILER_USAGE()) {
471 // Use PHPMailer class with SMTP enabled
472 require_once(PATH."inc/phpmailer/class.phpmailer.php");
473 require_once(PATH."inc/phpmailer/class.smtp.php");
476 $mail = new PHPMailer();
477 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
480 $mail->SMTPAuth = true;
481 $mail->Host = SMTP_HOSTNAME;
483 $mail->Username = SMTP_USER;
484 $mail->Password = SMTP_PASSWORD;
486 $mail->From = WEBMASTER;
490 $mail->FromName = MAIN_TITLE;
491 $mail->Subject = $subject;
492 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
494 $mail->AltBody = "Your mail program required HTML support to read this mail!";
495 $mail->WordWrap = 70;
498 $mail->Body = html_entity_decode($msg);
500 $mail->AddAddress($to, "");
501 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
502 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
503 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
506 // Use legacy mail() command
507 @mail($to, $subject, html_entity_decode($msg), $from);
512 // Generate a password in a specified length or use default password length
513 function GEN_PASS($LEN = 0) {
515 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
517 // Initialize array with all allowed chars
518 $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,-,+,_,/");
520 // Initialize randomizer
521 mt_srand((double) microtime() * 1000000);
523 // Start creating password
525 for ($i = 0; $i < $LEN; $i++) {
526 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
529 // When the size is below 40 we can also add additional security by scrambling it
530 if (strlen($PASS) <= 40) {
531 // Also scramble the password
532 $PASS = scrambleString($PASS);
535 // Return the password
539 function MAKE_DATETIME ($time, $mode="0")
543 return NEVER_HAPPENED;
545 // Filter out numbers
546 $time = bigintval($time);
549 switch (GET_LANGUAGE())
551 case "de": // German date / time format
553 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
554 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
555 case "2": $ret = date("d.m.Y|H:i", $time); break;
556 case "3": $ret = date("d.m.Y", $time); break;
560 default: // Default is the US date / time format!
562 case "0": $ret = date("r", $time); break;
563 case "1": $ret = date("Y-m-d - g:i A", $time); break;
564 case "2": $ret = date("y-m-d|H:i", $time); break;
565 case "3": $ret = date("y-m-d", $time); break;
571 // Translates the american decimal dot into a german comma
572 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
575 // Default is 3 you can change this in admin area "Misc -> Misc Options"
576 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
578 // Use from config is default
579 $maxComma = $_CONFIG['max_comma'];
581 // Use from parameter?
582 if ($max > 0) $maxComma = $max;
586 // Test for commata if in cut-mode
587 $com = explode(".", $dotted);
588 if (count($com) > 1) {
589 // Commata found, so only zeros?
590 if ($com[1] == str_repeat("0", strlen($com[1]))) {
591 // Only zeros, so display only one
595 // Don't display commatas even if there are none... ;-)
601 //DEBUG_LOG(__FUNCTION__.":dotted={$dotted},maxComma={$maxComma}");
604 switch (GET_LANGUAGE()) {
606 $dotted = number_format($dotted, $maxComma, ",", ".");
610 $dotted = number_format($dotted, $maxComma, ".", ",");
614 // Return translated value
619 function DEREFERER ($URL) {
620 // Don't de-refer our own links!
621 if (substr($URL, 0, strlen(URL)) != URL) {
622 // De-refer this link
623 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
631 function TRANSLATE_GENDER ($gender) {
634 case "M": $ret = GENDER_M; break;
635 case "F": $ret = GENDER_F; break;
636 case "C": $ret = GENDER_C; break;
637 default : $ret = $gender; break;
642 function FRAMETESTER($URL) {
643 // Prepare frametester URL
644 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
646 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
648 return $frametesterUrl;
651 function SELECTION_COUNT($array) {
653 if (is_array($array)) {
654 foreach ($array as $key => $sel) {
655 if (!empty($sel)) $ret++;
661 function IMG_CODE ($code, $type, $DATA, $uid) {
662 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
665 function TRANSLATE_STATUS($status) {
669 $ret = ACCOUNT_UNCONFIRMED;
673 $ret = ACCOUNT_CONFIRMED;
677 $ret = ACCOUNT_LOCKED;
682 $ret = ACCOUNT_DELETED;
686 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
692 function GET_LANGUAGE() {
693 if (!empty($_GET['mx_lang'])) {
694 // Accept only first 2 chars
695 $lang = substr($_GET['mx_lang'], 0, 2);
701 // Set default return value to default language from config
704 // Check GET variable and cookie
706 // Check if main language file does exist
707 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
708 // Okay found, so let's update cookies
711 } elseif (!isSessionVariableSet('mx_lang')) {
712 // Return stored value from cookie
713 $ret = get_session('mx_lang');
715 // Fixes a warning before the session has the mx_lang constant
716 if (empty($ret)) $ret = DEFAULT_LANG;
721 function SET_LANGUAGE($lang) {
724 // Accept only first 2 chars!
725 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
728 set_session("mx_lang", $lang);
731 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
732 global $DATA, $_CONFIG, $REPLACER;
734 // Make sure all template names are lowercase!
735 $template = strtolower($template);
737 // Default "nickname" if extension is not installed
740 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
741 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
743 // Prepare IP number and User Agent
744 $REMOTE_ADDR = GET_REMOTE_ADDR();
745 $HTTP_USER_AGENT = GET_USER_AGENT();
750 // Is the admin logged in?
753 $ADMIN = GET_ADMIN_EMAIL(get_session('admin_login'));
756 // Neutral email address is default
759 // Expiration in a nice output format
760 if ($_CONFIG['auto_purge'] == 0) {
761 // Will never expire!
762 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
763 } elseif (function_exists('CREATE_FANCY_TIME')) {
764 // Create nice date string
765 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
768 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
771 // Is content an array?
772 if (is_array($content)) {
773 // Add expiration to array, $EXPIRATION is now deprecated!
774 $content['expiration'] = $EXPIRATION;
778 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template}<br />\n";
780 if (EXT_IS_ACTIVE("nickname")) {
781 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
783 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
784 array(bigintval($UID)), __FILE__, __LINE__);
786 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
788 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
789 array(bigintval($UID)), __FILE__, __LINE__);
792 // Is content an array?
793 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content[]=".gettype($content)."<br />\n";
794 if (is_array($content)) {
795 // Fetch and migrate data
796 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
797 $content = array_merge($content, SQL_FETCHARRAY($result));
798 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
802 SQL_FREERESULT($result);
805 // Translate M to male or F to female if present
806 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
808 // Overwrite email from data if present
809 if (isset($content['email'])) $email = $content['email'];
811 // Store email for some functions in global data array
812 $DATA['email'] = $email;
815 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
817 // Check for admin/guest/member templates
818 if (strpos($template, "admin_") > -1) {
819 // Admin template found
820 $file = $BASE."admin/".$template.".tpl";
821 } elseif (strpos($template, "guest_") > -1) {
822 // Guest template found
823 $file = $BASE."guest/".$template.".tpl";
824 } elseif (strpos($template, "member_") > -1) {
825 // Member template found
826 $file = $BASE."member/".$template.".tpl";
828 // Test for extension
829 $test = substr($template, 0, strpos($template, "_"));
830 if (EXT_IS_ACTIVE($test)) {
831 // Set extra path to extension's name
832 $file = $BASE.$test."/".$template.".tpl";
834 // No special filename
835 $file = $BASE.$template.".tpl";
839 // Does the special template exists?
840 if (!FILE_READABLE($file)) {
841 // Reset to default template
842 $file = $BASE.$template.".tpl";
845 // Now does the final template exists?
847 if (FILE_READABLE($file)) {
848 // The local file does exists so we load it. :)
849 $tmpl_file = implode("", file($file));
850 $tmpl_file = addslashes($tmpl_file);
853 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
855 } elseif (!empty($template)) {
856 // Template file not found!
857 $newContent = TEMPLATE_404.": ".$template."<br />
859 <pre>".print_r($content, true)."</pre>
861 <pre>".print_r($DATA, true)."</pre>
864 // Debug mode not active? Then remove the HTML tags
865 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
867 // No template name supplied!
868 $newContent = NO_TEMPLATE_SUPPLIED;
871 // Is there some content?
872 if (empty($newContent)) {
874 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
875 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
878 // Remove content and data
882 // Return compiled content
883 return COMPILE_CODE($newContent);
886 function MAKE_TIME($H, $M, $S, $stamp) {
887 // Extract day, month and year from given timestamp
888 $DAY = date("d", $stamp);
889 $MONTH = date("m", $stamp);
890 $YEAR = date('Y', $stamp);
892 // Create timestamp for wished time which depends on extracted date
893 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
896 function LOAD_URL($URL, $addUrlData=true) {
897 global $CSS, $_CONFIG, $footer;
899 // Check if http(s):// is there
900 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
901 // Make all URLs full-qualified
905 // Compile out URI codes
906 $URL = COMPILE_CODE($URL);
909 $OUTPUT = ob_get_contents();
911 // Clear it only if there is content
912 if (!empty($OUTPUT)) {
916 // Add some data to URL if cookies are not accepted
917 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
919 // Probe for bot from search engine
920 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT())) || (eregi("spider", GET_USER_AGENT()))) {
921 // Search engine bot detected so let's rewrite many chars for the link
922 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
924 // Output new location link as anchor
925 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
926 } elseif (!headers_sent()) {
927 // Load URL when headers are not sent
930 debug_print_backtrace();
931 die("</pre>URL={$URL}");
933 @header ("Location: ".str_replace("&", "&", $URL));
935 // Output error message
936 include(PATH."inc/header.php");
937 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
938 include(PATH."inc/footer.php");
943 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
944 global $SEC_CHARS, $URL_CHARS;
945 // Is the code a string?
946 if (!is_string($code)) {
947 // Silently return it
953 // Select smaller set of chars to replace when we e.g. want to compile URLs
954 if (!$full) $ARRAY = $URL_CHARS;
958 // BEFORE 0.2.1 : Language and data constants
959 // WITH 0.2.1+ : Only language constants
960 $code = str_replace('{--','".', str_replace('--}','."', $code));
962 // BEFORE 0.2.1 : Not used
963 // WITH 0.2.1+ : Data constants
964 $code = str_replace('{!','".', str_replace("!}", '."', $code));
967 // Compile QUOT and other non-HTML codes
968 foreach ($ARRAY['to'] as $k => $to) {
969 // Do the reversed thing as in inc/libs/security_functions.php
970 $code = str_replace($to, $ARRAY['from'][$k], $code);
973 // But shall I keep simple quotes for later use?
974 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
976 // Find $content[bla][blub] entries
977 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
979 // Are some matches found?
980 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
981 // Replace all matches
982 $matchesFound = array();
983 foreach ($matches[0] as $key => $match) {
984 // Fuzzy look has failed by default
987 // Fuzzy look on match if already found
988 foreach ($matchesFound as $found => $set) {
990 $test = substr($found, 0, strlen($match));
992 // Does this entry exist?
993 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
994 if ($test == $match) {
996 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1003 if ($fuzzyFound) continue;
1005 // Take all string elements
1006 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1007 // Replace it in the code
1008 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1009 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1010 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1011 $matchesFound[$key."_".$matches[4][$key]] = 1;
1012 $matchesFound[$match] = 1;
1013 } elseif (!isset($matchesFound[$match])) {
1014 // Not yet replaced!
1015 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1016 $code = str_replace($match, "\".".$match.".\"", $code);
1017 $matchesFound[$match] = 1;
1022 // Return compiled code
1026 /************************************************************************
1028 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1029 * $a_sort sortiert: *
1031 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1032 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1033 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1034 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1035 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1037 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1038 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1039 * Sie, dass es doch nicht so schwer ist! :-) *
1041 ************************************************************************/
1042 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1045 while ($primary_key < count($a_sort)) {
1046 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1047 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1050 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1051 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1052 } elseif ($key != $key2) {
1053 // Sort numbers (E.g.: 9 < 10)
1054 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1055 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1059 // We have found two different values, so let's sort whole array
1060 foreach ($dummy as $sort_key => $sort_val) {
1061 $t = $dummy[$sort_key][$key];
1062 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1063 $dummy[$sort_key][$key2] = $t;
1074 // Write back sorted array
1078 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1080 global $MONTH_DESCR; $OUT = "";
1083 // This is a yes/no selection only!
1084 if ($id > 0) $prefix .= "[".$id."]";
1085 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1089 // Begin with regular selection box here
1090 if (!empty($prefix)) $prefix .= "_";
1092 if ($id > 0) $type2 .= "[".$id."]";
1093 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1098 for ($idx = 1; $idx < 32; $idx++)
1100 $OUT .= "<OPTION value=\"".$idx."\"";
1101 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1102 $OUT .= ">".$idx."</OPTION>\n";
1106 case "month": // Month
1107 foreach ($MONTH_DESCR as $month => $descr)
1109 $OUT .= "<OPTION value=\"".$month."\"";
1110 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1111 $OUT .= ">".$descr."</OPTION>\n";
1115 case "year": // Year
1117 $YEAR = date('Y', time());
1119 // Check if the default value is larger than minimum and bigger than actual year
1120 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1122 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1124 $OUT .= "<OPTION value=\"".$idx."\"";
1125 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1126 $OUT .= ">".$idx."</OPTION>\n";
1129 elseif ($DEFAULT == -1)
1131 // Current year minus 1
1132 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1134 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1139 // Get current year and subtract 16 (for erotic content)
1140 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1141 $YEAR = date('Y', time()) - 16;
1142 for ($idx = 1930; $idx <= $YEAR; $idx++)
1144 $OUT .= "<OPTION value=\"".$idx."\"";
1145 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1146 $OUT .= ">".$idx."</OPTION>\n";
1153 for ($idx = 0; $idx < 60; $idx+=5) {
1154 if (strlen($idx) == 1) $idx = "0".$idx;
1155 $OUT .= "<OPTION value=\"".$idx."\"";
1156 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1157 $OUT .= ">".$idx."</OPTION>\n";
1162 for ($idx = 0; $idx < 24; $idx++) {
1163 if (strlen($idx) == 1) $idx = "0".$idx;
1164 $OUT .= "<OPTION value=\"".$idx."\"";
1165 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1166 $OUT .= ">".$idx."</OPTION>\n";
1171 $OUT .= "<OPTION value=\"Y\"";
1172 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1173 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1174 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1175 $OUT .= ">".NO."</OPTION>\n";
1178 $OUT .= " </SELECT>\n";
1182 function TRANSLATE_YESNO($yn)
1186 case 'Y': $yn = YES; break;
1187 case 'N': $yn = NO; break;
1188 default : $yn = "??? (".$yn.")"; break;
1193 // Deprecated : $length
1196 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1199 // Fix missing _MAX constant
1200 if (!defined('_MAX')) define('_MAX', 15235);
1202 // Build server string
1203 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1206 $keys = SITE_KEY.":".DATE_KEY;
1207 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1208 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1209 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1210 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1212 // Build string from misc data
1213 $data = $code.":".$uid.":".$DATA;
1215 // Add more additional data
1216 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1217 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1218 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1219 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1220 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1221 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1223 // Calculate number for generating the code
1224 $a = $code + _ADD - 1;
1226 if (isset($_CONFIG['master_hash'])) {
1227 // Generate hash with master salt from modula of number with the prime number and other data
1228 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1230 // Create number from hash
1231 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1233 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1234 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1236 // Create number from hash
1237 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1240 // At least 10 numbers shall be secure enought!
1241 $len = $_CONFIG['code_length'];
1242 if ($len == 0) $len = $length;
1243 if ($len == 0) $len = 10;
1245 // Cut off requested counts of number
1246 $return = substr(str_replace('.', "", $rcode), 0, $len);
1248 // Done building code
1251 // Does only allow numbers
1252 function bigintval($num, $castValue = true) {
1253 // Filter all numbers out
1254 $ret = preg_replace("/[^0123456789]/", "", $num);
1257 if ($castValue) $ret = (double)$ret;
1259 // Has the whole value changed?
1260 if ("".$ret."" != "".$num."") {
1262 DEBUG_LOG(__FUNCTION__.": num={$num},ret={$ret}");
1268 // Insert the code in $img_code into jpeg or PNG image
1269 function GENERATE_IMAGE($img_code, $header=true) {
1272 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1273 // Stop execution of function here because of over-sized code length
1275 } elseif (!$header) {
1276 // Return in an HTML code code
1277 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1281 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1282 if (FILE_READABLE($img)) {
1283 // Switch image type
1284 switch ($_CONFIG['img_type'])
1287 // Okay, load image and hide all errors
1288 $image = @imagecreatefromjpeg($img);
1292 // Okay, load image and hide all errors
1293 $image = @imagecreatefrompng($img);
1297 // Exit function here
1301 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1302 $text_color = imagecolorallocate($image, 0, 0, 0);
1304 // Insert code into image
1305 imagestring($image, 5, 14, 2, $img_code, $text_color);
1307 // Return to browser
1308 header ("Content-Type: image/".$_CONFIG['img_type']);
1310 // Output image with matching image factory
1311 switch ($_CONFIG['img_type']) {
1312 case "jpg": imagejpeg($image); break;
1313 case "png": imagepng($image); break;
1316 // Remove image from memory
1317 imagedestroy($image);
1319 // Create selection box or array of splitted timestamp
1320 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1323 // Calculate 2-seconds timestamp
1324 $stamp = round($timestamp);
1326 // Do we have a leap year?
1328 $TEST = date('Y', time()) / 4;
1329 $M1 = date("m", time());
1330 $M2 = date("m", (time() + $stamp));
1332 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1333 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = $_CONFIG['one_day'];
1335 // First of all years...
1336 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1338 $M = abs(floor($stamp / 2628000 - $Y * 12));
1340 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / $_CONFIG['one_day']) / 7) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day']) / 7)));
1342 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / $_CONFIG['one_day']) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day'])) - $W * 7));
1344 $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));
1346 $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));
1347 // And at last seconds...
1348 $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));
1350 // Is seconds zero and time is < 60 seconds?
1351 if (($s == 0) && ($stamp < 60)) {
1353 $s = round($timestamp);
1357 // Now we convert them in seconds...
1359 if ($return_array) {
1360 // Just put all data in an array for later use
1372 $OUT = "<DIV align=\"".$align."\">\n";
1373 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1376 if (ereg('Y', $display) || (empty($display))) {
1377 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1380 if (ereg("M", $display) || (empty($display))) {
1381 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1384 if (ereg("W", $display) || (empty($display))) {
1385 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1388 if (ereg("D", $display) || (empty($display))) {
1389 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1392 if (ereg("h", $display) || (empty($display))) {
1393 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1396 if (ereg("m", $display) || (empty($display))) {
1397 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1400 if (ereg("s", $display) || (empty($display))) {
1401 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1407 if (ereg('Y', $display) || (empty($display))) {
1408 // Generate year selection
1409 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1410 for ($idx = 0; $idx <= 10; $idx++) {
1411 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1412 if ($idx == $Y) $OUT .= " selected default";
1413 $OUT .= ">".$idx."</OPTION>\n";
1415 $OUT .= " </SELECT></TD>\n";
1417 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1420 if (ereg("M", $display) || (empty($display))) {
1421 // Generate month selection
1422 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1423 for ($idx = 0; $idx <= 11; $idx++)
1425 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1426 if ($idx == $M) $OUT .= " selected default";
1427 $OUT .= ">".$idx."</OPTION>\n";
1429 $OUT .= " </SELECT></TD>\n";
1431 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1434 if (ereg("W", $display) || (empty($display))) {
1435 // Generate week selection
1436 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1437 for ($idx = 0; $idx <= 4; $idx++) {
1438 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1439 if ($idx == $W) $OUT .= " selected default";
1440 $OUT .= ">".$idx."</OPTION>\n";
1442 $OUT .= " </SELECT></TD>\n";
1444 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1447 if (ereg("D", $display) || (empty($display))) {
1448 // Generate day selection
1449 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1450 for ($idx = 0; $idx <= 31; $idx++) {
1451 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1452 if ($idx == $D) $OUT .= " selected default";
1453 $OUT .= ">".$idx."</OPTION>\n";
1455 $OUT .= " </SELECT></TD>\n";
1457 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1460 if (ereg("h", $display) || (empty($display))) {
1461 // Generate hour selection
1462 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1463 for ($idx = 0; $idx <= 23; $idx++) {
1464 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1465 if ($idx == $h) $OUT .= " selected default";
1466 $OUT .= ">".$idx."</OPTION>\n";
1468 $OUT .= " </SELECT></TD>\n";
1470 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1473 if (ereg("m", $display) || (empty($display))) {
1474 // Generate minute selection
1475 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1476 for ($idx = 0; $idx <= 59; $idx++) {
1477 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1478 if ($idx == $m) $OUT .= " selected default";
1479 $OUT .= ">".$idx."</OPTION>\n";
1481 $OUT .= " </SELECT></TD>\n";
1483 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1486 if (ereg("s", $display) || (empty($display))) {
1487 // Generate second selection
1488 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1489 for ($idx = 0; $idx <= 45; $idx += 15) {
1490 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1491 if ($idx == $s) $OUT .= " selected default";
1492 $OUT .= ">".$idx."</OPTION>\n";
1494 $OUT .= " </SELECT></TD>\n";
1496 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1499 $OUT .= "</TABLE>\n";
1501 // Return generated HTML code
1506 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1510 // Do we have a leap year?
1512 $TEST = date('Y', time()) / 4;
1513 $M1 = date("m", time());
1514 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1515 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = $_CONFIG['one_day'];
1516 // First add years...
1517 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1519 $ret += $POST[$prefix."_mo"] * 2628000;
1521 $ret += $POST[$prefix."_we"] * 604800;
1523 $ret += $POST[$prefix."_da"] * 86400;
1525 $ret += $POST[$prefix."_ho"] * 3600;
1527 $ret += $POST[$prefix."_mi"] * 60;
1528 // And at last seconds...
1529 $ret += $POST[$prefix."_se"];
1530 // Return calculated value
1533 // Sends out mail to all administrators
1534 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1535 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1536 // Trim template name
1537 $template = trim($template);
1539 // Load email template
1540 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1542 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1543 // Older version detected!
1544 return SEND_ADMIN_EMAILS($subj, $msg);
1547 // Check which admin shall receive this mail
1548 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1549 array($template), __FILE__, __LINE__);
1550 if (SQL_NUMROWS($result) == 0) {
1551 // Create new entry (to all admins)
1552 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1553 array($template), __FILE__, __LINE__);
1555 // Load admin IDs...
1557 while(list($aid) = SQL_FETCHROW($result)) {
1562 SQL_FREERESULT($result);
1564 // "implode" IDs and query string
1565 $aid = implode(",", $aids);
1567 // Add line to userlog
1568 USERLOG_ADD_LINE($subj, $msg, $UID);
1570 } elseif ($aid == "0") {
1571 // Select all email adresses
1572 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1574 // If Admin-ID is not "to-all" select
1575 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1579 // Load email addresses and send away
1580 while (list($email) = SQL_FETCHROW($result)) {
1581 SEND_EMAIL($email, $subj, $msg);
1585 SQL_FREERESULT($result);
1588 function CREATE_FANCY_TIME($stamp) {
1589 // Get data array with years/months/weeks/days/...
1590 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1592 foreach($data as $k => $v) {
1594 // Value is greater than 0 "eval" data to return string
1595 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1601 // Do we have something there?
1602 if (strlen($ret) > 0) {
1603 // Remove leading commata and space
1604 $ret = substr($ret, 2);
1607 $ret = "0 "._SECONDS;
1610 // Return fancy time string
1614 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1615 $SEP = ""; $TOP = "";
1618 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1622 for ($page = 1; $page <= $PAGES; $page++) {
1623 // Is the page currently selected or shall we generate a link to it?
1624 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1625 // Is currently selected, so only highlight it
1626 $NAV .= "<STRONG>-";
1628 // Open anchor tag and add base URL
1629 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1631 // Add userid when we shall show all mails from a single member
1632 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1634 // Close open anchor tag
1638 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1639 // Is currently selected, so only highlight it
1640 $NAV .= "-</STRONG>";
1646 // Add seperator if we have not yet reached total pages
1647 if ($page < $PAGES) $NAV .= " | ";
1650 // Define constants only once
1651 if (!defined('__NAV_OUTPUT')) {
1652 define('__NAV_OUTPUT' , $NAV);
1653 define('__NAV_COLSPAN', $colspan);
1654 define('__NAV_TOP' , $TOP);
1655 define('__NAV_SEP' , $SEP);
1658 // Load navigation template
1659 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1662 // Return generated HTML-Code
1670 // Extract host from script name
1671 function EXTRACT_HOST (&$script) {
1672 // Use default SERVER_URL by default... ;) So?
1675 // Is this URL valid?
1676 if (substr($script, 0, 7) == "http://") {
1677 // Use the hostname from script URL as new hostname
1678 $url = substr($script, 7);
1679 $extract = explode("/", $url);
1681 // Done extracting the URL :)
1684 // Extract host name
1685 $host = str_replace("http://", "", $url);
1686 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1688 // Generate relative URL
1689 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1690 if (substr(strtolower($script), 0, 7) == "http://") {
1691 // But only if http:// is in front!
1692 $script = substr($script, (strlen($url) + 7));
1693 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1695 $script = substr($script, (strlen($url) + 8));
1698 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1699 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1705 // Send a GET request
1706 function GET_URL ($script) {
1707 // Compile the script name
1708 $script = COMPILE_CODE($script);
1710 // Extract host name from script
1711 $host = EXTRACT_HOST($script);
1713 // Generate GET request header
1714 $request = "GET /" . 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: text/plain\r\n";
1719 $request .= "Cache-Control: no-cache\r\n";
1720 $request .= "Connection: Close\r\n\r\n";
1722 // Send the raw request
1723 $response = SEND_RAW_REQUEST($host, $request);
1725 // Return the result to the caller function
1729 // Send a POST request
1730 function POST_URL ($script, $postData) {
1731 // Is postData an array?
1732 if (!is_array($postData)) {
1734 return array("", "", "");
1737 // Compile the script name
1738 $script = COMPILE_CODE($script);
1740 // Extract host name from script
1741 $host = EXTRACT_HOST($script);
1743 // Construct request
1744 $data = http_build_query($postData, '','&');
1746 // Generate POST request header
1747 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1748 $request .= "Host: " . $host . "\r\n";
1749 $request .= "Referer: " . URL . "/admin.php\r\n";
1750 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1751 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1752 $request .= "Content-length: " . strlen($data) . "\r\n";
1753 $request .= "Cache-Control: no-cache\r\n";
1754 $request .= "Connection: Close\r\n\r\n";
1757 // Send the raw request
1758 $response = SEND_RAW_REQUEST($host, $request);
1760 // Return the result to the caller function
1764 // Sends a raw request to another host
1765 function SEND_RAW_REQUEST ($host, $request) {
1769 $response = array("", "", "");
1771 // Default is not to use proxy
1774 // Are proxy settins set?
1775 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1781 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1783 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1785 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1789 if (!is_resource($fp)) {
1796 // Generate CONNECT request header
1797 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1798 $proxyTunnel .= "Host: ".$host."\r\n";
1800 // Use login data to proxy? (username at least!)
1801 if (!empty($_CONFIG['proxy_username'])) {
1803 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1804 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1807 // Add last new-line
1808 $proxyTunnel .= "\r\n";
1809 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1812 fputs($fp, $proxyTunnel);
1816 // No response received
1820 // Read the first line
1821 $resp = trim(fgets($fp, 10240));
1822 $respArray = explode(" ", $resp);
1823 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1824 // Invalid response!
1830 fputs($fp, $request);
1834 $response[] = trim(fgets($fp, 1024));
1840 // Skip first empty lines
1842 foreach ($resp as $idx => $line) {
1844 $line = trim($line);
1846 // Is this line empty?
1849 array_shift($response);
1851 // Abort on first non-empty line
1856 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1858 // Proxy agent found?
1859 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1860 // Proxy header detected, so remove two lines
1861 array_shift($response);
1862 array_shift($response);
1865 // Was the request successfull?
1866 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1867 // Not found / access forbidden
1868 $response = array("", "", "");
1874 // Taken from www.php.net eregi() user comments
1875 function VALIDATE_EMAIL($email) {
1877 $email = COMPILE_CODE($email);
1879 // Check first part of email address
1880 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1883 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1886 $regex = "^".$first."@".$domain."$";
1888 // Return check result
1889 return eregi($regex, $email);
1891 // Function taken from user comments on www.php.net / function eregi()
1892 function VALIDATE_URL ($URL, $compile=true) {
1893 // Trim URL a little
1894 $URL = trim(urldecode($URL));
1895 //* DEBUG: */ echo $URL."<br />";
1897 // Compile some chars out...
1898 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1899 //* DEBUG: */ echo $URL."<br />";
1901 // Check for the extension filter
1902 if (EXT_IS_ACTIVE("filter")) {
1903 // Use the extension's filter set
1904 return FILTER_VALIDATE_URL($URL, false);
1907 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1908 // https:// in front of the URLs
1909 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1912 function MEMBER_ACTION_LINKS($uid, $status="") {
1913 // Define all main targets
1914 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1916 // Begin of navigation links
1917 $eval = "\$OUT = \"[ ";
1919 foreach ($TARGETS as $tar) {
1920 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1921 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1922 if (($tar == "lock_user") && ($status == "LOCKED")) {
1923 // Locked accounts shall be unlocked
1924 $eval .= "UNLOCK_USER";
1926 // All other status is fine
1927 $eval .= strtoupper($tar);
1929 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1930 if (($tar == "lock_user") && ($status == "LOCKED")) {
1931 // Locked accounts shall be unlocked
1932 $eval .= "UNLOCK_USER";
1934 // All other status is fine
1935 $eval .= strtoupper($tar);
1937 $eval .= ".\"</A></SPAN> | ";
1940 // Finish navigation link
1941 $eval = substr($eval, 0, -7)."]\";";
1947 // Function for backward-compatiblity
1948 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1949 // Load it from the register extension
1950 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1952 // Generate an email link
1953 function CREATE_EMAIL_LINK($email, $table="admins") {
1954 // Default email link (INSECURE! Spammer can read this by harvester programs)
1955 $EMAIL = "mailto:".$email;
1957 // Check for several extensions
1958 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1959 // Create email link for contacting admin in guest area
1960 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1961 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1962 // Create email link for contacting a member within admin area (or later in other areas, too?)
1963 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1964 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1965 // Create email link to contact sponsor within admin area (or like the link above?)
1966 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1969 // Shall I close the link when there is no admin?
1970 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1972 // Return email link
1975 // Generate a hash for extra-security for all passwords
1976 function generateHash ($plainText, $salt = "") {
1977 global $_CONFIG, $_SERVER;
1979 // Is the required extension "sql_patches" there and a salt is not given?
1980 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
1981 // Extension sql_patches is missing/outdated so we return the plain text
1985 // Do we miss an arry element here?
1986 if (!isset($_CONFIG['file_hash'])) {
1988 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
1989 debug_print_backtrace();
1993 // When the salt is empty build a new one, else use the first x configured characters as the salt
1995 // Build server string
1996 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1999 $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'];
2002 $data = $plainText.":".uniqid(rand(), true).":".time();
2004 // Calculate number for generating the code
2005 $a = time() + _ADD - 1;
2007 // Generate SHA1 sum from modula of number and the prime number
2008 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2009 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2010 $sha1 = scrambleString($sha1);
2011 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2012 //* DEBUG: */ $sha1b = descrambleString($sha1);
2013 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2015 // Generate the password salt string
2016 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
2017 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2020 $salt = substr($salt, 0, $_CONFIG['salt_length']);
2021 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2025 return $salt.sha1($salt.$plainText);
2028 function scrambleString($str) {
2034 // Final check, in case of failture it will return unscrambled string
2035 if (strlen($str) > 40) {
2036 // The string is to long
2038 } elseif (strlen($str) == 40) {
2040 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2042 // Generate new numbers
2043 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2046 // Scramble string here
2047 //* DEBUG: */ echo "***Original=".$str."***<br />";
2048 for ($idx = 0; $idx < strlen($str); $idx++) {
2049 // Get char on scrambled position
2050 $char = substr($str, $scrambleNums[$idx], 1);
2052 // Add it to final output string
2053 $scrambled .= $char;
2056 // Return scrambled string
2057 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2061 function descrambleString($str) {
2063 // Scramble only 40 chars long strings
2064 if (strlen($str) != 40) return $str;
2066 // Load numbers from config
2067 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2070 if (count($scrambleNums) != 40) return $str;
2072 // Begin descrambling
2073 $orig = str_repeat(" ", 40);
2074 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2075 for ($idx = 0; $idx < 40; $idx++) {
2076 $char = substr($str, $idx, 1);
2077 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2080 // Return scrambled string
2081 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2085 function genScrambleString($len) {
2086 // Prepare randomizer and array for the numbers
2087 mt_srand((double) microtime() * 1000000);
2088 $scrambleNumbers = array();
2090 // First we need to setup randomized numbers from 0 to 31
2091 for ($idx = 0; $idx < $len; $idx++) {
2093 $rand = mt_rand(0, ($len -1));
2095 // Check for it by creating more numbers
2096 while (array_key_exists($rand, $scrambleNumbers)) {
2097 $rand = mt_rand(0, ($len -1));
2101 $scrambleNumbers[$rand] = $rand;
2104 // So let's create the string for storing it in database
2105 $scrambleString = implode(":", $scrambleNumbers);
2106 return $scrambleString;
2108 // Append data like session ID or referal ID to the given URL which would
2109 // normally be stored in cookies
2110 function ADD_URL_DATA($URL) {
2114 // Determine URL binder
2116 if (strpos($URL, "?") !== false) $BIND = "&";
2118 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2119 // Cookies are not accepted
2120 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2121 // Cookie found in URL
2122 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2123 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2124 // Not found! So let's set default here
2125 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2128 // Is there already added data? Then change the binder
2129 if (!empty($ADD)) $BIND = "&";
2132 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2133 // Add session from URL
2134 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2136 // Add current session
2137 $ADD .= $BIND."PHPSESSID=".session_id();
2141 // Add all together and return it
2144 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2145 function generatePassString($passHash) {
2148 // Return vanilla password hash
2151 // Is a secret key and master salt already initialized?
2152 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2153 // Only calculate when the secret key is generated
2154 $newHash = ""; $start = 9;
2155 for ($idx = 0; $idx < 10; $idx++) {
2156 $part1 = hexdec(substr($passHash, $start, 4));
2157 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2158 $mod = dechex($idx);
2159 if ($part1 > $part2) {
2160 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2161 } elseif ($part2 > $part1) {
2162 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2164 $mod = substr(round($mod), 0, 4);
2165 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2166 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2171 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2172 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2173 //* DEBUG: */ print($ret."<br />\n");
2176 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2177 $ret = md5($passHash);
2178 //* DEBUG: */ echo "++".$ret."++<br />\n";
2185 // Fix "deleted" cookies
2186 function FIX_DELETED_COOKIES ($cookies) {
2187 // Is this an array with entries?
2188 if ((is_array($cookies)) && (count($cookies) > 0)) {
2189 // Then check all cookies if they are marked as deleted!
2190 foreach ($cookies as $cookieName) {
2191 // Is the cookie set to "deleted"?
2192 if (get_session($cookieName) == "deleted") {
2193 set_session($cookieName, "");
2199 // Output error messages in a fasioned way and die...
2200 function mxchange_die ($msg) {
2203 // Load the message template
2204 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2207 include(PATH."inc/footer.php");
2213 // Display parsing time and number of SQL queries in footer
2214 function DISPLAY_PARSING_TIME_FOOTER() {
2215 global $startTime, $_CONFIG;
2216 $endTime = microtime(true);
2218 // Is the timer started?
2219 if (!isset($GLOBALS['startTime'])) {
2224 // "Explode" both times
2225 $start = explode(" ", $GLOBALS['startTime']);
2226 $end = explode(" ", $endTime);
2227 $runTime = $end[0] - $start[0];
2228 if ($runTime < 0) $runTime = 0;
2229 $runTime = TRANSLATE_COMMA($runTime);
2233 'runtime' => $runTime,
2234 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2235 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2238 // Load the template
2239 LOAD_TEMPLATE("show_timings", false, $content);
2242 // Unset/set session variables
2243 function set_session ($var, $value) {
2246 // Abort in CSS mode here
2247 if ($CSS == 1) return true;
2249 // Trim value and session variable
2250 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2252 // Is the session variable set?
2253 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2254 // Remove the session
2255 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2256 unset($_SESSION[$var]);
2257 return session_unregister($var);
2258 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2260 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2261 $_SESSION[$var] = $value;
2262 return session_register($var);
2263 } elseif (!empty($value)) {
2265 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2266 $_SESSION[$var] = $value;
2270 // Ignored (but valid)
2271 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2275 // Check wether a boolean constant is set
2276 // Taken from user comments in PHP documentation for function constant()
2277 function isBooleanConstantAndTrue($constName) { // : Boolean
2280 // Failed by default
2284 if (isset($constCache[$constName])) {
2286 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2287 $res = $constCache[$constName];
2290 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2291 if (defined($constName)) $res = (constant($constName) === true);
2294 $constCache[$constName] = $res;
2296 //* DEBUG: */ var_dump($res);
2302 // Check wether a session variable is set
2303 function isSessionVariableSet($var) {
2304 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2305 return (isset($_SESSION[$var]));
2307 // Returns wether the value of the session variable or NULL if not set
2308 function get_session($var) {
2311 // Default is not found! ;-)
2314 // Is the variable there or cached values?
2315 if (isset($cacheArray['session'][$var])) {
2316 // Get cached value (skips a lot SQL_ESCAPE() calles!
2317 $value = $cacheArray['session'][$var];
2318 } elseif (isSessionVariableSet($var)) {
2319 // Then get it secured!
2320 $value = SQL_ESCAPE($_SESSION[$var]);
2323 $cacheArray['session'][$var] = $value;
2329 // Send notification to admin
2330 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2331 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2333 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2335 // Send outdated way
2336 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2337 SEND_ADMIN_EMAILS($subject, $msg);
2340 // Destroy user session
2341 function destroy_user_session () {
2342 // Remove all user data from session
2343 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2345 // Merges an array together but only if both are arrays
2346 function merge_array ($array1, $array2) {
2347 // Are both an array?
2348 if ((is_array($array1)) && (is_array($array2))) {
2349 // Merge all together
2350 return array_merge($array1, $array2);
2351 } elseif (is_array($array1)) {
2352 // Return left array
2356 // Something wired happened here...
2357 print(__FUNCTION__.":<pre>");
2358 debug_print_backtrace();
2361 // Debug message logger
2362 function DEBUG_LOG ($message, $force=false) {
2363 // Is debug mode enabled?
2364 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2365 // Log this message away
2366 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2367 fwrite($fp, date("d.m.Y|H:i:s", time())."|".strip_tags($message)."\n");
2371 // Reads a directory with PHP files in and gets only files back
2372 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2376 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2379 while ($baseFile = readdir($dirPointer)) {
2380 // Load file only if extension is active
2382 $file = $baseDir.$baseFile;
2384 // Is this a valid reset file?
2385 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2386 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2387 // Remove both for extension name
2388 $extName = substr($baseFile, strlen($prefix), -4);
2391 $extId = GET_EXT_ID($extName);
2393 // Is the extension valid and active?
2394 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2395 // Then add this file
2397 } elseif ($extId == 0) {
2398 // Add non-extension files as well
2405 closedir($dirPointer);
2410 // Return array with include files
2413 // Load more reset scripts
2414 function RESET_ADD_INCLUDES () {
2417 // Is the reset set or old sql_patches?
2418 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2423 // Get more daily reset scripts
2424 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2427 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2429 // Create current week mark
2430 $currWeek = date("W", time());
2433 if ($_CONFIG['last_week'] != $currWeek) {
2434 // Include weekly reset scripts
2435 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2438 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2441 // Create current month mark
2442 $currMonth = date("m", time());
2445 if ($_CONFIG['last_month'] != $currMonth) {
2446 // Include monthly reset scripts
2447 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2450 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2456 // Handle extra values
2457 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2458 // Default is the value itself
2461 // Do we have a special filter function?
2462 if (!empty($filterFunction)) {
2463 // Does the filter function exist?
2464 if (function_exists($filterFunction)) {
2465 // Do we have extra parameters here?
2466 if (!empty($extraValue)) {
2467 // Put both parameters in one new array by default
2468 $args = array($value, $extraValue);
2470 // If we have an array simply use it and pre-extend it with our value
2471 if (is_array($extraValue)) {
2472 // Make the new args array
2473 $args = array_merge(array($value), $extraValue);
2476 // Call the multi-parameter call-back
2477 $ret = call_user_func_array($filterFunction, $args);
2479 // One parameter call
2480 $ret = call_user_func($filterFunction, $value);
2488 // Check if given FQFN is a readable file
2489 function FILE_READABLE($fqfn) {
2491 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2493 // Converts timestamp selections into a timestamp
2494 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2495 // Init test variable
2498 // Get last three chars
2499 $TEST = substr($id, -3);
2501 // Improved way of checking! :-)
2502 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2503 // Found a multi-selection for timings?
2504 $TEST = substr($id, 0, -3);
2505 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)) {
2506 // Generate timestamp
2507 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2508 $DATA[] = "$TEST='".$POST[$TEST]."'";
2510 // Remove data from array
2511 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2512 unset($POST[$TEST."_".$rem]);
2516 unset($id); $skip = true; $TEST2 = $TEST;
2519 // Process this entry
2520 $skip = false; $TEST2 = "";
2523 // Reverts the german decimal comma into Computer decimal dot
2524 function REVERT_COMMA ($str) {
2525 // Default float is not a float... ;-)
2528 // Which language is selected?
2529 switch (GET_LANGUAGE()) {
2530 case "de": // German language
2531 // Remove german thousand dots first
2532 $str = str_replace(".", "", $str);
2534 // Replace german commata with decimal dot and cast it
2535 $float = (float)str_replace(",", ".", $str);
2538 default: // US and so on
2539 // Remove thousand dots first and cast
2540 $float = (float)str_replace(",", "", $str);
2547 // Handle menu-depending failed logins and return the rendered content
2548 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2549 // Default output is empty ;-)
2552 // Is the session data set?
2553 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2554 // Ignore zero values
2555 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2556 // Non-guest has login failtures found, get both data and prepare it for template
2557 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2559 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2560 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2564 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2567 // Reset session data
2568 set_session('mxchange_'.$accessLevel.'_failtures', "");
2569 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2572 // Return rendered content
2576 function REBUILD_CACHE ($cache, $inc="") {
2577 global $cacheInstance, $_CONFIG, $CSS;
2579 // Shall I remove the cache file?
2580 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2582 if ($cacheInstance->cache_file($cache, true)) {
2584 $cacheInstance->cache_destroy();
2587 // Include file given?
2590 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2592 // Is the include there?
2593 if (FILE_READABLE($fqfn)) {
2594 // And rebuild it from scratch
2597 // Include not found!
2598 DEBUG_LOG(__FUNCTION__.":Include {$inc} not found. cache={$cache}");
2603 // Purge admin menu cache
2604 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2605 global $_CONFIG, $cacheInstance;
2607 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2608 if (!EXT_IS_ACTIVE("cache")) {
2609 // Cache extension not active
2611 } elseif (!is_object($cacheInstance)) {
2612 // No cache instance!
2613 DEBUG_LOG(__FUNCTION__.": No cache instance found.");
2615 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2616 // Caching disabled (currently experiemental!)
2620 // Experiemental feature!
2621 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2623 // Translates the "pool type" into human-readable
2624 function TRANSLATE_POOL_TYPE ($type) {
2625 // Default type is unknown
2626 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2628 // Generate constant
2629 $constName = sprintf("POOL_TYPE_%s", $type);
2632 if (defined($constName)) {
2634 $translated = constant($constName);
2637 // Return "translation"
2640 // "Getter" for remote IP number
2641 function GET_REMOTE_ADDR () {
2642 // Get remote ip from environment
2643 $remoteAddr = getenv('REMOTE_ADDR');
2645 // Is removeip installed?
2646 if (EXT_IS_ACTIVE("removeip")) {
2647 // Then anonymize it
2648 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2654 // "Getter" for remote hostname
2655 function GET_REMOTE_HOST () {
2656 // Get remote ip from environment
2657 $remoteHost = getenv('REMOTE_HOST');
2659 // Is removeip installed?
2660 if (EXT_IS_ACTIVE("removeip")) {
2661 // Then anonymize it
2662 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2668 // "Getter" for user agent
2669 function GET_USER_AGENT () {
2670 // Get remote ip from environment
2671 $userAgent = getenv('HTTP_USER_AGENT');
2673 // Is removeip installed?
2674 if (EXT_IS_ACTIVE("removeip")) {
2675 // Then anonymize it
2676 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2682 // "Getter" for referer
2683 function GET_REFERER () {
2684 // Get remote ip from environment
2685 $referer = getenv('HTTP_REFERER');
2687 // Is removeip installed?
2688 if (EXT_IS_ACTIVE("removeip")) {
2689 // Then anonymize it
2690 $referer = GET_ANONYMOUS_REFERER($referer);
2697 // Adds a bonus mail to the queue
2698 // This is a high-level function!
2699 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2700 // Use mode from data if not set and availble ;-)
2701 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2703 // Generate receiver list
2704 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2707 if (!empty($RECEIVER)) {
2708 // Add bonus mail to queue
2709 ADD_BONUS_MAIL_TO_QUEUE(
2721 // Mail inserted into bonus pool
2722 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_BONUS_SEND);
2723 } elseif ($output) {
2724 // More entered than can be reached!
2725 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_MORE_SELECTED);
2728 DEBUG_LOG(__FUNCTION__."(".__LINE__."): cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2732 //////////////////////////////////////////////////
2734 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2736 //////////////////////////////////////////////////
2738 if (!function_exists('html_entity_decode')) {
2739 // Taken from documentation on www.php.net
2740 function html_entity_decode($string) {
2741 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2742 $trans_tbl = array_flip($trans_tbl);
2743 return strtr($string, $trans_tbl);