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 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", OUTPUT_MODE));
136 MXCHANGE_DIE("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
139 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
140 // Output cached HTML code
141 $OUTPUT = ob_get_contents();
143 // Clear output buffer for later output
147 header("HTTP/1.1 200");
150 $now = gmdate('D, d M Y H:i:s') . ' GMT';
152 // General headers for no caching
153 header("Expired: " . $now); // RFC2616 - Section 14.21
154 header("Last-Modified: " . $now);
155 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
156 header("Pragma: no-cache"); // HTTP/1.0
157 header("Connection: Close");
159 // Extension "rewrite" installed?
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 // Prepare the content and eval() it...
168 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
171 // Was that eval okay?
172 if (empty($newContent)) {
173 // Something went wrong!
174 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
176 $OUTPUT = $newContent;
179 // Output code here, DO NOT REMOVE! ;-)
181 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
182 // Rewrite links when rewrite extension is active
183 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
184 $OUTPUT = REWRITE_LINKS($OUTPUT);
187 // Compile and run finished rendered HTML code
188 while (strpos($OUTPUT, '{!') > 0) {
189 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
193 // Output code here, DO NOT REMOVE! ;-)
198 // Output the raw HTML code
199 function OUTPUT_RAW ($HTML) {
200 // Output stripped HTML code to avoid broken JavaScript code, etc.
201 echo stripslashes(stripslashes($HTML));
203 // Flush the output if only _OB_CACHING is not "on"
204 if (_OB_CACHING != "on") {
210 // Add a fatal error message to the queue array
211 function ADD_FATAL ($message, $extra="") {
215 // Regular text message to add to $FATAL
218 // $message is text with a mask plus extras to insert into the text
219 $message = sprintf($message, $extra);
223 // Log fatal messages away
224 DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
227 // Load a template file and return it's content (only it's name; do not use ' or ")
228 function LOAD_TEMPLATE($template, $return=false, $content=array()) {
229 // Add more variables which you want to use in your template files
230 global $DATA, $_CONFIG, $username;
232 // Make all template names lowercase
233 $template = strtolower($template);
235 // Count the template load
236 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
237 $_CONFIG['num_templates']++;
241 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
243 // @DEPRECATED Try to rewrite the if() condition
244 if ($template == "member_support_form") {
245 // Support request of a member
246 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
247 array($GLOBALS['userid']), __FILE__, __LINE__);
249 // Is content an array?
250 if (is_array($content)) {
252 $content = array_merge($content, SQL_FETCHARRAY($result));
255 $content['gender'] = TRANSLATE_GENDER($content['gender']);
257 // DEPRECATED: Load data in direct variables
258 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
261 $gender = TRANSLATE_GENDER($gender);
262 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
266 SQL_FREERESULT($result);
269 // Generate date/time string
270 $date_time = MAKE_DATETIME(time(), "1");
273 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
276 // Check for admin/guest/member templates
277 if (strpos($template, "admin_") > -1) {
278 // Admin template found
280 } elseif (strpos($template, "guest_") > -1) {
281 // Guest template found
283 } elseif (strpos($template, "member_") > -1) {
284 // Member template found
286 } elseif (strpos($template, "install_") > -1) {
287 // Installation template found
289 } elseif (strpos($template, "ext_") > -1) {
290 // Extension template found
292 } elseif (strpos($template, "la_") > -1) {
293 // "Logical-area" template found
296 // Test for extension
297 $test = substr($template, 0, strpos($template, "_"));
298 if (EXT_IS_ACTIVE($test)) {
299 // Set extra path to extension's name
304 ////////////////////////
305 // Generate file name //
306 ////////////////////////
307 $file = $BASE.$MODE.$template.".tpl";
309 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
310 // Select what depended header/footer template file for admin/guest/member area
311 $file2 = sprintf("%s%s%s_%s.tpl",
315 SQL_ESCAPE($GLOBALS['what'])
319 if (FILE_READABLE($file2)) $file = $file2;
321 // Remove variable from memory
325 // Does the special template exists?
326 if (!FILE_READABLE($file)) {
327 // Reset to default template
328 $file = $BASE.$template.".tpl";
331 // Now does the final template exists?
332 if (FILE_READABLE($file)) {
333 // The local file does exists so we load it. :)
334 $tmpl_file = implode("", file($file));
336 // Replace ' to our own chars to preventing them being quoted
337 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
339 // Do we have to compile the code?
341 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
343 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
346 // Simply return loaded code
350 // Add surrounding HTML comments to help finding bugs faster
351 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
352 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
353 // Only admins shall see this warning or when installation mode is active
354 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
355 (".basename($file).")<br />
358 <pre>".print_r($content, true)."</pre>
360 <pre>".print_r($DATA, true)."</pre>
364 // Remove content and data
368 // Do we have some content to output or return?
370 // Not empty so let's put it out! ;)
372 // Return the HTML code
378 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
379 // Warning, empty output!
380 return "E:".$template."<br />\n";
384 // Send mail out to an email address
385 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
386 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
388 // Compile subject line (for POINTS constant etc.)
389 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
393 if ((!eregi("@", $TO)) && ($TO > 0)) {
394 // Value detected, is the message extension installed?
395 if (EXT_IS_ACTIVE("msg")) {
396 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
399 // Load email address
400 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
401 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
403 // Does the user exist?
404 if (SQL_NUMROWS($result_email)) {
405 // Load email address
406 list($TO) = SQL_FETCHROW($result_email);
413 SQL_FREERESULT($result_email);
415 } elseif ("$TO" == "0") {
419 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
421 // Check for PHPMailer or debug-mode
422 if (!CHECK_PHPMAILER_USAGE()) {
423 // Not in PHPMailer-Mode
425 // Load email header template
426 $FROM = LOAD_EMAIL_TEMPLATE("header");
429 $FROM .= LOAD_EMAIL_TEMPLATE("header");
431 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
433 // Load email header template
434 $FROM = LOAD_EMAIL_TEMPLATE("header");
437 $FROM .= LOAD_EMAIL_TEMPLATE("header");
442 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
446 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
449 // Fix HTML parameter (default is no!)
450 if (empty($HTML)) $HTML = "N";
451 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
452 // In debug mode we want to display the mail instead of sending it away so we can debug this part
454 ".htmlentities(trim($FROM))."
456 Subject : ".$SUBJECT."
461 if (defined('DEBUG_MAIL')) DEBUG_LOG(__FUNCTION__, __LINE__, "to={$TO},subject={$SUBJECT},msg={$MSG}");
462 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
463 // Send mail as HTML away
464 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
465 } elseif (!empty($TO)) {
467 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
468 } elseif ($HTML == "N") {
470 SEND_RAW_EMAIL(WEBMASTER, "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
474 // Check if legacy or PHPMailer command
476 function CHECK_PHPMAILER_USAGE() {
477 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
481 * Send out a raw email with PHPMailer class or legacy mail() command
483 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
484 // Shall we use PHPMailer class or legacy mode?
485 if (CHECK_PHPMAILER_USAGE()) {
486 // Use PHPMailer class with SMTP enabled
487 require_once(PATH."inc/phpmailer/class.phpmailer.php");
488 require_once(PATH."inc/phpmailer/class.smtp.php");
491 $mail = new PHPMailer();
492 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
495 $mail->SMTPAuth = true;
496 $mail->Host = SMTP_HOSTNAME;
498 $mail->Username = SMTP_USER;
499 $mail->Password = SMTP_PASSWORD;
501 $mail->From = WEBMASTER;
505 $mail->FromName = MAIN_TITLE;
506 $mail->Subject = $subject;
507 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
509 $mail->AltBody = "Your mail program required HTML support to read this mail!";
510 $mail->WordWrap = 70;
513 $mail->Body = html_entity_decode($msg);
515 $mail->AddAddress($to, "");
516 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
517 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
518 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
521 // Use legacy mail() command
522 @mail($to, $subject, html_entity_decode($msg), $from);
527 // Generate a password in a specified length or use default password length
528 function GEN_PASS($LEN = 0) {
530 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
532 // Initialize array with all allowed chars
533 $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,-,+,_,/");
535 // Initialize randomizer
536 mt_srand((double) microtime() * 1000000);
538 // Start creating password
540 for ($i = 0; $i < $LEN; $i++) {
541 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
544 // When the size is below 40 we can also add additional security by scrambling it
545 if (strlen($PASS) <= 40) {
546 // Also scramble the password
547 $PASS = scrambleString($PASS);
550 // Return the password
554 function MAKE_DATETIME ($time, $mode="0")
558 return NEVER_HAPPENED;
560 // Filter out numbers
561 $time = bigintval($time);
564 switch (GET_LANGUAGE())
566 case "de": // German date / time format
568 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
569 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
570 case "2": $ret = date("d.m.Y|H:i", $time); break;
571 case "3": $ret = date("d.m.Y", $time); break;
573 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
578 default: // Default is the US date / time format!
580 case "0": $ret = date("r", $time); break;
581 case "1": $ret = date("Y-m-d - g:i A", $time); break;
582 case "2": $ret = date("y-m-d|H:i", $time); break;
583 case "3": $ret = date("y-m-d", $time); break;
585 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
592 // Translates the american decimal dot into a german comma
593 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
596 // Default is 3 you can change this in admin area "Misc -> Misc Options"
597 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
599 // Use from config is default
600 $maxComma = $_CONFIG['max_comma'];
602 // Use from parameter?
603 if ($max > 0) $maxComma = $max;
607 // Test for commata if in cut-mode
608 $com = explode(".", $dotted);
609 if (count($com) > 1) {
610 // Commata found, so only zeros?
611 if ($com[1] == str_repeat("0", strlen($com[1]))) {
612 // Only zeros, so display only one
616 // Don't display commatas even if there are none... ;-)
622 //DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
625 switch (GET_LANGUAGE()) {
627 $dotted = number_format($dotted, $maxComma, ",", ".");
631 $dotted = number_format($dotted, $maxComma, ".", ",");
635 // Return translated value
640 function DEREFERER ($URL) {
641 // Don't de-refer our own links!
642 if (substr($URL, 0, strlen(URL)) != URL) {
643 // De-refer this link
644 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
652 function TRANSLATE_GENDER ($gender) {
655 case "M": $ret = GENDER_M; break;
656 case "F": $ret = GENDER_F; break;
657 case "C": $ret = GENDER_C; break;
658 default : $ret = $gender; break;
663 function FRAMETESTER($URL) {
664 // Prepare frametester URL
665 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
667 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
669 return $frametesterUrl;
672 function SELECTION_COUNT($array) {
674 if (is_array($array)) {
675 foreach ($array as $key => $sel) {
676 if (!empty($sel)) $ret++;
682 function IMG_CODE ($code, $type, $DATA, $uid) {
683 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
686 function TRANSLATE_STATUS($status) {
690 $ret = ACCOUNT_UNCONFIRMED;
694 $ret = ACCOUNT_CONFIRMED;
698 $ret = ACCOUNT_LOCKED;
703 $ret = ACCOUNT_DELETED;
707 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
708 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
714 function GET_LANGUAGE() {
715 if (!empty($_GET['mx_lang'])) {
716 // Accept only first 2 chars
717 $lang = substr($_GET['mx_lang'], 0, 2);
723 // Set default return value to default language from config
726 // Check GET variable and cookie
728 // Check if main language file does exist
729 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
730 // Okay found, so let's update cookies
733 } elseif (!isSessionVariableSet('mx_lang')) {
734 // Return stored value from cookie
735 $ret = get_session('mx_lang');
737 // Fixes a warning before the session has the mx_lang constant
738 if (empty($ret)) $ret = DEFAULT_LANG;
743 function SET_LANGUAGE($lang) {
746 // Accept only first 2 chars!
747 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
750 set_session("mx_lang", $lang);
753 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
754 global $DATA, $_CONFIG, $REPLACER;
756 // Make sure all template names are lowercase!
757 $template = strtolower($template);
759 // Default "nickname" if extension is not installed
762 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
763 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
765 // Prepare IP number and User Agent
766 $REMOTE_ADDR = GET_REMOTE_ADDR();
767 $HTTP_USER_AGENT = GET_USER_AGENT();
772 // Is the admin logged in?
775 $aid = GET_ADMIN_ID(get_session('admin_login'));
778 $ADMIN = GET_ADMIN_EMAIL($aid);
781 // Neutral email address is default
784 // Expiration in a nice output format
785 if ($_CONFIG['auto_purge'] == 0) {
786 // Will never expire!
787 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
788 } elseif (function_exists('CREATE_FANCY_TIME')) {
789 // Create nice date string
790 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
793 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
796 // Is content an array?
797 if (is_array($content)) {
798 // Add expiration to array, $EXPIRATION is now deprecated!
799 $content['expiration'] = $EXPIRATION;
803 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template}<br />\n";
805 if (EXT_IS_ACTIVE("nickname")) {
806 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
808 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
809 array(bigintval($UID)), __FILE__, __LINE__);
811 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
813 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
814 array(bigintval($UID)), __FILE__, __LINE__);
817 // Is content an array?
818 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content[]=".gettype($content)."<br />\n";
819 if (is_array($content)) {
820 // Fetch and migrate data
821 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
822 $content = array_merge($content, SQL_FETCHARRAY($result));
823 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
827 SQL_FREERESULT($result);
830 // Translate M to male or F to female if present
831 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
833 // Overwrite email from data if present
834 if (isset($content['email'])) $email = $content['email'];
836 // Store email for some functions in global data array
837 $DATA['email'] = $email;
840 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
842 // Check for admin/guest/member templates
843 if (strpos($template, "admin_") > -1) {
844 // Admin template found
845 $file = $BASE."admin/".$template.".tpl";
846 } elseif (strpos($template, "guest_") > -1) {
847 // Guest template found
848 $file = $BASE."guest/".$template.".tpl";
849 } elseif (strpos($template, "member_") > -1) {
850 // Member template found
851 $file = $BASE."member/".$template.".tpl";
853 // Test for extension
854 $test = substr($template, 0, strpos($template, "_"));
855 if (EXT_IS_ACTIVE($test)) {
856 // Set extra path to extension's name
857 $file = $BASE.$test."/".$template.".tpl";
859 // No special filename
860 $file = $BASE.$template.".tpl";
864 // Does the special template exists?
865 if (!FILE_READABLE($file)) {
866 // Reset to default template
867 $file = $BASE.$template.".tpl";
870 // Now does the final template exists?
872 if (FILE_READABLE($file)) {
873 // The local file does exists so we load it. :)
874 $tmpl_file = implode("", file($file));
875 $tmpl_file = addslashes($tmpl_file);
878 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
880 } elseif (!empty($template)) {
881 // Template file not found!
882 $newContent = TEMPLATE_404.": ".$template."<br />
884 <pre>".print_r($content, true)."</pre>
886 <pre>".print_r($DATA, true)."</pre>
889 // Debug mode not active? Then remove the HTML tags
890 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
892 // No template name supplied!
893 $newContent = NO_TEMPLATE_SUPPLIED;
896 // Is there some content?
897 if (empty($newContent)) {
899 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
900 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
903 // Remove content and data
907 // Return compiled content
908 return COMPILE_CODE($newContent);
911 function MAKE_TIME($H, $M, $S, $stamp) {
912 // Extract day, month and year from given timestamp
913 $DAY = date("d", $stamp);
914 $MONTH = date("m", $stamp);
915 $YEAR = date('Y', $stamp);
917 // Create timestamp for wished time which depends on extracted date
918 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
921 function LOAD_URL($URL, $addUrlData=true) {
922 global $CSS, $_CONFIG, $footer;
924 // Compile out URI codes
925 $URL = COMPILE_CODE($URL);
927 // Check if http(s):// is there
928 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
929 // Make all URLs full-qualified
934 $OUTPUT = ob_get_contents();
936 // Clear it only if there is content
937 if (!empty($OUTPUT)) {
941 // Add some data to URL if cookies are not accepted
942 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
944 // Probe for bot from search engine
945 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT())) || (eregi("spider", GET_USER_AGENT()))) {
946 // Search engine bot detected so let's rewrite many chars for the link
947 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
949 // Output new location link as anchor
950 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
951 } elseif (!headers_sent()) {
952 // Load URL when headers are not sent
955 debug_print_backtrace();
956 die("</pre>URL={$URL}");
958 @header ("Location: ".str_replace("&", "&", $URL));
960 // Output error message
961 include(PATH."inc/header.php");
962 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
963 include(PATH."inc/footer.php");
968 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
969 global $SEC_CHARS, $URL_CHARS;
970 // Is the code a string?
971 if (!is_string($code)) {
972 // Silently return it
978 // Select smaller set of chars to replace when we e.g. want to compile URLs
979 if (!$full) $ARRAY = $URL_CHARS;
983 // BEFORE 0.2.1 : Language and data constants
984 // WITH 0.2.1+ : Only language constants
985 $code = str_replace('{--','".', str_replace('--}','."', $code));
987 // BEFORE 0.2.1 : Not used
988 // WITH 0.2.1+ : Data constants
989 $code = str_replace('{!','".', str_replace("!}", '."', $code));
992 // Compile QUOT and other non-HTML codes
993 foreach ($ARRAY['to'] as $k => $to) {
994 // Do the reversed thing as in inc/libs/security_functions.php
995 $code = str_replace($to, $ARRAY['from'][$k], $code);
998 // But shall I keep simple quotes for later use?
999 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
1001 // Find $content[bla][blub] entries
1002 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1004 // Are some matches found?
1005 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1006 // Replace all matches
1007 $matchesFound = array();
1008 foreach ($matches[0] as $key => $match) {
1009 // Fuzzy look has failed by default
1010 $fuzzyFound = false;
1012 // Fuzzy look on match if already found
1013 foreach ($matchesFound as $found => $set) {
1015 $test = substr($found, 0, strlen($match));
1017 // Does this entry exist?
1018 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1019 if ($test == $match) {
1021 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1028 if ($fuzzyFound) continue;
1030 // Take all string elements
1031 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1032 // Replace it in the code
1033 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1034 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1035 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1036 $matchesFound[$key."_".$matches[4][$key]] = 1;
1037 $matchesFound[$match] = 1;
1038 } elseif (!isset($matchesFound[$match])) {
1039 // Not yet replaced!
1040 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1041 $code = str_replace($match, "\".".$match.".\"", $code);
1042 $matchesFound[$match] = 1;
1047 // Return compiled code
1051 /************************************************************************
1053 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1054 * $a_sort sortiert: *
1056 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1057 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1058 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1059 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1060 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1062 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1063 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1064 * Sie, dass es doch nicht so schwer ist! :-) *
1066 ************************************************************************/
1067 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1070 while ($primary_key < count($a_sort)) {
1071 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1072 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1075 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1076 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1077 } elseif ($key != $key2) {
1078 // Sort numbers (E.g.: 9 < 10)
1079 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1080 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1084 // We have found two different values, so let's sort whole array
1085 foreach ($dummy as $sort_key => $sort_val) {
1086 $t = $dummy[$sort_key][$key];
1087 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1088 $dummy[$sort_key][$key2] = $t;
1099 // Write back sorted array
1103 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1105 global $MONTH_DESCR; $OUT = "";
1108 // This is a yes/no selection only!
1109 if ($id > 0) $prefix .= "[".$id."]";
1110 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1114 // Begin with regular selection box here
1115 if (!empty($prefix)) $prefix .= "_";
1117 if ($id > 0) $type2 .= "[".$id."]";
1118 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1123 for ($idx = 1; $idx < 32; $idx++)
1125 $OUT .= "<OPTION value=\"".$idx."\"";
1126 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1127 $OUT .= ">".$idx."</OPTION>\n";
1131 case "month": // Month
1132 foreach ($MONTH_DESCR as $month => $descr)
1134 $OUT .= "<OPTION value=\"".$month."\"";
1135 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1136 $OUT .= ">".$descr."</OPTION>\n";
1140 case "year": // Year
1142 $YEAR = date('Y', time());
1144 // Check if the default value is larger than minimum and bigger than actual year
1145 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1147 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1149 $OUT .= "<OPTION value=\"".$idx."\"";
1150 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1151 $OUT .= ">".$idx."</OPTION>\n";
1154 elseif ($DEFAULT == -1)
1156 // Current year minus 1
1157 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1159 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1164 // Get current year and subtract 16 (for erotic content)
1165 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1166 $YEAR = date('Y', time()) - 16;
1167 for ($idx = 1930; $idx <= $YEAR; $idx++)
1169 $OUT .= "<OPTION value=\"".$idx."\"";
1170 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1171 $OUT .= ">".$idx."</OPTION>\n";
1178 for ($idx = 0; $idx < 60; $idx+=5) {
1179 if (strlen($idx) == 1) $idx = "0".$idx;
1180 $OUT .= "<OPTION value=\"".$idx."\"";
1181 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1182 $OUT .= ">".$idx."</OPTION>\n";
1187 for ($idx = 0; $idx < 24; $idx++) {
1188 if (strlen($idx) == 1) $idx = "0".$idx;
1189 $OUT .= "<OPTION value=\"".$idx."\"";
1190 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1191 $OUT .= ">".$idx."</OPTION>\n";
1196 $OUT .= "<OPTION value=\"Y\"";
1197 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1198 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1199 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1200 $OUT .= ">".NO."</OPTION>\n";
1203 $OUT .= " </SELECT>\n";
1207 function TRANSLATE_YESNO($yn)
1211 case 'Y': $yn = YES; break;
1212 case 'N': $yn = NO; break;
1213 default : $yn = "??? (".$yn.")"; break;
1218 // Deprecated : $length
1221 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1224 // Fix missing _MAX constant
1225 if (!defined('_MAX')) define('_MAX', 15235);
1227 // Build server string
1228 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1231 $keys = SITE_KEY.":".DATE_KEY;
1232 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1233 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1234 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1235 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1237 // Build string from misc data
1238 $data = $code.":".$uid.":".$DATA;
1240 // Add more additional data
1241 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1242 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1243 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1244 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1245 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1246 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1248 // Calculate number for generating the code
1249 $a = $code + _ADD - 1;
1251 if (isset($_CONFIG['master_hash'])) {
1252 // Generate hash with master salt from modula of number with the prime number and other data
1253 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1255 // Create number from hash
1256 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1258 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1259 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1261 // Create number from hash
1262 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1265 // At least 10 numbers shall be secure enought!
1266 $len = $_CONFIG['code_length'];
1267 if ($len == 0) $len = $length;
1268 if ($len == 0) $len = 10;
1270 // Cut off requested counts of number
1271 $return = substr(str_replace('.', "", $rcode), 0, $len);
1273 // Done building code
1276 // Does only allow numbers
1277 function bigintval($num, $castValue = true) {
1278 // Filter all numbers out
1279 $ret = preg_replace("/[^0123456789]/", "", $num);
1282 if ($castValue) $ret = (double)$ret;
1284 // Has the whole value changed?
1285 if ("".$ret."" != "".$num."") {
1288 debug_print_backtrace();
1290 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1296 // Insert the code in $img_code into jpeg or PNG image
1297 function GENERATE_IMAGE($img_code, $header=true) {
1300 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1301 // Stop execution of function here because of over-sized code length
1303 } elseif (!$header) {
1304 // Return in an HTML code code
1305 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1309 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1310 if (FILE_READABLE($img)) {
1311 // Switch image type
1312 switch ($_CONFIG['img_type'])
1315 // Okay, load image and hide all errors
1316 $image = @imagecreatefromjpeg($img);
1320 // Okay, load image and hide all errors
1321 $image = @imagecreatefrompng($img);
1325 // Exit function here
1329 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1330 $text_color = imagecolorallocate($image, 0, 0, 0);
1332 // Insert code into image
1333 imagestring($image, 5, 14, 2, $img_code, $text_color);
1335 // Return to browser
1336 header ("Content-Type: image/".$_CONFIG['img_type']);
1338 // Output image with matching image factory
1339 switch ($_CONFIG['img_type']) {
1340 case "jpg": imagejpeg($image); break;
1341 case "png": imagepng($image); break;
1344 // Remove image from memory
1345 imagedestroy($image);
1347 // Create selection box or array of splitted timestamp
1348 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1351 // Calculate 2-seconds timestamp
1352 $stamp = round($timestamp);
1354 // Do we have a leap year?
1356 $TEST = date('Y', time()) / 4;
1357 $M1 = date("m", time());
1358 $M2 = date("m", (time() + $stamp));
1360 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1361 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = $_CONFIG['one_day'];
1363 // First of all years...
1364 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1366 $M = abs(floor($stamp / 2628000 - $Y * 12));
1368 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / $_CONFIG['one_day']) / 7) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day']) / 7)));
1370 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / $_CONFIG['one_day']) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day'])) - $W * 7));
1372 $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));
1374 $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));
1375 // And at last seconds...
1376 $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));
1378 // Is seconds zero and time is < 60 seconds?
1379 if (($s == 0) && ($stamp < 60)) {
1381 $s = round($timestamp);
1385 // Now we convert them in seconds...
1387 if ($return_array) {
1388 // Just put all data in an array for later use
1400 $OUT = "<DIV align=\"".$align."\">\n";
1401 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1404 if (ereg('Y', $display) || (empty($display))) {
1405 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1408 if (ereg("M", $display) || (empty($display))) {
1409 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1412 if (ereg("W", $display) || (empty($display))) {
1413 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1416 if (ereg("D", $display) || (empty($display))) {
1417 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1420 if (ereg("h", $display) || (empty($display))) {
1421 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1424 if (ereg("m", $display) || (empty($display))) {
1425 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1428 if (ereg("s", $display) || (empty($display))) {
1429 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1435 if (ereg('Y', $display) || (empty($display))) {
1436 // Generate year selection
1437 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1438 for ($idx = 0; $idx <= 10; $idx++) {
1439 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1440 if ($idx == $Y) $OUT .= " selected default";
1441 $OUT .= ">".$idx."</OPTION>\n";
1443 $OUT .= " </SELECT></TD>\n";
1445 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1448 if (ereg("M", $display) || (empty($display))) {
1449 // Generate month selection
1450 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1451 for ($idx = 0; $idx <= 11; $idx++)
1453 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1454 if ($idx == $M) $OUT .= " selected default";
1455 $OUT .= ">".$idx."</OPTION>\n";
1457 $OUT .= " </SELECT></TD>\n";
1459 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1462 if (ereg("W", $display) || (empty($display))) {
1463 // Generate week selection
1464 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1465 for ($idx = 0; $idx <= 4; $idx++) {
1466 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1467 if ($idx == $W) $OUT .= " selected default";
1468 $OUT .= ">".$idx."</OPTION>\n";
1470 $OUT .= " </SELECT></TD>\n";
1472 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1475 if (ereg("D", $display) || (empty($display))) {
1476 // Generate day selection
1477 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1478 for ($idx = 0; $idx <= 31; $idx++) {
1479 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1480 if ($idx == $D) $OUT .= " selected default";
1481 $OUT .= ">".$idx."</OPTION>\n";
1483 $OUT .= " </SELECT></TD>\n";
1485 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1488 if (ereg("h", $display) || (empty($display))) {
1489 // Generate hour selection
1490 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1491 for ($idx = 0; $idx <= 23; $idx++) {
1492 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1493 if ($idx == $h) $OUT .= " selected default";
1494 $OUT .= ">".$idx."</OPTION>\n";
1496 $OUT .= " </SELECT></TD>\n";
1498 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1501 if (ereg("m", $display) || (empty($display))) {
1502 // Generate minute selection
1503 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1504 for ($idx = 0; $idx <= 59; $idx++) {
1505 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1506 if ($idx == $m) $OUT .= " selected default";
1507 $OUT .= ">".$idx."</OPTION>\n";
1509 $OUT .= " </SELECT></TD>\n";
1511 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1514 if (ereg("s", $display) || (empty($display))) {
1515 // Generate second selection
1516 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1517 for ($idx = 0; $idx <= 45; $idx += 15) {
1518 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1519 if ($idx == $s) $OUT .= " selected default";
1520 $OUT .= ">".$idx."</OPTION>\n";
1522 $OUT .= " </SELECT></TD>\n";
1524 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1527 $OUT .= "</TABLE>\n";
1529 // Return generated HTML code
1534 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1538 // Do we have a leap year?
1540 $TEST = date('Y', time()) / 4;
1541 $M1 = date("m", time());
1542 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1543 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = $_CONFIG['one_day'];
1544 // First add years...
1545 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1547 $ret += $POST[$prefix."_mo"] * 2628000;
1549 $ret += $POST[$prefix."_we"] * 604800;
1551 $ret += $POST[$prefix."_da"] * 86400;
1553 $ret += $POST[$prefix."_ho"] * 3600;
1555 $ret += $POST[$prefix."_mi"] * 60;
1556 // And at last seconds...
1557 $ret += $POST[$prefix."_se"];
1558 // Return calculated value
1561 // Sends out mail to all administrators
1562 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1563 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1564 // Trim template name
1565 $template = trim($template);
1567 // Load email template
1568 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1570 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1571 // Older version detected!
1572 return SEND_ADMIN_EMAILS($subj, $msg);
1575 // Check which admin shall receive this mail
1576 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1577 array($template), __FILE__, __LINE__);
1578 if (SQL_NUMROWS($result) == 0) {
1579 // Create new entry (to all admins)
1580 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1581 array($template), __FILE__, __LINE__);
1583 // Load admin IDs...
1585 while(list($aid) = SQL_FETCHROW($result)) {
1590 SQL_FREERESULT($result);
1592 // "implode" IDs and query string
1593 $aid = implode(",", $aids);
1595 // Add line to userlog
1596 USERLOG_ADD_LINE($subj, $msg, $UID);
1598 } elseif ($aid == "0") {
1599 // Select all email adresses
1600 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1602 // If Admin-ID is not "to-all" select
1603 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1607 // Load email addresses and send away
1608 while (list($email) = SQL_FETCHROW($result)) {
1609 SEND_EMAIL($email, $subj, $msg);
1613 SQL_FREERESULT($result);
1616 function CREATE_FANCY_TIME($stamp) {
1617 // Get data array with years/months/weeks/days/...
1618 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1620 foreach($data as $k => $v) {
1622 // Value is greater than 0 "eval" data to return string
1623 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1629 // Do we have something there?
1630 if (strlen($ret) > 0) {
1631 // Remove leading commata and space
1632 $ret = substr($ret, 2);
1635 $ret = "0 "._SECONDS;
1638 // Return fancy time string
1642 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1643 $SEP = ""; $TOP = "";
1646 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1650 for ($page = 1; $page <= $PAGES; $page++) {
1651 // Is the page currently selected or shall we generate a link to it?
1652 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1653 // Is currently selected, so only highlight it
1654 $NAV .= "<STRONG>-";
1656 // Open anchor tag and add base URL
1657 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1659 // Add userid when we shall show all mails from a single member
1660 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1662 // Close open anchor tag
1666 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1667 // Is currently selected, so only highlight it
1668 $NAV .= "-</STRONG>";
1674 // Add seperator if we have not yet reached total pages
1675 if ($page < $PAGES) $NAV .= " | ";
1678 // Define constants only once
1679 if (!defined('__NAV_OUTPUT')) {
1680 define('__NAV_OUTPUT' , $NAV);
1681 define('__NAV_COLSPAN', $colspan);
1682 define('__NAV_TOP' , $TOP);
1683 define('__NAV_SEP' , $SEP);
1686 // Load navigation template
1687 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1690 // Return generated HTML-Code
1698 // Extract host from script name
1699 function EXTRACT_HOST (&$script) {
1700 // Use default SERVER_URL by default... ;) So?
1703 // Is this URL valid?
1704 if (substr($script, 0, 7) == "http://") {
1705 // Use the hostname from script URL as new hostname
1706 $url = substr($script, 7);
1707 $extract = explode("/", $url);
1709 // Done extracting the URL :)
1712 // Extract host name
1713 $host = str_replace("http://", "", $url);
1714 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1716 // Generate relative URL
1717 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1718 if (substr(strtolower($script), 0, 7) == "http://") {
1719 // But only if http:// is in front!
1720 $script = substr($script, (strlen($url) + 7));
1721 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1723 $script = substr($script, (strlen($url) + 8));
1726 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1727 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1733 // Send a GET request
1734 function GET_URL ($script) {
1735 // Compile the script name
1736 $script = COMPILE_CODE($script);
1738 // Extract host name from script
1739 $host = EXTRACT_HOST($script);
1741 // Generate GET request header
1742 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1743 $request .= "Host: " . $host . "\r\n";
1744 $request .= "Referer: " . URL . "/admin.php\r\n";
1745 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1746 $request .= "Content-Type: text/plain\r\n";
1747 $request .= "Cache-Control: no-cache\r\n";
1748 $request .= "Connection: Close\r\n\r\n";
1750 // Send the raw request
1751 $response = SEND_RAW_REQUEST($host, $request);
1753 // Return the result to the caller function
1757 // Send a POST request
1758 function POST_URL ($script, $postData) {
1759 // Is postData an array?
1760 if (!is_array($postData)) {
1762 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1763 return array("", "", "");
1766 // Compile the script name
1767 $script = COMPILE_CODE($script);
1769 // Extract host name from script
1770 $host = EXTRACT_HOST($script);
1772 // Construct request
1773 $data = http_build_query($postData, '','&');
1775 // Generate POST request header
1776 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1777 $request .= "Host: " . $host . "\r\n";
1778 $request .= "Referer: " . URL . "/admin.php\r\n";
1779 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1780 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1781 $request .= "Content-length: " . strlen($data) . "\r\n";
1782 $request .= "Cache-Control: no-cache\r\n";
1783 $request .= "Connection: Close\r\n\r\n";
1786 // Send the raw request
1787 $response = SEND_RAW_REQUEST($host, $request);
1789 // Return the result to the caller function
1793 // Sends a raw request to another host
1794 function SEND_RAW_REQUEST ($host, $request) {
1798 $response = array("", "", "");
1800 // Default is not to use proxy
1803 // Are proxy settins set?
1804 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1810 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1812 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1814 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1818 if (!is_resource($fp)) {
1825 // Generate CONNECT request header
1826 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1827 $proxyTunnel .= "Host: ".$host."\r\n";
1829 // Use login data to proxy? (username at least!)
1830 if (!empty($_CONFIG['proxy_username'])) {
1832 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1833 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1836 // Add last new-line
1837 $proxyTunnel .= "\r\n";
1838 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1841 fputs($fp, $proxyTunnel);
1845 // No response received
1849 // Read the first line
1850 $resp = trim(fgets($fp, 10240));
1851 $respArray = explode(" ", $resp);
1852 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1853 // Invalid response!
1859 fputs($fp, $request);
1863 $response[] = trim(fgets($fp, 1024));
1869 // Skip first empty lines
1871 foreach ($resp as $idx => $line) {
1873 $line = trim($line);
1875 // Is this line empty?
1878 array_shift($response);
1880 // Abort on first non-empty line
1885 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1887 // Proxy agent found?
1888 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1889 // Proxy header detected, so remove two lines
1890 array_shift($response);
1891 array_shift($response);
1894 // Was the request successfull?
1895 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1896 // Not found / access forbidden
1897 $response = array("", "", "");
1903 // Taken from www.php.net eregi() user comments
1904 function VALIDATE_EMAIL($email) {
1906 $email = COMPILE_CODE($email);
1908 // Check first part of email address
1909 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1912 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1915 $regex = "^".$first."@".$domain."$";
1917 // Return check result
1918 return eregi($regex, $email);
1920 // Function taken from user comments on www.php.net / function eregi()
1921 function VALIDATE_URL ($URL, $compile=true) {
1922 // Trim URL a little
1923 $URL = trim(urldecode($URL));
1924 //* DEBUG: */ echo $URL."<br />";
1926 // Compile some chars out...
1927 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1928 //* DEBUG: */ echo $URL."<br />";
1930 // Check for the extension filter
1931 if (EXT_IS_ACTIVE("filter")) {
1932 // Use the extension's filter set
1933 return FILTER_VALIDATE_URL($URL, false);
1936 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1937 // https:// in front of the URLs
1938 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1941 function MEMBER_ACTION_LINKS($uid, $status="") {
1942 // Define all main targets
1943 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1945 // Begin of navigation links
1946 $eval = "\$OUT = \"[ ";
1948 foreach ($TARGETS as $tar) {
1949 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1950 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1951 if (($tar == "lock_user") && ($status == "LOCKED")) {
1952 // Locked accounts shall be unlocked
1953 $eval .= "UNLOCK_USER";
1955 // All other status is fine
1956 $eval .= strtoupper($tar);
1958 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1959 if (($tar == "lock_user") && ($status == "LOCKED")) {
1960 // Locked accounts shall be unlocked
1961 $eval .= "UNLOCK_USER";
1963 // All other status is fine
1964 $eval .= strtoupper($tar);
1966 $eval .= ".\"</A></SPAN> | ";
1969 // Finish navigation link
1970 $eval = substr($eval, 0, -7)."]\";";
1976 // Function for backward-compatiblity
1977 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1978 // Load it from the register extension
1979 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1981 // Generate an email link
1982 function CREATE_EMAIL_LINK($email, $table="admins") {
1983 // Default email link (INSECURE! Spammer can read this by harvester programs)
1984 $EMAIL = "mailto:".$email;
1986 // Check for several extensions
1987 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1988 // Create email link for contacting admin in guest area
1989 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1990 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1991 // Create email link for contacting a member within admin area (or later in other areas, too?)
1992 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1993 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1994 // Create email link to contact sponsor within admin area (or like the link above?)
1995 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1998 // Shall I close the link when there is no admin?
1999 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2001 // Return email link
2004 // Generate a hash for extra-security for all passwords
2005 function generateHash ($plainText, $salt = "") {
2006 global $_CONFIG, $_SERVER;
2008 // Is the required extension "sql_patches" there and a salt is not given?
2009 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2010 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2011 return md5($plainText);
2014 // Do we miss an arry element here?
2015 if (!isset($_CONFIG['file_hash'])) {
2017 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2018 debug_print_backtrace();
2022 // When the salt is empty build a new one, else use the first x configured characters as the salt
2024 // Build server string
2025 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2028 $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'];
2031 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2033 // Calculate number for generating the code
2034 $a = time() + _ADD - 1;
2036 // Generate SHA1 sum from modula of number and the prime number
2037 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2038 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2039 $sha1 = scrambleString($sha1);
2040 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2041 //* DEBUG: */ $sha1b = descrambleString($sha1);
2042 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2044 // Generate the password salt string
2045 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
2046 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2049 $salt = substr($salt, 0, $_CONFIG['salt_length']);
2050 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2054 return $salt.sha1($salt.$plainText);
2057 function scrambleString($str) {
2063 // Final check, in case of failture it will return unscrambled string
2064 if (strlen($str) > 40) {
2065 // The string is to long
2067 } elseif (strlen($str) == 40) {
2069 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2071 // Generate new numbers
2072 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2075 // Scramble string here
2076 //* DEBUG: */ echo "***Original=".$str."***<br />";
2077 for ($idx = 0; $idx < strlen($str); $idx++) {
2078 // Get char on scrambled position
2079 $char = substr($str, $scrambleNums[$idx], 1);
2081 // Add it to final output string
2082 $scrambled .= $char;
2085 // Return scrambled string
2086 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2090 function descrambleString($str) {
2092 // Scramble only 40 chars long strings
2093 if (strlen($str) != 40) return $str;
2095 // Load numbers from config
2096 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2099 if (count($scrambleNums) != 40) return $str;
2101 // Begin descrambling
2102 $orig = str_repeat(" ", 40);
2103 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2104 for ($idx = 0; $idx < 40; $idx++) {
2105 $char = substr($str, $idx, 1);
2106 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2109 // Return scrambled string
2110 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2114 function genScrambleString($len) {
2115 // Prepare randomizer and array for the numbers
2116 mt_srand((double) microtime() * 1000000);
2117 $scrambleNumbers = array();
2119 // First we need to setup randomized numbers from 0 to 31
2120 for ($idx = 0; $idx < $len; $idx++) {
2122 $rand = mt_rand(0, ($len -1));
2124 // Check for it by creating more numbers
2125 while (array_key_exists($rand, $scrambleNumbers)) {
2126 $rand = mt_rand(0, ($len -1));
2130 $scrambleNumbers[$rand] = $rand;
2133 // So let's create the string for storing it in database
2134 $scrambleString = implode(":", $scrambleNumbers);
2135 return $scrambleString;
2137 // Append data like session ID or referal ID to the given URL which would
2138 // normally be stored in cookies
2139 function ADD_URL_DATA($URL) {
2143 // Determine URL binder
2145 if (strpos($URL, "?") !== false) $BIND = "&";
2147 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2148 // Cookies are not accepted
2149 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2150 // Cookie found in URL
2151 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2152 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2153 // Not found! So let's set default here
2154 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2157 // Is there already added data? Then change the binder
2158 if (!empty($ADD)) $BIND = "&";
2161 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2162 // Add session from URL
2163 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2165 // Add current session
2166 $ADD .= $BIND."PHPSESSID=".session_id();
2170 // Add all together and return it
2173 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2174 function generatePassString($passHash) {
2177 // Return vanilla password hash
2180 // Is a secret key and master salt already initialized?
2181 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2182 // Only calculate when the secret key is generated
2183 $newHash = ""; $start = 9;
2184 for ($idx = 0; $idx < 10; $idx++) {
2185 $part1 = hexdec(substr($passHash, $start, 4));
2186 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2187 $mod = dechex($idx);
2188 if ($part1 > $part2) {
2189 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2190 } elseif ($part2 > $part1) {
2191 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2193 $mod = substr(round($mod), 0, 4);
2194 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2195 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2200 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2201 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2202 //* DEBUG: */ print($ret."<br />\n");
2205 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2206 $ret = md5($passHash);
2207 //* DEBUG: */ echo "++".$ret."++<br />\n";
2214 // Fix "deleted" cookies
2215 function FIX_DELETED_COOKIES ($cookies) {
2216 // Is this an array with entries?
2217 if ((is_array($cookies)) && (count($cookies) > 0)) {
2218 // Then check all cookies if they are marked as deleted!
2219 foreach ($cookies as $cookieName) {
2220 // Is the cookie set to "deleted"?
2221 if (get_session($cookieName) == "deleted") {
2222 set_session($cookieName, "");
2228 // Output error messages in a fasioned way and die...
2229 function mxchange_die ($msg) {
2232 // Load the message template
2233 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2236 include(PATH."inc/footer.php");
2242 // Display parsing time and number of SQL queries in footer
2243 function DISPLAY_PARSING_TIME_FOOTER() {
2245 $endTime = microtime(true);
2247 // Is the timer started?
2248 if (!isset($GLOBALS['startTime'])) {
2253 // "Explode" both times
2254 $start = explode(" ", $GLOBALS['startTime']);
2255 $end = explode(" ", $endTime);
2256 $runTime = $end[0] - $start[0];
2257 if ($runTime < 0) $runTime = 0;
2258 $runTime = TRANSLATE_COMMA($runTime);
2262 'runtime' => $runTime,
2263 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2264 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2267 // Load the template
2268 LOAD_TEMPLATE("show_timings", false, $content);
2271 // Unset/set session variables
2272 function set_session ($var, $value) {
2275 // Abort in CSS mode here
2276 if ($CSS == 1) return true;
2278 // Trim value and session variable
2279 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2281 // Is the session variable set?
2282 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2283 // Remove the session
2284 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2285 unset($_SESSION[$var]);
2286 return session_unregister($var);
2287 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2289 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2290 $_SESSION[$var] = $value;
2291 return session_register($var);
2292 } elseif (!empty($value)) {
2294 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2295 $_SESSION[$var] = $value;
2299 // Ignored (but valid)
2300 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2304 // Check wether a boolean constant is set
2305 // Taken from user comments in PHP documentation for function constant()
2306 function isBooleanConstantAndTrue($constName) { // : Boolean
2309 // Failed by default
2313 if (isset($constCache[$constName])) {
2315 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2316 $res = $constCache[$constName];
2319 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2320 if (defined($constName)) $res = (constant($constName) === true);
2323 $constCache[$constName] = $res;
2325 //* DEBUG: */ var_dump($res);
2331 // Check wether a session variable is set
2332 function isSessionVariableSet($var) {
2333 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2334 return (isset($_SESSION[$var]));
2336 // Returns wether the value of the session variable or NULL if not set
2337 function get_session($var) {
2340 // Default is not found! ;-)
2343 // Is the variable there or cached values?
2344 if (isset($cacheArray['session'][$var])) {
2345 // Get cached value (skips a lot SQL_ESCAPE() calles!
2346 $value = $cacheArray['session'][$var];
2347 } elseif (isSessionVariableSet($var)) {
2348 // Then get it secured!
2349 $value = SQL_ESCAPE($_SESSION[$var]);
2352 $cacheArray['session'][$var] = $value;
2358 // Send notification to admin
2359 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2360 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2362 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2364 // Send outdated way
2365 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2366 SEND_ADMIN_EMAILS($subject, $msg);
2369 // Destroy user session
2370 function destroy_user_session () {
2371 // Remove all user data from session
2372 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2374 // Merges an array together but only if both are arrays
2375 function merge_array ($array1, $array2) {
2376 // Are both an array?
2377 if ((is_array($array1)) && (is_array($array2))) {
2378 // Merge all together
2379 return array_merge($array1, $array2);
2380 } elseif (is_array($array1)) {
2381 // Return left array
2385 // Something wired happened here...
2386 print(__FUNCTION__.":<pre>");
2387 debug_print_backtrace();
2390 // Debug message logger
2391 function DEBUG_LOG ($file, $line, $message, $force=true) {
2392 // Is debug mode enabled?
2393 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2394 // Log this message away
2395 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2396 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename(__FILE__)."|".__LINE__."|".strip_tags($message)."\n");
2400 // Reads a directory with PHP files in and gets only files back
2401 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2405 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2408 while ($baseFile = readdir($dirPointer)) {
2409 // Load file only if extension is active
2411 $file = $baseDir.$baseFile;
2413 // Is this a valid reset file?
2414 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2415 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2416 // Remove both for extension name
2417 $extName = substr($baseFile, strlen($prefix), -4);
2420 $extId = GET_EXT_ID($extName);
2422 // Is the extension valid and active?
2423 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2424 // Then add this file
2426 } elseif ($extId == 0) {
2427 // Add non-extension files as well
2434 closedir($dirPointer);
2439 // Return array with include files
2442 // Load more reset scripts
2443 function RESET_ADD_INCLUDES () {
2446 // Is the reset set or old sql_patches?
2447 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2452 // Get more daily reset scripts
2453 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2456 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2458 // Create current week mark
2459 $currWeek = date("W", time());
2462 if ($_CONFIG['last_week'] != $currWeek) {
2463 // Include weekly reset scripts
2464 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2467 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2470 // Create current month mark
2471 $currMonth = date("m", time());
2474 if ($_CONFIG['last_month'] != $currMonth) {
2475 // Include monthly reset scripts
2476 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2479 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2485 // Handle extra values
2486 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2487 // Default is the value itself
2490 // Do we have a special filter function?
2491 if (!empty($filterFunction)) {
2492 // Does the filter function exist?
2493 if (function_exists($filterFunction)) {
2494 // Do we have extra parameters here?
2495 if (!empty($extraValue)) {
2496 // Put both parameters in one new array by default
2497 $args = array($value, $extraValue);
2499 // If we have an array simply use it and pre-extend it with our value
2500 if (is_array($extraValue)) {
2501 // Make the new args array
2502 $args = array_merge(array($value), $extraValue);
2505 // Call the multi-parameter call-back
2506 $ret = call_user_func_array($filterFunction, $args);
2508 // One parameter call
2509 $ret = call_user_func($filterFunction, $value);
2517 // Check if given FQFN is a readable file
2518 function FILE_READABLE($fqfn) {
2520 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2522 // Converts timestamp selections into a timestamp
2523 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2524 // Init test variable
2527 // Get last three chars
2528 $TEST = substr($id, -3);
2530 // Improved way of checking! :-)
2531 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2532 // Found a multi-selection for timings?
2533 $TEST = substr($id, 0, -3);
2534 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)) {
2535 // Generate timestamp
2536 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2537 $DATA[] = "$TEST='".$POST[$TEST]."'";
2539 // Remove data from array
2540 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2541 unset($POST[$TEST."_".$rem]);
2545 unset($id); $skip = true; $TEST2 = $TEST;
2548 // Process this entry
2549 $skip = false; $TEST2 = "";
2552 // Reverts the german decimal comma into Computer decimal dot
2553 function REVERT_COMMA ($str) {
2554 // Default float is not a float... ;-)
2557 // Which language is selected?
2558 switch (GET_LANGUAGE()) {
2559 case "de": // German language
2560 // Remove german thousand dots first
2561 $str = str_replace(".", "", $str);
2563 // Replace german commata with decimal dot and cast it
2564 $float = (float)str_replace(",", ".", $str);
2567 default: // US and so on
2568 // Remove thousand dots first and cast
2569 $float = (float)str_replace(",", "", $str);
2576 // Handle menu-depending failed logins and return the rendered content
2577 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2578 // Default output is empty ;-)
2581 // Is the session data set?
2582 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2583 // Ignore zero values
2584 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2585 // Non-guest has login failtures found, get both data and prepare it for template
2586 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2588 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2589 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2593 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2596 // Reset session data
2597 set_session('mxchange_'.$accessLevel.'_failtures', "");
2598 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2601 // Return rendered content
2605 function REBUILD_CACHE ($cache, $inc="") {
2606 global $cacheInstance, $_CONFIG, $CSS;
2608 // Shall I remove the cache file?
2609 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2611 if ($cacheInstance->cache_file($cache, true)) {
2613 $cacheInstance->cache_destroy();
2616 // Include file given?
2619 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2621 // Is the include there?
2622 if (FILE_READABLE($fqfn)) {
2623 // And rebuild it from scratch
2626 // Include not found!
2627 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2632 // Purge admin menu cache
2633 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2634 global $_CONFIG, $cacheInstance;
2636 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2637 if (!EXT_IS_ACTIVE("cache")) {
2638 // Cache extension not active
2640 } elseif (!is_object($cacheInstance)) {
2641 // No cache instance!
2642 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2644 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2645 // Caching disabled (currently experiemental!)
2649 // Experiemental feature!
2650 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2652 // Translates the "pool type" into human-readable
2653 function TRANSLATE_POOL_TYPE ($type) {
2654 // Default type is unknown
2655 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2657 // Generate constant
2658 $constName = sprintf("POOL_TYPE_%s", $type);
2661 if (defined($constName)) {
2663 $translated = constant($constName);
2666 // Return "translation"
2669 // "Getter" for remote IP number
2670 function GET_REMOTE_ADDR () {
2671 // Get remote ip from environment
2672 $remoteAddr = getenv('REMOTE_ADDR');
2674 // Is removeip installed?
2675 if (EXT_IS_ACTIVE("removeip")) {
2676 // Then anonymize it
2677 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2683 // "Getter" for remote hostname
2684 function GET_REMOTE_HOST () {
2685 // Get remote ip from environment
2686 $remoteHost = getenv('REMOTE_HOST');
2688 // Is removeip installed?
2689 if (EXT_IS_ACTIVE("removeip")) {
2690 // Then anonymize it
2691 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2697 // "Getter" for user agent
2698 function GET_USER_AGENT () {
2699 // Get remote ip from environment
2700 $userAgent = getenv('HTTP_USER_AGENT');
2702 // Is removeip installed?
2703 if (EXT_IS_ACTIVE("removeip")) {
2704 // Then anonymize it
2705 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2711 // "Getter" for referer
2712 function GET_REFERER () {
2713 // Get remote ip from environment
2714 $referer = getenv('HTTP_REFERER');
2716 // Is removeip installed?
2717 if (EXT_IS_ACTIVE("removeip")) {
2718 // Then anonymize it
2719 $referer = GET_ANONYMOUS_REFERER($referer);
2726 // Adds a bonus mail to the queue
2727 // This is a high-level function!
2728 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2729 // Use mode from data if not set and availble ;-)
2730 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2732 // Generate receiver list
2733 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2736 if (!empty($RECEIVER)) {
2737 // Add bonus mail to queue
2738 ADD_BONUS_MAIL_TO_QUEUE(
2750 // Mail inserted into bonus pool
2751 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_BONUS_SEND);
2752 } elseif ($output) {
2753 // More entered than can be reached!
2754 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_MORE_SELECTED);
2757 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2760 // Determines referal id and sets it
2761 function DETERMINE_REFID () {
2762 global $_CONFIG, $CLICK, $_SERVER;
2764 // Check if refid is set
2765 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2766 // The variable user comes from the click-counter script click.php and we only accept this here
2767 $GLOBALS['refid'] = bigintval($_GET['user']);
2768 } elseif (!empty($_POST['refid'])) {
2769 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2770 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2771 } elseif (!empty($_GET['refid'])) {
2772 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2773 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2774 } elseif (!empty($_GET['ref'])) {
2775 // Set refid=ref (the referal link uses such variable)
2776 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2777 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2778 // Set session refid als global
2779 $GLOBALS['refid'] = bigintval(get_session('refid'));
2780 } elseif ((GET_EXT_VERSION("sql_patches") != "") && ($_CONFIG['def_refid'] > 0)) {
2781 // Set default refid as refid in URL
2782 $GLOBALS['refid'] = bigintval($_CONFIG['def_refid']);
2783 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && ($_CONFIG['select_user_zero_refid']) == "Y") {
2784 // Select a random user which has confirmed enougth mails
2785 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2787 // No default ID when sql_patches is not installed or none set
2788 $GLOBALS['refid'] = 0;
2791 // Set cookie when default refid > 0
2792 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (isset($_CONFIG['def_refid'])) && ($_CONFIG['def_refid'] > 0))) {
2794 set_session('refid', $GLOBALS['refid']);
2798 // Destroys the admin session
2799 function DESTROY_ADMIN_SESSION () {
2800 // Kill maybe existing session variables including array elements
2801 set_session('admin_login' , "");
2802 set_session('admin_md5' , "");
2803 set_session('admin_last' , "");
2804 set_session('admin_to' , "");
2806 // Destroy session and return status
2807 return @session_destroy();
2810 // Checks if a given apache module is loaded
2811 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2812 // Check it and return result
2813 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2816 //////////////////////////////////////////////////
2818 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2820 //////////////////////////////////////////////////
2822 if (!function_exists('html_entity_decode')) {
2823 // Taken from documentation on www.php.net
2824 function html_entity_decode($string) {
2825 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2826 $trans_tbl = array_flip($trans_tbl);
2827 return strtr($string, $trans_tbl);