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
146 header("HTTP/1.1 200");
149 $now = gmdate('D, d M Y H:i:s') . ' GMT';
151 // General headers for no caching
152 header("Expired: " . $now); // RFC2616 - Section 14.21
153 header("Last-Modified: " . $now);
154 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
155 header("Pragma: no-cache"); // HTTP/1.0
156 header("Connection: Close");
158 // Extension "rewrite" installed?
159 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
160 $OUTPUT = REWRITE_LINKS($OUTPUT);
163 // Compile and run finished rendered HTML code
164 while (strpos($OUTPUT, '{!') > 0) {
165 // Prepare the content and eval() it...
167 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
170 // Was that eval okay?
171 if (empty($newContent)) {
172 // Something went wrong!
173 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
175 $OUTPUT = $newContent;
178 // Output code here, DO NOT REMOVE! ;-)
180 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
181 // Rewrite links when rewrite extension is active
182 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
183 $OUTPUT = REWRITE_LINKS($OUTPUT);
186 // Compile and run finished rendered HTML code
187 while (strpos($OUTPUT, '{!') > 0) {
188 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
192 // Output code here, DO NOT REMOVE! ;-)
197 // Output the raw HTML code
198 function OUTPUT_RAW ($HTML) {
199 // Output stripped HTML code to avoid broken JavaScript code, etc.
200 echo stripslashes(stripslashes($HTML));
202 // Flush the output if only _OB_CACHING is not "on"
203 if (_OB_CACHING != "on") {
209 // Add a fatal error message to the queue array
210 function ADD_FATAL ($message, $extra="") {
214 // Regular text message to add to $FATAL
217 // $message is text with a mask plus extras to insert into the text
218 $message = sprintf($message, $extra);
222 // Log fatal messages away
223 DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
226 // Load a template file and return it's content (only it's name; do not use ' or ")
227 function LOAD_TEMPLATE($template, $return=false, $content=array()) {
228 // Add more variables which you want to use in your template files
229 global $DATA, $_CONFIG, $username;
231 // Make all template names lowercase
232 $template = strtolower($template);
234 // Count the template load
235 if (!isset($_CONFIG['num_templates'])) $_CONFIG['num_templates'] = 0;
236 $_CONFIG['num_templates']++;
240 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
242 // @DEPRECATED Try to remove this if() block
243 if ($template == "member_support_form") {
244 // Support request of a member
245 $result = SQL_QUERY_ESC("SELECT gender, surname, family, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
246 array($GLOBALS['userid']), __FILE__, __LINE__);
248 // Is content an array?
249 if (is_array($content)) {
251 $content = array_merge($content, SQL_FETCHARRAY($result));
254 $content['gender'] = TRANSLATE_GENDER($content['gender']);
256 // DEPRECATED: Load data in direct variables
257 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
260 $gender = TRANSLATE_GENDER($gender);
264 SQL_FREERESULT($result);
267 // Generate date/time string
268 $date_time = MAKE_DATETIME(time(), "1");
271 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
274 // Check for admin/guest/member templates
275 if (strpos($template, "admin_") > -1) {
276 // Admin template found
278 } elseif (strpos($template, "guest_") > -1) {
279 // Guest template found
281 } elseif (strpos($template, "member_") > -1) {
282 // Member template found
284 } elseif (strpos($template, "install_") > -1) {
285 // Installation template found
287 } elseif (strpos($template, "ext_") > -1) {
288 // Extension template found
290 } elseif (strpos($template, "la_") > -1) {
291 // "Logical-area" template found
294 // Test for extension
295 $test = substr($template, 0, strpos($template, "_"));
296 if (EXT_IS_ACTIVE($test)) {
297 // Set extra path to extension's name
302 ////////////////////////
303 // Generate file name //
304 ////////////////////////
305 $file = $BASE.$MODE.$template.".tpl";
307 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
308 // Select what depended header/footer template file for admin/guest/member area
309 $file2 = sprintf("%s%s%s_%s.tpl",
313 SQL_ESCAPE($GLOBALS['what'])
317 if (FILE_READABLE($file2)) $file = $file2;
319 // Remove variable from memory
323 // Does the special template exists?
324 if (!FILE_READABLE($file)) {
325 // Reset to default template
326 $file = $BASE.$template.".tpl";
329 // Now does the final template exists?
330 if (FILE_READABLE($file)) {
331 // The local file does exists so we load it. :)
332 $tmpl_file = implode("", file($file));
334 // Replace ' to our own chars to preventing them being quoted
335 while (strpos($tmpl_file, "\'") !== false) { $tmpl_file = str_replace("\'", '{QUOT}', $tmpl_file); }
337 // Do we have to compile the code?
339 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
341 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
344 // Simply return loaded code
348 // Add surrounding HTML comments to help finding bugs faster
349 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
350 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
351 // Only admins shall see this warning or when installation mode is active
352 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
353 (".basename($file).")<br />
356 <pre>".print_r($content, true)."</pre>
358 <pre>".print_r($DATA, true)."</pre>
362 // Remove content and data
366 // Do we have some content to output or return?
368 // Not empty so let's put it out! ;)
370 // Return the HTML code
376 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
377 // Warning, empty output!
378 return "E:".$template."<br />\n";
382 // Send mail out to an email address
383 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
384 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
386 // Compile subject line (for POINTS constant etc.)
387 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
391 if ((!eregi("@", $TO)) && ($TO > 0)) {
392 // Value detected, is the message extension installed?
393 if (EXT_IS_ACTIVE("msg")) {
394 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
397 // Load email address
398 $result_email = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
399 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
401 // Does the user exist?
402 if (SQL_NUMROWS($result_email)) {
403 // Load email address
404 list($TO) = SQL_FETCHROW($result_email);
411 SQL_FREERESULT($result_email);
413 } elseif ("$TO" == "0") {
417 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
419 // Check for PHPMailer or debug-mode
420 if (!CHECK_PHPMAILER_USAGE()) {
421 // Not in PHPMailer-Mode
423 // Load email header template
424 $FROM = LOAD_EMAIL_TEMPLATE("header");
427 $FROM .= LOAD_EMAIL_TEMPLATE("header");
429 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
431 // Load email header template
432 $FROM = LOAD_EMAIL_TEMPLATE("header");
435 $FROM .= LOAD_EMAIL_TEMPLATE("header");
440 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
444 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
447 // Fix HTML parameter (default is no!)
448 if (empty($HTML)) $HTML = "N";
449 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
450 // In debug mode we want to display the mail instead of sending it away so we can debug this part
452 ".htmlentities(trim($FROM))."
454 Subject : ".$SUBJECT."
459 if (defined('DEBUG_MAIL')) DEBUG_LOG(__FUNCTION__, __LINE__, "to={$TO},subject={$SUBJECT},msg={$MSG}");
460 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
461 // Send mail as HTML away
462 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
463 } elseif (!empty($TO)) {
465 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
466 } elseif ($HTML == "N") {
468 SEND_RAW_EMAIL(WEBMASTER, "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
472 // Check if legacy or PHPMailer command
474 function CHECK_PHPMAILER_USAGE() {
475 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
479 * Send out a raw email with PHPMailer class or legacy mail() command
481 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
482 // Shall we use PHPMailer class or legacy mode?
483 if (CHECK_PHPMAILER_USAGE()) {
484 // Use PHPMailer class with SMTP enabled
485 require_once(PATH."inc/phpmailer/class.phpmailer.php");
486 require_once(PATH."inc/phpmailer/class.smtp.php");
489 $mail = new PHPMailer();
490 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
493 $mail->SMTPAuth = true;
494 $mail->Host = SMTP_HOSTNAME;
496 $mail->Username = SMTP_USER;
497 $mail->Password = SMTP_PASSWORD;
499 $mail->From = WEBMASTER;
503 $mail->FromName = MAIN_TITLE;
504 $mail->Subject = $subject;
505 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
507 $mail->AltBody = "Your mail program required HTML support to read this mail!";
508 $mail->WordWrap = 70;
511 $mail->Body = html_entity_decode($msg);
513 $mail->AddAddress($to, "");
514 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
515 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
516 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
519 // Use legacy mail() command
520 @mail($to, $subject, html_entity_decode($msg), $from);
525 // Generate a password in a specified length or use default password length
526 function GEN_PASS($LEN = 0) {
528 if ($LEN == 0) $LEN = $_CONFIG['pass_len'];
530 // Initialize array with all allowed chars
531 $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,-,+,_,/");
533 // Initialize randomizer
534 mt_srand((double) microtime() * 1000000);
536 // Start creating password
538 for ($i = 0; $i < $LEN; $i++) {
539 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
542 // When the size is below 40 we can also add additional security by scrambling it
543 if (strlen($PASS) <= 40) {
544 // Also scramble the password
545 $PASS = scrambleString($PASS);
548 // Return the password
552 function MAKE_DATETIME ($time, $mode="0")
556 return NEVER_HAPPENED;
558 // Filter out numbers
559 $time = bigintval($time);
562 switch (GET_LANGUAGE())
564 case "de": // German date / time format
566 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
567 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
568 case "2": $ret = date("d.m.Y|H:i", $time); break;
569 case "3": $ret = date("d.m.Y", $time); break;
573 default: // Default is the US date / time format!
575 case "0": $ret = date("r", $time); break;
576 case "1": $ret = date("Y-m-d - g:i A", $time); break;
577 case "2": $ret = date("y-m-d|H:i", $time); break;
578 case "3": $ret = date("y-m-d", $time); break;
584 // Translates the american decimal dot into a german comma
585 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
588 // Default is 3 you can change this in admin area "Misc -> Misc Options"
589 if (empty($_CONFIG['max_comma'])) $_CONFIG['max_comma'] = "3";
591 // Use from config is default
592 $maxComma = $_CONFIG['max_comma'];
594 // Use from parameter?
595 if ($max > 0) $maxComma = $max;
599 // Test for commata if in cut-mode
600 $com = explode(".", $dotted);
601 if (count($com) > 1) {
602 // Commata found, so only zeros?
603 if ($com[1] == str_repeat("0", strlen($com[1]))) {
604 // Only zeros, so display only one
608 // Don't display commatas even if there are none... ;-)
614 //DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
617 switch (GET_LANGUAGE()) {
619 $dotted = number_format($dotted, $maxComma, ",", ".");
623 $dotted = number_format($dotted, $maxComma, ".", ",");
627 // Return translated value
632 function DEREFERER ($URL) {
633 // Don't de-refer our own links!
634 if (substr($URL, 0, strlen(URL)) != URL) {
635 // De-refer this link
636 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
644 function TRANSLATE_GENDER ($gender) {
647 case "M": $ret = GENDER_M; break;
648 case "F": $ret = GENDER_F; break;
649 case "C": $ret = GENDER_C; break;
650 default : $ret = $gender; break;
655 function FRAMETESTER($URL) {
656 // Prepare frametester URL
657 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
659 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
661 return $frametesterUrl;
664 function SELECTION_COUNT($array) {
666 if (is_array($array)) {
667 foreach ($array as $key => $sel) {
668 if (!empty($sel)) $ret++;
674 function IMG_CODE ($code, $type, $DATA, $uid) {
675 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
678 function TRANSLATE_STATUS($status) {
682 $ret = ACCOUNT_UNCONFIRMED;
686 $ret = ACCOUNT_CONFIRMED;
690 $ret = ACCOUNT_LOCKED;
695 $ret = ACCOUNT_DELETED;
699 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
705 function GET_LANGUAGE() {
706 if (!empty($_GET['mx_lang'])) {
707 // Accept only first 2 chars
708 $lang = substr($_GET['mx_lang'], 0, 2);
714 // Set default return value to default language from config
717 // Check GET variable and cookie
719 // Check if main language file does exist
720 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
721 // Okay found, so let's update cookies
724 } elseif (!isSessionVariableSet('mx_lang')) {
725 // Return stored value from cookie
726 $ret = get_session('mx_lang');
728 // Fixes a warning before the session has the mx_lang constant
729 if (empty($ret)) $ret = DEFAULT_LANG;
734 function SET_LANGUAGE($lang) {
737 // Accept only first 2 chars!
738 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
741 set_session("mx_lang", $lang);
744 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
745 global $DATA, $_CONFIG, $REPLACER;
747 // Make sure all template names are lowercase!
748 $template = strtolower($template);
750 // Default "nickname" if extension is not installed
753 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
754 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
756 // Prepare IP number and User Agent
757 $REMOTE_ADDR = GET_REMOTE_ADDR();
758 $HTTP_USER_AGENT = GET_USER_AGENT();
763 // Is the admin logged in?
766 $aid = GET_ADMIN_ID(get_session('admin_login'));
769 $ADMIN = GET_ADMIN_EMAIL($aid);
772 // Neutral email address is default
775 // Expiration in a nice output format
776 if ($_CONFIG['auto_purge'] == 0) {
777 // Will never expire!
778 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
779 } elseif (function_exists('CREATE_FANCY_TIME')) {
780 // Create nice date string
781 $EXPIRATION = CREATE_FANCY_TIME($_CONFIG['auto_purge']);
784 $EXPIRATION = round($_CONFIG['auto_purge']/60/60/24)." "._DAYS;
787 // Is content an array?
788 if (is_array($content)) {
789 // Add expiration to array, $EXPIRATION is now deprecated!
790 $content['expiration'] = $EXPIRATION;
794 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template}<br />\n";
796 if (EXT_IS_ACTIVE("nickname")) {
797 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
799 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
800 array(bigintval($UID)), __FILE__, __LINE__);
802 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
804 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s LIMIT 1",
805 array(bigintval($UID)), __FILE__, __LINE__);
808 // Is content an array?
809 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content[]=".gettype($content)."<br />\n";
810 if (is_array($content)) {
811 // Fetch and migrate data
812 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
813 $content = array_merge($content, SQL_FETCHARRAY($result));
814 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
818 SQL_FREERESULT($result);
821 // Translate M to male or F to female if present
822 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
824 // Overwrite email from data if present
825 if (isset($content['email'])) $email = $content['email'];
827 // Store email for some functions in global data array
828 $DATA['email'] = $email;
831 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
833 // Check for admin/guest/member templates
834 if (strpos($template, "admin_") > -1) {
835 // Admin template found
836 $file = $BASE."admin/".$template.".tpl";
837 } elseif (strpos($template, "guest_") > -1) {
838 // Guest template found
839 $file = $BASE."guest/".$template.".tpl";
840 } elseif (strpos($template, "member_") > -1) {
841 // Member template found
842 $file = $BASE."member/".$template.".tpl";
844 // Test for extension
845 $test = substr($template, 0, strpos($template, "_"));
846 if (EXT_IS_ACTIVE($test)) {
847 // Set extra path to extension's name
848 $file = $BASE.$test."/".$template.".tpl";
850 // No special filename
851 $file = $BASE.$template.".tpl";
855 // Does the special template exists?
856 if (!FILE_READABLE($file)) {
857 // Reset to default template
858 $file = $BASE.$template.".tpl";
861 // Now does the final template exists?
863 if (FILE_READABLE($file)) {
864 // The local file does exists so we load it. :)
865 $tmpl_file = implode("", file($file));
866 $tmpl_file = addslashes($tmpl_file);
869 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
871 } elseif (!empty($template)) {
872 // Template file not found!
873 $newContent = TEMPLATE_404.": ".$template."<br />
875 <pre>".print_r($content, true)."</pre>
877 <pre>".print_r($DATA, true)."</pre>
880 // Debug mode not active? Then remove the HTML tags
881 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
883 // No template name supplied!
884 $newContent = NO_TEMPLATE_SUPPLIED;
887 // Is there some content?
888 if (empty($newContent)) {
890 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
891 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
894 // Remove content and data
898 // Return compiled content
899 return COMPILE_CODE($newContent);
902 function MAKE_TIME($H, $M, $S, $stamp) {
903 // Extract day, month and year from given timestamp
904 $DAY = date("d", $stamp);
905 $MONTH = date("m", $stamp);
906 $YEAR = date('Y', $stamp);
908 // Create timestamp for wished time which depends on extracted date
909 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
912 function LOAD_URL($URL, $addUrlData=true) {
913 global $CSS, $_CONFIG, $footer;
915 // Check if http(s):// is there
916 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
917 // Make all URLs full-qualified
921 // Compile out URI codes
922 $URL = COMPILE_CODE($URL);
925 $OUTPUT = ob_get_contents();
927 // Clear it only if there is content
928 if (!empty($OUTPUT)) {
932 // Add some data to URL if cookies are not accepted
933 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
935 // Probe for bot from search engine
936 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT())) || (eregi("spider", GET_USER_AGENT()))) {
937 // Search engine bot detected so let's rewrite many chars for the link
938 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
940 // Output new location link as anchor
941 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
942 } elseif (!headers_sent()) {
943 // Load URL when headers are not sent
946 debug_print_backtrace();
947 die("</pre>URL={$URL}");
949 @header ("Location: ".str_replace("&", "&", $URL));
951 // Output error message
952 include(PATH."inc/header.php");
953 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
954 include(PATH."inc/footer.php");
959 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
960 global $SEC_CHARS, $URL_CHARS;
961 // Is the code a string?
962 if (!is_string($code)) {
963 // Silently return it
969 // Select smaller set of chars to replace when we e.g. want to compile URLs
970 if (!$full) $ARRAY = $URL_CHARS;
974 // BEFORE 0.2.1 : Language and data constants
975 // WITH 0.2.1+ : Only language constants
976 $code = str_replace('{--','".', str_replace('--}','."', $code));
978 // BEFORE 0.2.1 : Not used
979 // WITH 0.2.1+ : Data constants
980 $code = str_replace('{!','".', str_replace("!}", '."', $code));
983 // Compile QUOT and other non-HTML codes
984 foreach ($ARRAY['to'] as $k => $to) {
985 // Do the reversed thing as in inc/libs/security_functions.php
986 $code = str_replace($to, $ARRAY['from'][$k], $code);
989 // But shall I keep simple quotes for later use?
990 if ($simple) $code = str_replace("\'", '{QUOT}', $code);
992 // Find $content[bla][blub] entries
993 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
995 // Are some matches found?
996 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
997 // Replace all matches
998 $matchesFound = array();
999 foreach ($matches[0] as $key => $match) {
1000 // Fuzzy look has failed by default
1001 $fuzzyFound = false;
1003 // Fuzzy look on match if already found
1004 foreach ($matchesFound as $found => $set) {
1006 $test = substr($found, 0, strlen($match));
1008 // Does this entry exist?
1009 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1010 if ($test == $match) {
1012 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1019 if ($fuzzyFound) continue;
1021 // Take all string elements
1022 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1023 // Replace it in the code
1024 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1025 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1026 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1027 $matchesFound[$key."_".$matches[4][$key]] = 1;
1028 $matchesFound[$match] = 1;
1029 } elseif (!isset($matchesFound[$match])) {
1030 // Not yet replaced!
1031 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1032 $code = str_replace($match, "\".".$match.".\"", $code);
1033 $matchesFound[$match] = 1;
1038 // Return compiled code
1042 /************************************************************************
1044 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1045 * $a_sort sortiert: *
1047 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1048 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1049 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1050 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1051 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1053 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1054 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1055 * Sie, dass es doch nicht so schwer ist! :-) *
1057 ************************************************************************/
1058 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1061 while ($primary_key < count($a_sort)) {
1062 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1063 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1066 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1067 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1068 } elseif ($key != $key2) {
1069 // Sort numbers (E.g.: 9 < 10)
1070 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1071 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1075 // We have found two different values, so let's sort whole array
1076 foreach ($dummy as $sort_key => $sort_val) {
1077 $t = $dummy[$sort_key][$key];
1078 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1079 $dummy[$sort_key][$key2] = $t;
1090 // Write back sorted array
1094 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0")
1096 global $MONTH_DESCR; $OUT = "";
1099 // This is a yes/no selection only!
1100 if ($id > 0) $prefix .= "[".$id."]";
1101 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1105 // Begin with regular selection box here
1106 if (!empty($prefix)) $prefix .= "_";
1108 if ($id > 0) $type2 .= "[".$id."]";
1109 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1114 for ($idx = 1; $idx < 32; $idx++)
1116 $OUT .= "<OPTION value=\"".$idx."\"";
1117 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1118 $OUT .= ">".$idx."</OPTION>\n";
1122 case "month": // Month
1123 foreach ($MONTH_DESCR as $month => $descr)
1125 $OUT .= "<OPTION value=\"".$month."\"";
1126 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1127 $OUT .= ">".$descr."</OPTION>\n";
1131 case "year": // Year
1133 $YEAR = date('Y', time());
1135 // Check if the default value is larger than minimum and bigger than actual year
1136 if (($DEFAULT > 1930) && ($DEFAULT >= $YEAR))
1138 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++)
1140 $OUT .= "<OPTION value=\"".$idx."\"";
1141 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1142 $OUT .= ">".$idx."</OPTION>\n";
1145 elseif ($DEFAULT == -1)
1147 // Current year minus 1
1148 for ($idx = 2003; $idx <= ($YEAR + 1); $idx++)
1150 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1155 // Get current year and subtract 16 (for erotic content)
1156 $OUT .= "<OPTION value=\"1929\"><1930</OPTION>\n";
1157 $YEAR = date('Y', time()) - 16;
1158 for ($idx = 1930; $idx <= $YEAR; $idx++)
1160 $OUT .= "<OPTION value=\"".$idx."\"";
1161 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1162 $OUT .= ">".$idx."</OPTION>\n";
1169 for ($idx = 0; $idx < 60; $idx+=5) {
1170 if (strlen($idx) == 1) $idx = "0".$idx;
1171 $OUT .= "<OPTION value=\"".$idx."\"";
1172 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1173 $OUT .= ">".$idx."</OPTION>\n";
1178 for ($idx = 0; $idx < 24; $idx++) {
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 $OUT .= "<OPTION value=\"Y\"";
1188 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1189 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1190 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1191 $OUT .= ">".NO."</OPTION>\n";
1194 $OUT .= " </SELECT>\n";
1198 function TRANSLATE_YESNO($yn)
1202 case 'Y': $yn = YES; break;
1203 case 'N': $yn = NO; break;
1204 default : $yn = "??? (".$yn.")"; break;
1209 // Deprecated : $length
1212 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1215 // Fix missing _MAX constant
1216 if (!defined('_MAX')) define('_MAX', 15235);
1218 // Build server string
1219 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1222 $keys = SITE_KEY.":".DATE_KEY;
1223 if (isset($_CONFIG['secret_key'])) $keys .= ":".$_CONFIG['secret_key'];
1224 if (isset($_CONFIG['file_hash'])) $keys .= ":".$_CONFIG['file_hash'];
1225 $keys .= ":".date("d-m-Y (l-F-T)", bigintval($_CONFIG['patch_ctime']));
1226 if (isset($_CONFIG['master_salt'])) $keys .= ":".$_CONFIG['master_salt'];
1228 // Build string from misc data
1229 $data = $code.":".$uid.":".$DATA;
1231 // Add more additional data
1232 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1233 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1234 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1235 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1236 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1237 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1239 // Calculate number for generating the code
1240 $a = $code + _ADD - 1;
1242 if (isset($_CONFIG['master_hash'])) {
1243 // Generate hash with master salt from modula of number with the prime number and other data
1244 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, $_CONFIG['master_salt']);
1246 // Create number from hash
1247 $rcode = hexdec(substr($saltedHash, strlen($_CONFIG['master_salt']), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1249 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1250 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1252 // Create number from hash
1253 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1256 // At least 10 numbers shall be secure enought!
1257 $len = $_CONFIG['code_length'];
1258 if ($len == 0) $len = $length;
1259 if ($len == 0) $len = 10;
1261 // Cut off requested counts of number
1262 $return = substr(str_replace('.', "", $rcode), 0, $len);
1264 // Done building code
1267 // Does only allow numbers
1268 function bigintval($num, $castValue = true) {
1269 // Filter all numbers out
1270 $ret = preg_replace("/[^0123456789]/", "", $num);
1273 if ($castValue) $ret = (double)$ret;
1275 // Has the whole value changed?
1276 if ("".$ret."" != "".$num."") {
1278 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1284 // Insert the code in $img_code into jpeg or PNG image
1285 function GENERATE_IMAGE($img_code, $header=true) {
1288 if ((strlen($img_code) > 6) || (empty($img_code)) || ($_CONFIG['code_length'] == 0)) {
1289 // Stop execution of function here because of over-sized code length
1291 } elseif (!$header) {
1292 // Return in an HTML code code
1293 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1297 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), $_CONFIG['img_type']);
1298 if (FILE_READABLE($img)) {
1299 // Switch image type
1300 switch ($_CONFIG['img_type'])
1303 // Okay, load image and hide all errors
1304 $image = @imagecreatefromjpeg($img);
1308 // Okay, load image and hide all errors
1309 $image = @imagecreatefrompng($img);
1313 // Exit function here
1317 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1318 $text_color = imagecolorallocate($image, 0, 0, 0);
1320 // Insert code into image
1321 imagestring($image, 5, 14, 2, $img_code, $text_color);
1323 // Return to browser
1324 header ("Content-Type: image/".$_CONFIG['img_type']);
1326 // Output image with matching image factory
1327 switch ($_CONFIG['img_type']) {
1328 case "jpg": imagejpeg($image); break;
1329 case "png": imagepng($image); break;
1332 // Remove image from memory
1333 imagedestroy($image);
1335 // Create selection box or array of splitted timestamp
1336 function CREATE_TIME_SELECTIONS($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1339 // Calculate 2-seconds timestamp
1340 $stamp = round($timestamp);
1342 // Do we have a leap year?
1344 $TEST = date('Y', time()) / 4;
1345 $M1 = date("m", time());
1346 $M2 = date("m", (time() + $stamp));
1348 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1349 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = $_CONFIG['one_day'];
1351 // First of all years...
1352 $Y = abs(floor($stamp / (31536000 + $SWITCH)));
1354 $M = abs(floor($stamp / 2628000 - $Y * 12));
1356 $W = abs(floor($stamp / 604800 - $Y * ((365 + $SWITCH / $_CONFIG['one_day']) / 7) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day']) / 7)));
1358 $D = abs(floor($stamp / 86400 - $Y * (365 + $SWITCH / $_CONFIG['one_day']) - ($M / 12 * (365 + $SWITCH / $_CONFIG['one_day'])) - $W * 7));
1360 $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));
1362 $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));
1363 // And at last seconds...
1364 $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));
1366 // Is seconds zero and time is < 60 seconds?
1367 if (($s == 0) && ($stamp < 60)) {
1369 $s = round($timestamp);
1373 // Now we convert them in seconds...
1375 if ($return_array) {
1376 // Just put all data in an array for later use
1388 $OUT = "<DIV align=\"".$align."\">\n";
1389 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1392 if (ereg('Y', $display) || (empty($display))) {
1393 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1396 if (ereg("M", $display) || (empty($display))) {
1397 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1400 if (ereg("W", $display) || (empty($display))) {
1401 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1404 if (ereg("D", $display) || (empty($display))) {
1405 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1408 if (ereg("h", $display) || (empty($display))) {
1409 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1412 if (ereg("m", $display) || (empty($display))) {
1413 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1416 if (ereg("s", $display) || (empty($display))) {
1417 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1423 if (ereg('Y', $display) || (empty($display))) {
1424 // Generate year selection
1425 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1426 for ($idx = 0; $idx <= 10; $idx++) {
1427 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1428 if ($idx == $Y) $OUT .= " selected default";
1429 $OUT .= ">".$idx."</OPTION>\n";
1431 $OUT .= " </SELECT></TD>\n";
1433 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1436 if (ereg("M", $display) || (empty($display))) {
1437 // Generate month selection
1438 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1439 for ($idx = 0; $idx <= 11; $idx++)
1441 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1442 if ($idx == $M) $OUT .= " selected default";
1443 $OUT .= ">".$idx."</OPTION>\n";
1445 $OUT .= " </SELECT></TD>\n";
1447 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1450 if (ereg("W", $display) || (empty($display))) {
1451 // Generate week selection
1452 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1453 for ($idx = 0; $idx <= 4; $idx++) {
1454 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1455 if ($idx == $W) $OUT .= " selected default";
1456 $OUT .= ">".$idx."</OPTION>\n";
1458 $OUT .= " </SELECT></TD>\n";
1460 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1463 if (ereg("D", $display) || (empty($display))) {
1464 // Generate day selection
1465 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1466 for ($idx = 0; $idx <= 31; $idx++) {
1467 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1468 if ($idx == $D) $OUT .= " selected default";
1469 $OUT .= ">".$idx."</OPTION>\n";
1471 $OUT .= " </SELECT></TD>\n";
1473 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1476 if (ereg("h", $display) || (empty($display))) {
1477 // Generate hour selection
1478 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1479 for ($idx = 0; $idx <= 23; $idx++) {
1480 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1481 if ($idx == $h) $OUT .= " selected default";
1482 $OUT .= ">".$idx."</OPTION>\n";
1484 $OUT .= " </SELECT></TD>\n";
1486 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1489 if (ereg("m", $display) || (empty($display))) {
1490 // Generate minute selection
1491 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1492 for ($idx = 0; $idx <= 59; $idx++) {
1493 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1494 if ($idx == $m) $OUT .= " selected default";
1495 $OUT .= ">".$idx."</OPTION>\n";
1497 $OUT .= " </SELECT></TD>\n";
1499 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1502 if (ereg("s", $display) || (empty($display))) {
1503 // Generate second selection
1504 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1505 for ($idx = 0; $idx <= 45; $idx += 15) {
1506 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1507 if ($idx == $s) $OUT .= " selected default";
1508 $OUT .= ">".$idx."</OPTION>\n";
1510 $OUT .= " </SELECT></TD>\n";
1512 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1515 $OUT .= "</TABLE>\n";
1517 // Return generated HTML code
1522 function CREATE_TIMESTAMP_FROM_SELECTIONS($prefix, $POST) {
1526 // Do we have a leap year?
1528 $TEST = date('Y', time()) / 4;
1529 $M1 = date("m", time());
1530 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1531 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = $_CONFIG['one_day'];
1532 // First add years...
1533 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1535 $ret += $POST[$prefix."_mo"] * 2628000;
1537 $ret += $POST[$prefix."_we"] * 604800;
1539 $ret += $POST[$prefix."_da"] * 86400;
1541 $ret += $POST[$prefix."_ho"] * 3600;
1543 $ret += $POST[$prefix."_mi"] * 60;
1544 // And at last seconds...
1545 $ret += $POST[$prefix."_se"];
1546 // Return calculated value
1549 // Sends out mail to all administrators
1550 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1551 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1552 // Trim template name
1553 $template = trim($template);
1555 // Load email template
1556 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1558 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1559 // Older version detected!
1560 return SEND_ADMIN_EMAILS($subj, $msg);
1563 // Check which admin shall receive this mail
1564 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1565 array($template), __FILE__, __LINE__);
1566 if (SQL_NUMROWS($result) == 0) {
1567 // Create new entry (to all admins)
1568 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1569 array($template), __FILE__, __LINE__);
1571 // Load admin IDs...
1573 while(list($aid) = SQL_FETCHROW($result)) {
1578 SQL_FREERESULT($result);
1580 // "implode" IDs and query string
1581 $aid = implode(",", $aids);
1583 // Add line to userlog
1584 USERLOG_ADD_LINE($subj, $msg, $UID);
1586 } elseif ($aid == "0") {
1587 // Select all email adresses
1588 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1590 // If Admin-ID is not "to-all" select
1591 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1595 // Load email addresses and send away
1596 while (list($email) = SQL_FETCHROW($result)) {
1597 SEND_EMAIL($email, $subj, $msg);
1601 SQL_FREERESULT($result);
1604 function CREATE_FANCY_TIME($stamp) {
1605 // Get data array with years/months/weeks/days/...
1606 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1608 foreach($data as $k => $v) {
1610 // Value is greater than 0 "eval" data to return string
1611 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1617 // Do we have something there?
1618 if (strlen($ret) > 0) {
1619 // Remove leading commata and space
1620 $ret = substr($ret, 2);
1623 $ret = "0 "._SECONDS;
1626 // Return fancy time string
1630 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1631 $SEP = ""; $TOP = "";
1634 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1638 for ($page = 1; $page <= $PAGES; $page++) {
1639 // Is the page currently selected or shall we generate a link to it?
1640 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1641 // Is currently selected, so only highlight it
1642 $NAV .= "<STRONG>-";
1644 // Open anchor tag and add base URL
1645 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1647 // Add userid when we shall show all mails from a single member
1648 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1650 // Close open anchor tag
1654 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1655 // Is currently selected, so only highlight it
1656 $NAV .= "-</STRONG>";
1662 // Add seperator if we have not yet reached total pages
1663 if ($page < $PAGES) $NAV .= " | ";
1666 // Define constants only once
1667 if (!defined('__NAV_OUTPUT')) {
1668 define('__NAV_OUTPUT' , $NAV);
1669 define('__NAV_COLSPAN', $colspan);
1670 define('__NAV_TOP' , $TOP);
1671 define('__NAV_SEP' , $SEP);
1674 // Load navigation template
1675 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1678 // Return generated HTML-Code
1686 // Extract host from script name
1687 function EXTRACT_HOST (&$script) {
1688 // Use default SERVER_URL by default... ;) So?
1691 // Is this URL valid?
1692 if (substr($script, 0, 7) == "http://") {
1693 // Use the hostname from script URL as new hostname
1694 $url = substr($script, 7);
1695 $extract = explode("/", $url);
1697 // Done extracting the URL :)
1700 // Extract host name
1701 $host = str_replace("http://", "", $url);
1702 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1704 // Generate relative URL
1705 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1706 if (substr(strtolower($script), 0, 7) == "http://") {
1707 // But only if http:// is in front!
1708 $script = substr($script, (strlen($url) + 7));
1709 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1711 $script = substr($script, (strlen($url) + 8));
1714 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1715 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1721 // Send a GET request
1722 function GET_URL ($script) {
1723 // Compile the script name
1724 $script = COMPILE_CODE($script);
1726 // Extract host name from script
1727 $host = EXTRACT_HOST($script);
1729 // Generate GET request header
1730 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1731 $request .= "Host: " . $host . "\r\n";
1732 $request .= "Referer: " . URL . "/admin.php\r\n";
1733 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1734 $request .= "Content-Type: text/plain\r\n";
1735 $request .= "Cache-Control: no-cache\r\n";
1736 $request .= "Connection: Close\r\n\r\n";
1738 // Send the raw request
1739 $response = SEND_RAW_REQUEST($host, $request);
1741 // Return the result to the caller function
1745 // Send a POST request
1746 function POST_URL ($script, $postData) {
1747 // Is postData an array?
1748 if (!is_array($postData)) {
1750 return array("", "", "");
1753 // Compile the script name
1754 $script = COMPILE_CODE($script);
1756 // Extract host name from script
1757 $host = EXTRACT_HOST($script);
1759 // Construct request
1760 $data = http_build_query($postData, '','&');
1762 // Generate POST request header
1763 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1764 $request .= "Host: " . $host . "\r\n";
1765 $request .= "Referer: " . URL . "/admin.php\r\n";
1766 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1767 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1768 $request .= "Content-length: " . strlen($data) . "\r\n";
1769 $request .= "Cache-Control: no-cache\r\n";
1770 $request .= "Connection: Close\r\n\r\n";
1773 // Send the raw request
1774 $response = SEND_RAW_REQUEST($host, $request);
1776 // Return the result to the caller function
1780 // Sends a raw request to another host
1781 function SEND_RAW_REQUEST ($host, $request) {
1785 $response = array("", "", "");
1787 // Default is not to use proxy
1790 // Are proxy settins set?
1791 if ((!empty($_CONFIG['proxy_host'])) && ($_CONFIG['proxy_port'] > 0)) {
1797 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1799 $fp = @fsockopen(COMPILE_CODE($_CONFIG['proxy_host']), $_CONFIG['proxy_port'], $errno, $errdesc, 30);
1801 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1805 if (!is_resource($fp)) {
1812 // Generate CONNECT request header
1813 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1814 $proxyTunnel .= "Host: ".$host."\r\n";
1816 // Use login data to proxy? (username at least!)
1817 if (!empty($_CONFIG['proxy_username'])) {
1819 $encodedAuth = base64_encode(COMPILE_CODE($_CONFIG['proxy_username']).":".COMPILE_CODE($_CONFIG['proxy_password']));
1820 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1823 // Add last new-line
1824 $proxyTunnel .= "\r\n";
1825 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1828 fputs($fp, $proxyTunnel);
1832 // No response received
1836 // Read the first line
1837 $resp = trim(fgets($fp, 10240));
1838 $respArray = explode(" ", $resp);
1839 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1840 // Invalid response!
1846 fputs($fp, $request);
1850 $response[] = trim(fgets($fp, 1024));
1856 // Skip first empty lines
1858 foreach ($resp as $idx => $line) {
1860 $line = trim($line);
1862 // Is this line empty?
1865 array_shift($response);
1867 // Abort on first non-empty line
1872 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1874 // Proxy agent found?
1875 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1876 // Proxy header detected, so remove two lines
1877 array_shift($response);
1878 array_shift($response);
1881 // Was the request successfull?
1882 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1883 // Not found / access forbidden
1884 $response = array("", "", "");
1890 // Taken from www.php.net eregi() user comments
1891 function VALIDATE_EMAIL($email) {
1893 $email = COMPILE_CODE($email);
1895 // Check first part of email address
1896 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1899 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1902 $regex = "^".$first."@".$domain."$";
1904 // Return check result
1905 return eregi($regex, $email);
1907 // Function taken from user comments on www.php.net / function eregi()
1908 function VALIDATE_URL ($URL, $compile=true) {
1909 // Trim URL a little
1910 $URL = trim(urldecode($URL));
1911 //* DEBUG: */ echo $URL."<br />";
1913 // Compile some chars out...
1914 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1915 //* DEBUG: */ echo $URL."<br />";
1917 // Check for the extension filter
1918 if (EXT_IS_ACTIVE("filter")) {
1919 // Use the extension's filter set
1920 return FILTER_VALIDATE_URL($URL, false);
1923 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1924 // https:// in front of the URLs
1925 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1928 function MEMBER_ACTION_LINKS($uid, $status="") {
1929 // Define all main targets
1930 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1932 // Begin of navigation links
1933 $eval = "\$OUT = \"[ ";
1935 foreach ($TARGETS as $tar) {
1936 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1937 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1938 if (($tar == "lock_user") && ($status == "LOCKED")) {
1939 // Locked accounts shall be unlocked
1940 $eval .= "UNLOCK_USER";
1942 // All other status is fine
1943 $eval .= strtoupper($tar);
1945 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1946 if (($tar == "lock_user") && ($status == "LOCKED")) {
1947 // Locked accounts shall be unlocked
1948 $eval .= "UNLOCK_USER";
1950 // All other status is fine
1951 $eval .= strtoupper($tar);
1953 $eval .= ".\"</A></SPAN> | ";
1956 // Finish navigation link
1957 $eval = substr($eval, 0, -7)."]\";";
1963 // Function for backward-compatiblity
1964 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1965 // Load it from the register extension
1966 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1968 // Generate an email link
1969 function CREATE_EMAIL_LINK($email, $table="admins") {
1970 // Default email link (INSECURE! Spammer can read this by harvester programs)
1971 $EMAIL = "mailto:".$email;
1973 // Check for several extensions
1974 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1975 // Create email link for contacting admin in guest area
1976 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1977 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1978 // Create email link for contacting a member within admin area (or later in other areas, too?)
1979 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1980 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1981 // Create email link to contact sponsor within admin area (or like the link above?)
1982 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1985 // Shall I close the link when there is no admin?
1986 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
1988 // Return email link
1991 // Generate a hash for extra-security for all passwords
1992 function generateHash ($plainText, $salt = "") {
1993 global $_CONFIG, $_SERVER;
1995 // Is the required extension "sql_patches" there and a salt is not given?
1996 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
1997 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
1998 return md5($plainText);
2001 // Do we miss an arry element here?
2002 if (!isset($_CONFIG['file_hash'])) {
2004 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2005 debug_print_backtrace();
2009 // When the salt is empty build a new one, else use the first x configured characters as the salt
2011 // Build server string
2012 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2015 $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'];
2018 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2020 // Calculate number for generating the code
2021 $a = time() + _ADD - 1;
2023 // Generate SHA1 sum from modula of number and the prime number
2024 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2025 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2026 $sha1 = scrambleString($sha1);
2027 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2028 //* DEBUG: */ $sha1b = descrambleString($sha1);
2029 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2031 // Generate the password salt string
2032 $salt = substr($sha1, 0, $_CONFIG['salt_length']);
2033 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2036 $salt = substr($salt, 0, $_CONFIG['salt_length']);
2037 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2041 return $salt.sha1($salt.$plainText);
2044 function scrambleString($str) {
2050 // Final check, in case of failture it will return unscrambled string
2051 if (strlen($str) > 40) {
2052 // The string is to long
2054 } elseif (strlen($str) == 40) {
2056 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2058 // Generate new numbers
2059 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2062 // Scramble string here
2063 //* DEBUG: */ echo "***Original=".$str."***<br />";
2064 for ($idx = 0; $idx < strlen($str); $idx++) {
2065 // Get char on scrambled position
2066 $char = substr($str, $scrambleNums[$idx], 1);
2068 // Add it to final output string
2069 $scrambled .= $char;
2072 // Return scrambled string
2073 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2077 function descrambleString($str) {
2079 // Scramble only 40 chars long strings
2080 if (strlen($str) != 40) return $str;
2082 // Load numbers from config
2083 $scrambleNums = explode(":", $_CONFIG['pass_scramble']);
2086 if (count($scrambleNums) != 40) return $str;
2088 // Begin descrambling
2089 $orig = str_repeat(" ", 40);
2090 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2091 for ($idx = 0; $idx < 40; $idx++) {
2092 $char = substr($str, $idx, 1);
2093 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2096 // Return scrambled string
2097 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2101 function genScrambleString($len) {
2102 // Prepare randomizer and array for the numbers
2103 mt_srand((double) microtime() * 1000000);
2104 $scrambleNumbers = array();
2106 // First we need to setup randomized numbers from 0 to 31
2107 for ($idx = 0; $idx < $len; $idx++) {
2109 $rand = mt_rand(0, ($len -1));
2111 // Check for it by creating more numbers
2112 while (array_key_exists($rand, $scrambleNumbers)) {
2113 $rand = mt_rand(0, ($len -1));
2117 $scrambleNumbers[$rand] = $rand;
2120 // So let's create the string for storing it in database
2121 $scrambleString = implode(":", $scrambleNumbers);
2122 return $scrambleString;
2124 // Append data like session ID or referal ID to the given URL which would
2125 // normally be stored in cookies
2126 function ADD_URL_DATA($URL) {
2130 // Determine URL binder
2132 if (strpos($URL, "?") !== false) $BIND = "&";
2134 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2135 // Cookies are not accepted
2136 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2137 // Cookie found in URL
2138 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2139 } elseif ((GET_EXT_VERSION("sql_patches") != '') && ($_CONFIG['def_refid'] > 0)) {
2140 // Not found! So let's set default here
2141 $ADD .= $BIND."refid=".$_CONFIG['def_refid'];
2144 // Is there already added data? Then change the binder
2145 if (!empty($ADD)) $BIND = "&";
2148 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2149 // Add session from URL
2150 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2152 // Add current session
2153 $ADD .= $BIND."PHPSESSID=".session_id();
2157 // Add all together and return it
2160 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2161 function generatePassString($passHash) {
2164 // Return vanilla password hash
2167 // Is a secret key and master salt already initialized?
2168 if ((!empty($_CONFIG['secret_key'])) && (!empty($_CONFIG['master_salt']))) {
2169 // Only calculate when the secret key is generated
2170 $newHash = ""; $start = 9;
2171 for ($idx = 0; $idx < 10; $idx++) {
2172 $part1 = hexdec(substr($passHash, $start, 4));
2173 $part2 = hexdec(substr($_CONFIG['secret_key'], $start, 4));
2174 $mod = dechex($idx);
2175 if ($part1 > $part2) {
2176 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2177 } elseif ($part2 > $part1) {
2178 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2180 $mod = substr(round($mod), 0, 4);
2181 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2182 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2187 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2188 $ret = generateHash($newHash, $_CONFIG['master_salt']);
2189 //* DEBUG: */ print($ret."<br />\n");
2192 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2193 $ret = md5($passHash);
2194 //* DEBUG: */ echo "++".$ret."++<br />\n";
2201 // Fix "deleted" cookies
2202 function FIX_DELETED_COOKIES ($cookies) {
2203 // Is this an array with entries?
2204 if ((is_array($cookies)) && (count($cookies) > 0)) {
2205 // Then check all cookies if they are marked as deleted!
2206 foreach ($cookies as $cookieName) {
2207 // Is the cookie set to "deleted"?
2208 if (get_session($cookieName) == "deleted") {
2209 set_session($cookieName, "");
2215 // Output error messages in a fasioned way and die...
2216 function mxchange_die ($msg) {
2219 // Load the message template
2220 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2223 include(PATH."inc/footer.php");
2229 // Display parsing time and number of SQL queries in footer
2230 function DISPLAY_PARSING_TIME_FOOTER() {
2231 global $startTime, $_CONFIG;
2232 $endTime = microtime(true);
2234 // Is the timer started?
2235 if (!isset($GLOBALS['startTime'])) {
2240 // "Explode" both times
2241 $start = explode(" ", $GLOBALS['startTime']);
2242 $end = explode(" ", $endTime);
2243 $runTime = $end[0] - $start[0];
2244 if ($runTime < 0) $runTime = 0;
2245 $runTime = TRANSLATE_COMMA($runTime);
2249 'runtime' => $runTime,
2250 'numSQLs' => ($_CONFIG['sql_count'] + 1),
2251 'numTemplates' => ($_CONFIG['num_templates'] + 1)
2254 // Load the template
2255 LOAD_TEMPLATE("show_timings", false, $content);
2258 // Unset/set session variables
2259 function set_session ($var, $value) {
2262 // Abort in CSS mode here
2263 if ($CSS == 1) return true;
2265 // Trim value and session variable
2266 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2268 // Is the session variable set?
2269 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2270 // Remove the session
2271 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2272 unset($_SESSION[$var]);
2273 return session_unregister($var);
2274 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2276 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2277 $_SESSION[$var] = $value;
2278 return session_register($var);
2279 } elseif (!empty($value)) {
2281 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2282 $_SESSION[$var] = $value;
2286 // Ignored (but valid)
2287 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2291 // Check wether a boolean constant is set
2292 // Taken from user comments in PHP documentation for function constant()
2293 function isBooleanConstantAndTrue($constName) { // : Boolean
2296 // Failed by default
2300 if (isset($constCache[$constName])) {
2302 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2303 $res = $constCache[$constName];
2306 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2307 if (defined($constName)) $res = (constant($constName) === true);
2310 $constCache[$constName] = $res;
2312 //* DEBUG: */ var_dump($res);
2318 // Check wether a session variable is set
2319 function isSessionVariableSet($var) {
2320 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2321 return (isset($_SESSION[$var]));
2323 // Returns wether the value of the session variable or NULL if not set
2324 function get_session($var) {
2327 // Default is not found! ;-)
2330 // Is the variable there or cached values?
2331 if (isset($cacheArray['session'][$var])) {
2332 // Get cached value (skips a lot SQL_ESCAPE() calles!
2333 $value = $cacheArray['session'][$var];
2334 } elseif (isSessionVariableSet($var)) {
2335 // Then get it secured!
2336 $value = SQL_ESCAPE($_SESSION[$var]);
2339 $cacheArray['session'][$var] = $value;
2345 // Send notification to admin
2346 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2347 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2349 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2351 // Send outdated way
2352 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2353 SEND_ADMIN_EMAILS($subject, $msg);
2356 // Destroy user session
2357 function destroy_user_session () {
2358 // Remove all user data from session
2359 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2361 // Merges an array together but only if both are arrays
2362 function merge_array ($array1, $array2) {
2363 // Are both an array?
2364 if ((is_array($array1)) && (is_array($array2))) {
2365 // Merge all together
2366 return array_merge($array1, $array2);
2367 } elseif (is_array($array1)) {
2368 // Return left array
2372 // Something wired happened here...
2373 print(__FUNCTION__.":<pre>");
2374 debug_print_backtrace();
2377 // Debug message logger
2378 function DEBUG_LOG ($file, $line, $message, $force=false) {
2379 // Is debug mode enabled?
2380 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2381 // Log this message away
2382 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2383 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename(__FILE__)."|".__LINE__."|".strip_tags($message)."\n");
2387 // Reads a directory with PHP files in and gets only files back
2388 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2392 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2395 while ($baseFile = readdir($dirPointer)) {
2396 // Load file only if extension is active
2398 $file = $baseDir.$baseFile;
2400 // Is this a valid reset file?
2401 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2402 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2403 // Remove both for extension name
2404 $extName = substr($baseFile, strlen($prefix), -4);
2407 $extId = GET_EXT_ID($extName);
2409 // Is the extension valid and active?
2410 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2411 // Then add this file
2413 } elseif ($extId == 0) {
2414 // Add non-extension files as well
2421 closedir($dirPointer);
2426 // Return array with include files
2429 // Load more reset scripts
2430 function RESET_ADD_INCLUDES () {
2433 // Is the reset set or old sql_patches?
2434 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2439 // Get more daily reset scripts
2440 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2443 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2445 // Create current week mark
2446 $currWeek = date("W", time());
2449 if ($_CONFIG['last_week'] != $currWeek) {
2450 // Include weekly reset scripts
2451 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2454 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2457 // Create current month mark
2458 $currMonth = date("m", time());
2461 if ($_CONFIG['last_month'] != $currMonth) {
2462 // Include monthly reset scripts
2463 $INC_POOL = array_merge($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2466 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2472 // Handle extra values
2473 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2474 // Default is the value itself
2477 // Do we have a special filter function?
2478 if (!empty($filterFunction)) {
2479 // Does the filter function exist?
2480 if (function_exists($filterFunction)) {
2481 // Do we have extra parameters here?
2482 if (!empty($extraValue)) {
2483 // Put both parameters in one new array by default
2484 $args = array($value, $extraValue);
2486 // If we have an array simply use it and pre-extend it with our value
2487 if (is_array($extraValue)) {
2488 // Make the new args array
2489 $args = array_merge(array($value), $extraValue);
2492 // Call the multi-parameter call-back
2493 $ret = call_user_func_array($filterFunction, $args);
2495 // One parameter call
2496 $ret = call_user_func($filterFunction, $value);
2504 // Check if given FQFN is a readable file
2505 function FILE_READABLE($fqfn) {
2507 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2509 // Converts timestamp selections into a timestamp
2510 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2511 // Init test variable
2514 // Get last three chars
2515 $TEST = substr($id, -3);
2517 // Improved way of checking! :-)
2518 if (in_array($TEST, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2519 // Found a multi-selection for timings?
2520 $TEST = substr($id, 0, -3);
2521 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)) {
2522 // Generate timestamp
2523 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
2524 $DATA[] = "$TEST='".$POST[$TEST]."'";
2526 // Remove data from array
2527 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2528 unset($POST[$TEST."_".$rem]);
2532 unset($id); $skip = true; $TEST2 = $TEST;
2535 // Process this entry
2536 $skip = false; $TEST2 = "";
2539 // Reverts the german decimal comma into Computer decimal dot
2540 function REVERT_COMMA ($str) {
2541 // Default float is not a float... ;-)
2544 // Which language is selected?
2545 switch (GET_LANGUAGE()) {
2546 case "de": // German language
2547 // Remove german thousand dots first
2548 $str = str_replace(".", "", $str);
2550 // Replace german commata with decimal dot and cast it
2551 $float = (float)str_replace(",", ".", $str);
2554 default: // US and so on
2555 // Remove thousand dots first and cast
2556 $float = (float)str_replace(",", "", $str);
2563 // Handle menu-depending failed logins and return the rendered content
2564 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2565 // Default output is empty ;-)
2568 // Is the session data set?
2569 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2570 // Ignore zero values
2571 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2572 // Non-guest has login failtures found, get both data and prepare it for template
2573 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2575 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2576 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2580 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2583 // Reset session data
2584 set_session('mxchange_'.$accessLevel.'_failtures', "");
2585 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2588 // Return rendered content
2592 function REBUILD_CACHE ($cache, $inc="") {
2593 global $cacheInstance, $_CONFIG, $CSS;
2595 // Shall I remove the cache file?
2596 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2598 if ($cacheInstance->cache_file($cache, true)) {
2600 $cacheInstance->cache_destroy();
2603 // Include file given?
2606 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2608 // Is the include there?
2609 if (FILE_READABLE($fqfn)) {
2610 // And rebuild it from scratch
2613 // Include not found!
2614 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2619 // Purge admin menu cache
2620 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2621 global $_CONFIG, $cacheInstance;
2623 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2624 if (!EXT_IS_ACTIVE("cache")) {
2625 // Cache extension not active
2627 } elseif (!is_object($cacheInstance)) {
2628 // No cache instance!
2629 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2631 } elseif ((!isset($_CONFIG['cache_admin_menu'])) || ($_CONFIG['cache_admin_menu'] == "N")) {
2632 // Caching disabled (currently experiemental!)
2636 // Experiemental feature!
2637 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2639 // Translates the "pool type" into human-readable
2640 function TRANSLATE_POOL_TYPE ($type) {
2641 // Default type is unknown
2642 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2644 // Generate constant
2645 $constName = sprintf("POOL_TYPE_%s", $type);
2648 if (defined($constName)) {
2650 $translated = constant($constName);
2653 // Return "translation"
2656 // "Getter" for remote IP number
2657 function GET_REMOTE_ADDR () {
2658 // Get remote ip from environment
2659 $remoteAddr = getenv('REMOTE_ADDR');
2661 // Is removeip installed?
2662 if (EXT_IS_ACTIVE("removeip")) {
2663 // Then anonymize it
2664 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2670 // "Getter" for remote hostname
2671 function GET_REMOTE_HOST () {
2672 // Get remote ip from environment
2673 $remoteHost = getenv('REMOTE_HOST');
2675 // Is removeip installed?
2676 if (EXT_IS_ACTIVE("removeip")) {
2677 // Then anonymize it
2678 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2684 // "Getter" for user agent
2685 function GET_USER_AGENT () {
2686 // Get remote ip from environment
2687 $userAgent = getenv('HTTP_USER_AGENT');
2689 // Is removeip installed?
2690 if (EXT_IS_ACTIVE("removeip")) {
2691 // Then anonymize it
2692 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2698 // "Getter" for referer
2699 function GET_REFERER () {
2700 // Get remote ip from environment
2701 $referer = getenv('HTTP_REFERER');
2703 // Is removeip installed?
2704 if (EXT_IS_ACTIVE("removeip")) {
2705 // Then anonymize it
2706 $referer = GET_ANONYMOUS_REFERER($referer);
2713 // Adds a bonus mail to the queue
2714 // This is a high-level function!
2715 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2716 // Use mode from data if not set and availble ;-)
2717 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2719 // Generate receiver list
2720 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2723 if (!empty($RECEIVER)) {
2724 // Add bonus mail to queue
2725 ADD_BONUS_MAIL_TO_QUEUE(
2737 // Mail inserted into bonus pool
2738 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_BONUS_SEND);
2739 } elseif ($output) {
2740 // More entered than can be reached!
2741 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_MORE_SELECTED);
2744 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2747 // Determines referal id and sets it
2748 function DETERMINE_REFID () {
2749 global $_CONFIG, $CLICK, $_SERVER;
2751 // Check if refid is set
2752 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2753 // The variable user comes from the click-counter script click.php and we only accept this here
2754 $GLOBALS['refid'] = bigintval($_GET['user']);
2755 } elseif (!empty($_POST['refid'])) {
2756 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2757 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2758 } elseif (!empty($_GET['refid'])) {
2759 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2760 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2761 } elseif (!empty($_GET['ref'])) {
2762 // Set refid=ref (the referal link uses such variable)
2763 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2764 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2765 // Set session refid als global
2766 $GLOBALS['refid'] = bigintval(get_session('refid'));
2767 } elseif ((GET_EXT_VERSION("sql_patches") != "") && ($_CONFIG['def_refid'] > 0)) {
2768 // Set default refid as refid in URL
2769 $GLOBALS['refid'] = bigintval($_CONFIG['def_refid']);
2770 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && ($_CONFIG['select_user_zero_refid']) == "Y") {
2771 // Select a random user which has confirmed enougth mails
2772 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2774 // No default ID when sql_patches is not installed or none set
2775 $GLOBALS['refid'] = 0;
2778 // Set cookie when default refid > 0
2779 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (isset($_CONFIG['def_refid'])) && ($_CONFIG['def_refid'] > 0))) {
2781 set_session('refid', $GLOBALS['refid']);
2785 // Destroys the admin session
2786 function DESTROY_ADMIN_SESSION () {
2787 // Kill maybe existing session variables including array elements
2788 set_session('admin_login' , "");
2789 set_session('admin_md5' , "");
2790 set_session('admin_last' , "");
2791 set_session('admin_to' , "");
2793 // Destroy session and return status
2794 return @session_destroy();
2797 //////////////////////////////////////////////////
2799 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2801 //////////////////////////////////////////////////
2803 if (!function_exists('html_entity_decode')) {
2804 // Taken from documentation on www.php.net
2805 function html_entity_decode($string) {
2806 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2807 $trans_tbl = array_flip($trans_tbl);
2808 return strtr($string, $trans_tbl);